auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static Block spatialPartitions(KdbTree kdbTree, Rectangle envelope) { Map<Integer, Rectangle> partitions = kdbTree.findIntersectingLeaves(envelope); if (partitions.isEmpty()) { return EMPTY_ARRAY_OF_INTS; } boolean point = (envelope.getWidth() == 0 && envelope.getHeight() == 0); if (point) { for (Map.Entry<Integer, Rectangle> partition : partitions.entrySet()) { if (envelope.getXMin() < partition.getValue().getXMax() && envelope.getYMin() < partition.getValue().getYMax()) { BlockBuilder blockBuilder = IntegerType.INTEGER.createFixedSizeBlockBuilder(1); blockBuilder.writeInt(partition.getKey()); return blockBuilder.build(); } } throw new VerifyException(format("Cannot find half-open partition extent for a point: (%s, %s)", envelope.getXMin(), envelope.getYMin())); } BlockBuilder blockBuilder = IntegerType.INTEGER.createFixedSizeBlockBuilder(partitions.size()); for (Integer id : partitions.keySet()) { blockBuilder.writeInt(id); } return blockBuilder.build(); }

Target:
private static Block spatialPartitions(KdbTree kdbTree, Rectangle envelope) { Map<Integer, Rectangle> partitions = kdbTree.findIntersectingLeaves(envelope); if (partitions.isEmpty()) { return EMPTY_ARRAY_OF_INTS; } boolean point = (envelope.getWidth() == 0 && envelope.getHeight() == 0); if (point) { for (Map.Entry<Integer, Rectangle> partition : partitions.entrySet()) { if (envelope.getXMin() < partition.getValue().getXMax() && envelope.getYMin() < partition.getValue().getYMax()) { BlockBuilder blockBuilder = IntegerType.INTEGER.createFixedSizeBlockBuilder(1); blockBuilder.writeInt(partition.getKey()); return blockBuilder.build(); } } throw new VerifyException(format("Cannot find half-open partition extent for a point: (%s, %s)", envelope.getXMin(), envelope.getYMin())); } BlockBuilder blockBuilder = IntegerType.INTEGER.createFixedSizeBlockBuilder(partitions.size()); for (int id : partitions.keySet()) { blockBuilder.writeInt(id); } return blockBuilder.build(); }
Source:
public CompletableFuture<?> execute() { CompletableFuture<Void> counter = new CompletableFuture<>(); delete(builderLedgerId, new SyncDeleteCallback(), counter); return counter; }

Target:
public CompletableFuture<Void> execute() { CompletableFuture<Void> future = new CompletableFuture<>(); SyncDeleteCallback result = new SyncDeleteCallback(future); delete(builderLedgerId, result); return future; }
Source:
public NotificationsPrefs() { soundsEnabled = new SimpleBooleanProperty(true); mentionSoundEnabled = new SimpleBooleanProperty(true); infoSoundEnabled = new SimpleBooleanProperty(true); warnSoundEnabled = new SimpleBooleanProperty(true); errorSoundEnabled = new SimpleBooleanProperty(true); eventNotificationsEnabled = new SimpleBooleanProperty(true); toastPosition = new SimpleObjectProperty<>(ToastPosition.BOTTOM_RIGHT); friendOnlineToastEnabled = new SimpleBooleanProperty(true); friendOfflineToastEnabled = new SimpleBooleanProperty(true); ladder1v1ToastEnabled = new SimpleBooleanProperty(true); friendOnlineSoundEnabled = new SimpleBooleanProperty(true); friendOfflineSoundEnabled = new SimpleBooleanProperty(true); friendJoinsGameSoundEnabled = new SimpleBooleanProperty(true); friendPlaysGameSoundEnabled = new SimpleBooleanProperty(true); friendPlaysGameToastEnabled = new SimpleBooleanProperty(true); friendJoinsGameToastEnabled = new SimpleBooleanProperty(true); privateMessageSoundEnabled = new SimpleBooleanProperty(true); privateMessageToastEnabled = new SimpleBooleanProperty(true); notifyOnAtMentionOnlyEnabled = new SimpleBooleanProperty(false); toastScreen = new SimpleIntegerProperty(0); toastDisplayTime = new SimpleIntegerProperty(5000); afterGameReviewEnabled = new SimpleBooleanProperty(true); }

Target:
public NotificationsPrefs() { soundsEnabled = new SimpleBooleanProperty(true); mentionSoundEnabled = new SimpleBooleanProperty(true); infoSoundEnabled = new SimpleBooleanProperty(true); warnSoundEnabled = new SimpleBooleanProperty(true); errorSoundEnabled = new SimpleBooleanProperty(true); transientNotificationsEnabled = new SimpleBooleanProperty(true); toastPosition = new SimpleObjectProperty<>(ToastPosition.BOTTOM_RIGHT); friendOnlineToastEnabled = new SimpleBooleanProperty(true); friendOfflineToastEnabled = new SimpleBooleanProperty(true); ladder1v1ToastEnabled = new SimpleBooleanProperty(true); friendOnlineSoundEnabled = new SimpleBooleanProperty(true); friendOfflineSoundEnabled = new SimpleBooleanProperty(true); friendJoinsGameSoundEnabled = new SimpleBooleanProperty(true); friendPlaysGameSoundEnabled = new SimpleBooleanProperty(true); friendPlaysGameToastEnabled = new SimpleBooleanProperty(true); friendJoinsGameToastEnabled = new SimpleBooleanProperty(true); privateMessageSoundEnabled = new SimpleBooleanProperty(true); privateMessageToastEnabled = new SimpleBooleanProperty(true); notifyOnAtMentionOnlyEnabled = new SimpleBooleanProperty(false); toastScreen = new SimpleIntegerProperty(0); toastDisplayTime = new SimpleIntegerProperty(5000); afterGameReviewEnabled = new SimpleBooleanProperty(true); }
Source:
public String eventDlOpen() { return "lttng_ust_dl:dlopen"; }

Target:
public String eventDlOpen() { return "ust_dl:dlopen"; }
Source:
public void deleteMarkers(IMarker[] markers) { for (IMarker marker : markers) { removeMarker(marker); } }

Target:
public void deleteMarkers(IMarker[] markers) { for (IMarker marker : markers) { deleteMarker(marker); } }
Source:
private DBCursor getOrderedCursor(DBObject query) { return collection.find(query).addSpecial("$orderby", new BasicDBObject(MongoConstants.ID, 1)); }

Target:
private DBCursor getOrderedCursor(DBObject query) { return collection.find(query).sort(new MongoSortBuilder().ascending(MongoConstants.ID).build()); }
Source:
public static Member getMember(Class<?> clazz, String property, ElementType elementType) { Contracts.assertNotNull( clazz, MESSAGES.classCannotBeNull() ); if ( property == null || property.length() == 0 ) { throw log.getPropertyNameCannotBeNullOrEmptyException(); } if ( !( ElementType.FIELD.equals( elementType ) || ElementType.METHOD.equals( elementType ) ) ) { throw log.getElementTypeHasToBeFieldOrMethodException(); } Member member = null; if ( ElementType.FIELD.equals( elementType ) ) { GetDeclaredField action = GetDeclaredField.action( clazz, property ); if ( System.getSecurityManager() != null ) { member = AccessController.doPrivileged( action ); } else { member = action.run(); } } else { String methodName = property.substring( 0, 1 ).toUpperCase() + property.substring( 1 ); for ( String prefix : ReflectionHelper.PROPERTY_ACCESSOR_PREFIXES ) { GetMethod action = GetMethod.action( clazz, prefix + methodName ); if ( System.getSecurityManager() != null ) { member = AccessController.doPrivileged( action ); } else { member = action.run(); } if ( member != null ) { break; } } } return member; }

Target:
private Member getMember(Class<?> clazz, String property, ElementType elementType) { Contracts.assertNotNull( clazz, MESSAGES.classCannotBeNull() ); if ( property == null || property.length() == 0 ) { throw log.getPropertyNameCannotBeNullOrEmptyException(); } if ( !( ElementType.FIELD.equals( elementType ) || ElementType.METHOD.equals( elementType ) ) ) { throw log.getElementTypeHasToBeFieldOrMethodException(); } Member member = null; if ( ElementType.FIELD.equals( elementType ) ) { GetDeclaredField action = GetDeclaredField.action( clazz, property ); if ( System.getSecurityManager() != null ) { member = AccessController.doPrivileged( action ); } else { member = action.run(); } } else { String methodName = property.substring( 0, 1 ).toUpperCase() + property.substring( 1 ); for ( String prefix : ReflectionHelper.PROPERTY_ACCESSOR_PREFIXES ) { GetMethod action = GetMethod.action( clazz, prefix + methodName ); if ( System.getSecurityManager() != null ) { member = AccessController.doPrivileged( action ); } else { member = action.run(); } if ( member != null ) { break; } } } return member; }
Source:
public long length() throws IOException { return exists() ? writeRaf().length() : -1; }

Target:
public long length() throws IOException { return exists() ? reader().length() : -1; }
Source:
public void visitClass(ClassTree tree) { ClassType classType = ((ClassTreeImpl) tree).classType(); if (tree.name() != null) { tree.name().symbol().get().addType(classType); } for (MethodDeclarationTree methodDeclarationTree : tree.methods()) { Tree name = methodDeclarationTree.name(); if (name.is(Tree.Kind.IDENTIFIER_NAME)) { Scope classScope = getContext().getSymbolModel().getScope(tree); classType.addMethod((IdentifierTree) name, FunctionType.create(methodDeclarationTree), classScope); } } super.visitClass(tree); }

Target:
public void visitClass(ClassTree tree) { ClassType classType = ((ClassTreeImpl) tree).classType(); if (tree.name() != null) { tree.name().symbol().get().addType(classType); } for (Tree element : tree.elements()) { Tree name; if (element.is(Tree.Kind.GET_METHOD, Tree.Kind.SET_METHOD)) { name = ((AccessorMethodDeclarationTree) element).name(); } else if (element.is(Tree.Kind.METHOD, Tree.Kind.GENERATOR_METHOD)) { name = ((MethodDeclarationTree) element).name(); } else { continue; } if (name.is(Tree.Kind.PROPERTY_IDENTIFIER)) { Scope classScope = getContext().getSymbolModel().getScope(tree); classType.addMethod((IdentifierTree) name, FunctionType.create((FunctionTree) element), classScope); } } super.visitClass(tree); }
Source:
public void bindView(View view, Context context, Cursor cursor) { view.setBackgroundResource(R.drawable.selectable_item_background); TextView title = (TextView) view.findViewById(R.id.page_list_item_title); ImageView thumbnail = (ImageView) view.findViewById(R.id.page_list_item_image); SavedPage entry = SavedPage.PERSISTENCE_HELPER.fromCursor(cursor); title.setText(entry.getTitle().getDisplayText()); view.setTag(entry); if (app.isImageDownloadEnabled()) { Picasso.with(getActivity()) .load(cursor.getString(SavedPageContentProvider.COL_INDEX_IMAGE)) .placeholder(R.drawable.ic_pageimage_placeholder) .error(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } else { Picasso.with(getActivity()) .load(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } }

Target:
public void bindView(View view, Context context, Cursor cursor) { TextView title = (TextView) view.findViewById(R.id.page_list_item_title); ImageView thumbnail = (ImageView) view.findViewById(R.id.page_list_item_image); SavedPage entry = SavedPage.PERSISTENCE_HELPER.fromCursor(cursor); title.setText(entry.getTitle().getDisplayText()); view.setTag(entry); if (app.isImageDownloadEnabled()) { Picasso.with(getActivity()) .load(cursor.getString(SavedPageContentProvider.COL_INDEX_IMAGE)) .placeholder(R.drawable.ic_pageimage_placeholder) .error(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } else { Picasso.with(getActivity()) .load(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } }
Source:
private void cancelCurrentBuilds(AbstractProject<?, ?> project, Integer prId) { if (overrideGlobal) { return; } Queue queue = Jenkins.getInstance().getQueue(); for (Queue.Item item : queue.getItems(project)) { GhprbCause cause = Ghprb.getCause(item); if (cause == null) { continue; } if (cause.getPullID() == prId) { queue.cancel(item); } } RunList<?> runs = project.getBuilds(); for (Run<?, ?> run : runs) { if (!run.isBuilding() && !run.hasntStartedYet()) { break; } GhprbCause cause = Ghprb.getCause(run); if (cause == null) { continue; } if (cause.getPullID() == prId) { run.addAction(this); run.getExecutor().interrupt(Result.ABORTED); } } }

Target:
private void cancelCurrentBuilds(AbstractProject<?, ?> project, Integer prId) { if (overrideGlobal) { return; } Queue queue = Jenkins.getInstance().getQueue(); for (Queue.Item item : queue.getItems(project)) { GhprbCause qcause = null; for (Cause cause : item.getCauses()){ if (cause instanceof GhprbCause) { qcause = (GhprbCause) cause; } } if (qcause == null) { continue; } if (qcause.getPullID() == prId) { try { queue.cancel(item); } catch (Exception e) { logger.log(Level.SEVERE, "Unable to cancel queued build", e); } } } RunList<?> runs = project.getBuilds(); for (Run<?, ?> run : runs) { if (!run.isBuilding() && !run.hasntStartedYet()) { break; } GhprbCause cause = Ghprb.getCause(run); if (cause == null) { continue; } if (cause.getPullID() == prId) { try { run.addAction(this); run.getExecutor().interrupt(Result.ABORTED); } catch (Exception e) { run.getActions().remove(this); logger.log(Level.SEVERE, "Unable to interrupt build!", e); } } } }
Source:
public void render(Context context, U value, SafeHtmlBuilder sb) { if (value != null) { sb.appendHtmlConstant("<span title=\"" + titleProvider_.get(value) + "\" " + "style=\"cursor: pointer;\">"); sb.append(image_.getSafeHtml()); sb.appendHtmlConstant("</span>"); } }

Target:
public void render(Context context, U value, SafeHtmlBuilder sb) { if (value != null) { sb.append(TEMPLATES.render(image_.getSafeHtml(), titleProvider_.get(value))); } }
Source:
void setEmailUserId(@NonNull String id) { boolean changed = id != null && !id.equals(emailUserId); emailUserId = id; if (changed) observable.notifyChange(this); }

Target:
void setEmailUserId(@NonNull String id) { boolean changed = false; if (id == null) changed = emailUserId != null; else if (!id.equals(emailUserId)) changed = true; emailUserId = id; if (changed) observable.notifyChange(this); }
Source:
public ProcessedPoms process(final InternalNIOCompilationRequest req) { Path mainPom = Paths.get(req.getInfo().getPrjPath().toString(), POM_NAME); if (!Files.isReadable(mainPom)) { return new ProcessedPoms(Boolean.FALSE, Collections.emptyList()); } PomPlaceHolder placeHolder = editor.readSingle(mainPom); Boolean isPresent = isPresent(placeHolder); if (placeHolder.isValid() && !isPresent) { List<String> pomsList = new ArrayList(); InternalNIOMavenUtils.searchPoms(Paths.get(req.getInfo().getPrjPath().toString()), pomsList); if (pomsList.size() > 0) { processFoundedPoms(pomsList, req); } return new ProcessedPoms(Boolean.TRUE, pomsList); } else { return new ProcessedPoms(Boolean.FALSE, Collections.emptyList()); } }

Target:
public ProcessedPoms process(final InternalNIOCompilationRequest req) { Path mainPom = Paths.get(req.getInfo().getPrjPath().toString(), POM_NAME); if (!Files.isReadable(mainPom)) { return new ProcessedPoms(Boolean.FALSE, Collections.emptyList()); } PomPlaceHolder placeHolder = editor.readSingle(mainPom); Boolean isPresent = isPresent(placeHolder); if (placeHolder.isValid() && !isPresent) { List<String> pomsList = new ArrayList<>(); InternalNIOMavenUtils.searchPoms(Paths.get(req.getInfo().getPrjPath().toString()), pomsList); if (pomsList.size() > 0) { processFoundPoms(pomsList, req); } return new ProcessedPoms(Boolean.TRUE, pomsList); } else { return new ProcessedPoms(Boolean.FALSE, Collections.emptyList()); } }
Source:
public void destroy(long entityId) { if (!entityManager.idLoaded(entityId)) { return; } EntityRef ref = createEntityRef(entityId); if (entityManager.getEventSystem() != null) { entityManager.getEventSystem().send(ref, BeforeDeactivateComponent.newInstance()); entityManager.getEventSystem().send(ref, BeforeRemoveComponent.newInstance()); } entityManager.notifyComponentRemovalAndEntityDestruction(entityId, ref); destroy(ref); }

Target:
public void destroy(long entityId) { if (!entityManager.idLoaded(entityId)) { return; } EntityRef ref = createEntityRef(entityId); EventSystem eventSystem = entityManager.getEventSystem(); if (eventSystem != null) { eventSystem.send(ref, BeforeDeactivateComponent.newInstance()); eventSystem.send(ref, BeforeRemoveComponent.newInstance()); } entityManager.notifyComponentRemovalAndEntityDestruction(entityId, ref); destroy(ref); }
Source:
private static boolean isValidExternalPath(IPath path) { if (path != null) { if (UNCPathConverter.isUNC(path.toString())) { return true; } File file = path.toFile(); if (file != null) { return file.exists(); } } return false; }

Target:
private static boolean isValidExternalPath(IPath path) { if (path != null) { if (path.isUNC()) { return true; } File file = path.toFile(); if (file != null) { return file.exists(); } } return false; }
Source:
public void configure(Map stormConf, JsonNode paramNode) { JsonNode node = paramNode.get("urlFilters"); if (node != null && node.isArray()) { rules = new ArrayList<RegexRule>(); ArrayNode array = (ArrayNode) node; for (JsonNode urlFilterNode : array) { try { RegexRule rule = createRule(urlFilterNode.asText()); if (rule != null) { rules.add(rule); } } catch (IOException e) { LOG.error("There was an error reading regex filter {}", urlFilterNode.asText()); e.printStackTrace(); } } } else { JsonNode filenameNode = paramNode.get("regexFilterFile"); String rulesFileName; if (filenameNode != null) { rulesFileName = filenameNode.textValue(); } else { rulesFileName = "default-regex-filters.txt"; } rules = readRules(rulesFileName); } }

Target:
public void configure(Map stormConf, JsonNode paramNode) { JsonNode node = paramNode.get("urlFilters"); if (node != null && node.isArray()) { rules = readRules((ArrayNode) node); } else { JsonNode filenameNode = paramNode.get("regexFilterFile"); String rulesFileName; if (filenameNode != null) { rulesFileName = filenameNode.textValue(); } else { rulesFileName = "default-regex-filters.txt"; } rules = readRules(rulesFileName); } }
Source:
public static void afterClass() { try { if (ConfigUtils.isDomain()) { CLI.reloadServers(); } else { CLI.reload(); } } finally { CLI.closeClient(); } }

Target:
public static void afterClass() { cli.closeClient(); }
Source:
public void unbind( DataServiceClientService service ) { if ( dataServiceClientService.compareAndSet( service, null ) ) { dataServiceClientService.set( null ); ThinConnection.localClient = null; } }

Target:
public void unbind( DataServiceClientService service ) { if ( dataServiceClientService.compareAndSet( service, null ) ) { ThinConnection.localClient = null; } }
Source:
public CisConversionResult convertToPdf(InputStream inputStream, String filename, ConversionOption conversionOption) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("inputStream == null"); } File tmpFile = null; try { tmpFile = getUniqueFile(); Files.copy(inputStream, tmpFile.toPath()); return convertToPdf(tmpFile, filename, conversionOption); } catch (IOException e) { LOGGER.error("Fout bij conversie van bestand " + filename + "naar PDF", e); throw createCisConversionException(e); } finally { FileUtil.deleteFile(tmpFile); tmpFile = null; } }

Target:
public CisConversionResult convertToPdf(InputStream inputStream, String filename, ConversionOption conversionOption) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("inputStream == null"); } File tmpFile = null; try { tmpFile = getUniqueFile(); Files.copy(inputStream, tmpFile.toPath()); return convertToPdf(tmpFile, filename, conversionOption); } catch (IOException e) { LOGGER.error("Fout bij conversie van bestand " + filename + "naar PDF", e); throw createCisConversionException(e); } finally { com.aspose.pdf.MemoryCleaner.clearAllTempFiles(); FileUtil.deleteFile(tmpFile); tmpFile = null; } }
Source:
public static Department findDepartment(HttpServletRequest request) throws ServiceException{ did = Integer.parseInt(request.getParameter("did")); return SQLSource.interact(new SQLInteractionInterface<Department>() { @Override public Department run(Connection connection) throws ServiceException, SQLException{ return Department.lookup(connection, did); } }); }

Target:
public static Department findDepartment(HttpServletRequest request) throws ServiceException { String deptID = request.getParameter("did"); if (deptID == null) { throw new ServiceException(ServiceStatus.MALFORMED_REQUEST); } final int did = Integer.parseInt(deptID); return SQLSource.interact(new SQLInteractionInterface<Department>() { @Override public Department run(Connection connection) throws ServiceException, SQLException { return Department.lookup(connection, did); } }); }
Source:
protected void sendAppendRequest(Connection connection, MemberState member, AppendRequest request) { long timestamp = System.currentTimeMillis(); connection.<AppendRequest, AppendResponse>send(request).whenComplete((response, error) -> { context.checkThread(); if (!request.entries().isEmpty()) { member.completeAppend(System.currentTimeMillis() - timestamp); } else { member.completeAppend(); } if (open) { if (error == null) { LOGGER.debug("{} - Received from {}", context.getCluster().member().address(), response, member.getMember().address()); handleAppendResponse(member, request, response); } else { handleAppendResponseFailure(member, request, error); } } }); updateNextIndex(member, request); if (!request.entries().isEmpty() && hasMoreEntries(member)) { appendEntries(member); } }

Target:
protected void sendAppendRequest(Connection connection, MemberState member, AppendRequest request) { long timestamp = System.nanoTime(); connection.<AppendRequest, AppendResponse>send(request).whenComplete((response, error) -> { context.checkThread(); if (!request.entries().isEmpty()) { member.completeAppend(System.nanoTime() - timestamp); } else { member.completeAppend(); } if (open) { if (error == null) { LOGGER.debug("{} - Received from {}", context.getCluster().member().address(), response, member.getMember().address()); handleAppendResponse(member, request, response); } else { handleAppendResponseFailure(member, request, error); } } }); updateNextIndex(member, request); if (!request.entries().isEmpty() && hasMoreEntries(member)) { appendEntries(member); } }
Source:
public void setUp() { converterWithPrefix = new EventConverter(new ObjectMapper(), null, "druid"); converterWithSpacePrefix = new EventConverter(new ObjectMapper(), null, "legendary druid"); converterWithoutPrefix = new EventConverter(new ObjectMapper(), null, null); }

Target:
public void setUp() { converterWithNamespacePrefix = new EventConverter(new ObjectMapper(), null, "druid"); converterWithNamespacePrefixContainingSpace = new EventConverter(new ObjectMapper(), null, "legendary druid"); converterWithoutNamespacePrefix = new EventConverter(new ObjectMapper(), null, null); }
Source:
public void testStopSequenceValidation() { StopTimeSequanceValidator stopSequenceValidator = new StopTimeSequanceValidator(); stopTimeUpdate.setStopSequence(1); tripUpdate.addStopTimeUpdate(stopTimeUpdate); stopTimeUpdate.setStopSequence(5); tripUpdate.addStopTimeUpdate(stopTimeUpdate); feedEntity.setTripUpdate(tripUpdate); feedMessage.setEntity(0, feedEntity); errors = stopSequenceValidator.validate(gtfsData, feedMessage.build()); assertNull(errors); stopTimeUpdate.setStopSequence(3); tripUpdate.addStopTimeUpdate(stopTimeUpdate); feedEntity.setTripUpdate(tripUpdate); feedMessage.setEntity(0, feedEntity); errors = stopSequenceValidator.validate(gtfsData, feedMessage.build()); assertEquals(1, errors.getOccurrenceList().size()); clearAndInitRequiredFeedFields(); }

Target:
public void testStopSequenceValidation() { StopTimeSequanceValidator stopSequenceValidator = new StopTimeSequanceValidator(); GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdateBuilder = GtfsRealtime.TripUpdate.StopTimeUpdate.newBuilder(); GtfsRealtime.TripDescriptor.Builder tripDescriptorBuilder = GtfsRealtime.TripDescriptor.newBuilder(); tripUpdateBuilder.setTrip(tripDescriptorBuilder.build()); feedEntityBuilder.setTripUpdate(tripUpdateBuilder.build()); feedMessageBuilder.setEntity(0, feedEntityBuilder.build()); stopTimeUpdateBuilder.setStopSequence(1); tripUpdateBuilder.addStopTimeUpdate(stopTimeUpdateBuilder.build()); stopTimeUpdateBuilder.setStopSequence(5); tripUpdateBuilder.addStopTimeUpdate(stopTimeUpdateBuilder.build()); feedEntityBuilder.setTripUpdate(tripUpdateBuilder.build()); feedMessageBuilder.setEntity(0, feedEntityBuilder.build()); assertEquals(2, feedMessageBuilder.getEntity(0).getTripUpdate().getStopTimeUpdateCount()); errors = stopSequenceValidator.validate(gtfsData, feedMessageBuilder.build()); assertNull(errors); stopTimeUpdateBuilder.setStopSequence(3); tripUpdateBuilder.addStopTimeUpdate(stopTimeUpdateBuilder.build()); feedEntityBuilder.setTripUpdate(tripUpdateBuilder.build()); feedMessageBuilder.setEntity(0, feedEntityBuilder.build()); assertEquals(3, feedMessageBuilder.getEntity(0).getTripUpdate().getStopTimeUpdateCount()); errors = stopSequenceValidator.validate(gtfsData, feedMessageBuilder.build()); assertEquals(1, errors.getOccurrenceList().size()); clearAndInitRequiredFeedFields(); }
Source:
public void testBuildConfigs() { ViewerSorter comparator = ProjectViewerComparator.createProjectTreeSorter(new OpenShiftExplorerLabelProvider()); IBuildConfig config1 = Mockito.mock(IBuildConfig.class); when(config1.getKind()).thenReturn(ResourceKind.BUILD_CONFIG); when(config1.getName()).thenReturn("n"); when(config1.getSourceURI()).thenReturn("c1"); when(config1.toString()).thenReturn("z"); ObservableTreeItem i1 = new ObservableTreeItem(config1); IBuildConfig config2 = Mockito.mock(IBuildConfig.class); when(config2.getKind()).thenReturn(ResourceKind.BUILD_CONFIG); when(config2.getName()).thenReturn("n"); when(config2.getSourceURI()).thenReturn("c2"); when(config2.toString()).thenReturn("x"); ObservableTreeItem i2 = new ObservableTreeItem(config2); assertTrue(comparator.compare(null, i1, i2) < 0); }

Target:
public void testBuildConfigs() { ViewerComparator comparator = ProjectViewerComparator.createProjectTreeSorter(new OpenShiftExplorerLabelProvider()); ObservableTreeItem i1 = new ObservableTreeItem(mockBuildConfig("n", "c1", "z")); ObservableTreeItem i2 = new ObservableTreeItem(mockBuildConfig("n", "c2", "x")); assertTrue(comparator.compare(null, i1, i2) < 0); assertTrue(comparator.compare(null, i2, i1) > 0); assertEquals(0, comparator.compare(null, i1, i1)); }
Source:
public void GenericPacketTest() throws BadPacketException, IOException, BadPcapFileException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); PcapFile dummy = trace.getTrace(); ByteBuffer byteBuffer = fEthernetPacket; if (byteBuffer == null) { fail("GenericPacketTest has failed!"); return; } Packet packet = new EthernetIIPacket(dummy, null, byteBuffer); assertTrue(packet.hasProtocol(PcapProtocol.ETHERNET_II)); assertTrue(packet.hasProtocol(PcapProtocol.UNKNOWN)); assertFalse(packet.hasProtocol(PcapProtocol.TCP)); assertEquals(PcapProtocol.ETHERNET_II, packet.getProtocol()); assertEquals(packet, packet.getPacket(PcapProtocol.ETHERNET_II)); assertNull(packet.getPacket(PcapProtocol.TCP)); assertEquals(packet.getChildPacket(), packet.getPacket(PcapProtocol.UNKNOWN)); assertEquals(packet.getPacket(PcapProtocol.ETHERNET_II), packet.getMostEcapsulatedPacket()); assertNull(packet.getParentPacket()); assertFalse(packet.getPcapFile().equals(null)); Packet child = packet.getChildPacket(); if (child == null) { fail("GenericPacketTest has failed!"); return; } assertEquals(packet.getPayload(), child.getPayload()); assertEquals(packet.getGlobalSummaryString(), "Source MAC: 10:f8:82:b3:44:78 , Destination MAC: 34:67:0c:d2:91:51"); }

Target:
public void GenericPacketTest() throws BadPacketException, IOException, BadPcapFileException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); try (PcapFile dummy = trace.getTrace();) { ByteBuffer byteBuffer = fEthernetPacket; if (byteBuffer == null) { fail("GenericPacketTest has failed!"); return; } Packet packet = new EthernetIIPacket(dummy, null, byteBuffer); assertTrue(packet.hasProtocol(PcapProtocol.ETHERNET_II)); assertTrue(packet.hasProtocol(PcapProtocol.UNKNOWN)); assertFalse(packet.hasProtocol(PcapProtocol.TCP)); assertEquals(PcapProtocol.ETHERNET_II, packet.getProtocol()); assertEquals(packet, packet.getPacket(PcapProtocol.ETHERNET_II)); assertNull(packet.getPacket(PcapProtocol.TCP)); assertEquals(packet.getChildPacket(), packet.getPacket(PcapProtocol.UNKNOWN)); assertEquals(packet.getPacket(PcapProtocol.ETHERNET_II), packet.getMostEcapsulatedPacket()); assertNull(packet.getParentPacket()); assertFalse(packet.getPcapFile().equals(null)); Packet child = packet.getChildPacket(); if (child == null) { fail("GenericPacketTest has failed!"); return; } assertEquals(packet.getPayload(), child.getPayload()); assertEquals(packet.getGlobalSummaryString(), "Source MAC: 10:f8:82:b3:44:78 , Destination MAC: 34:67:0c:d2:91:51"); } }
Source:
public void testInvalidNullDefaultForPotentiallyNonNullableArray() throws Exception { MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", " \"name\": \"FooBar\",", " \"validVersions\": \"0-2\",", " \"fields\": [", " { \"name\": \"field1\", \"type\": \"[]int32\", \"versions\": \"0+\", \"nullableVersions\": \"1+\", ", " \"default\": \"null\" }", " ]", "}")), MessageSpec.class); try { new MessageDataGenerator("test").generate(testMessageSpec); fail("Expected MessageDataGenerator#generate to fail"); } catch (RuntimeException e) { assertTrue("Invalid error message: " + e.getMessage(), e.getMessage().contains("not all versions of this field are nullable")); } }

Target:
public void testInvalidNullDefaultForPotentiallyNonNullableArray() throws Exception { MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", " \"name\": \"FooBar\",", " \"validVersions\": \"0-2\",", " \"fields\": [", " { \"name\": \"field1\", \"type\": \"[]int32\", \"versions\": \"0+\", \"nullableVersions\": \"1+\", ", " \"default\": \"null\" }", " ]", "}")), MessageSpec.class); try { new MessageDataGenerator("org.apache.kafka.common.message").generate(testMessageSpec); fail("Expected MessageDataGenerator#generate to fail"); } catch (RuntimeException e) { assertTrue("Invalid error message: " + e.getMessage(), e.getMessage().contains("not all versions of this field are nullable")); } }
Source:
private ZkBaseDataAccessor(RealmAwareZkClient zkClient, boolean usesExternalZkClient) { if (zkClient == null) { throw new NullPointerException("zkclient is null"); } _zkClient = zkClient; _usesExternalZkClient = usesExternalZkClient; }

Target:
private ZkBaseDataAccessor(RealmAwareZkClient zkClient, boolean usesExternalZkClient) { if (zkClient == null) { throw new IllegalArgumentException("zkclient is null"); } _zkClient = zkClient; _usesExternalZkClient = usesExternalZkClient; }
Source:
protected void onHandleIntent(Intent intent) { Log.i(TAG, "Handle Intent"); broadcastManager.sendBroadcast(runningBroadcast()); final Type type = (Type) intent.getSerializableExtra(EXTRA_TYPE); Log.i(TAG, "Type: " + type); try { switch (type) { case DOWNLOAD_TRAINING: searchTraining(intent.getStringExtra(MINISTRY_ID), intent.getStringExtra(MINISTRY_MCC)); break; case SYNC_TRAINING: syncTraining(intent); break; case SYNC_DIRTY_TRAINING: syncDirtyTraining(); default: break; } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } }

Target:
protected void onHandleIntent(Intent intent) { Log.i(TAG, "Handle Intent"); broadcastManager.sendBroadcast(runningBroadcast()); final Type type = (Type) intent.getSerializableExtra(EXTRA_TYPE); Log.i(TAG, "Type: " + type); try { switch (type) { case DOWNLOAD_TRAINING: searchTraining(intent.getStringExtra(MINISTRY_ID), intent.getStringExtra(MINISTRY_MCC)); break; case SYNC_TRAINING: syncTraining(intent); break; case SYNC_DIRTY_TRAINING: syncDirtyTraining(); break; default: break; } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } }
Source:
protected void execute() { logger.debug("execute() method is called!"); try { final InfoResponse response = createProtocol().info(); for (NeoHubBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { final String device = provider.getNeoStatDevice(itemName); State result = null; switch (provider.getNeoStatProperty(itemName)) { case CurrentTemperature: result = new DecimalType(response.getDevice(device) .getCurrentTemperature()); break; case CurrentFloorTemperature: result = new DecimalType(response.getDevice(device) .getCurrentFloorTemperature()); break; case CurrentSetTemperature: result = new DecimalType(response.getDevice(device) .getCurrentSetTemperature()); break; case DeviceName: result = new StringType(response.getDevice(device) .getDeviceName()); break; case Away: result = response.getDevice(device).isAway() ? OnOffType.ON : OnOffType.OFF; break; case Standby: result = response.getDevice(device).isStandby() ? OnOffType.ON : OnOffType.OFF; break; case Heating: result = response.getDevice(device).isHeating() ? OnOffType.ON : OnOffType.OFF; break; } if (eventPublisher != null && result != null) { eventPublisher.postUpdate(itemName, result); } } } } catch (final RuntimeException e) { logger.error( "Failed to parse response or fetch expected result from it. Please check your configuration.", e); return; } }

Target:
protected void execute() { try { final InfoResponse response = createProtocol().info(); for (NeoHubBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { final String device = provider.getNeoStatDevice(itemName); final NeoStatProperty property = provider .getNeoStatProperty(itemName); final State result = mapResponseToState(response, device, property); if (eventPublisher != null) { eventPublisher.postUpdate(itemName, result); } } } } catch (final RuntimeException e) { logger.warn("Failed to fetch info from neo hub.", e); } }
Source:
private void doPoll() { log.debug("Starting polling of segment table"); final List<DataSegment> segments = connector.inReadOnlyTransaction( new TransactionCallback<List<DataSegment>>() { @Override public List<DataSegment> inTransaction(Handle handle, TransactionStatus status) { return handle .createQuery(StringUtils.format("SELECT payload FROM %s WHERE used=true", getSegmentsTable())) .setFetchSize(connector.getStreamingFetchSize()) .map( new ResultSetMapper<DataSegment>() { @Override public DataSegment map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { DataSegment segment = jsonMapper.readValue(r.getBytes("payload"), DataSegment.class); return replaceWithExistingSegmentIfPresent(segment); } catch (IOException e) { log.makeAlert(e, "Failed to read segment from db.").emit(); return null; } } } ) .list(); } } ); ImmutableMap<String, String> dataSourceProperties = createDefaultDataSourceProperties(); if (segments == null || segments.isEmpty()) { log.info("No segments found in the database!"); dataSourcesSnapshot = DataSourcesSnapshot.fromUsedSegments(Collections.emptyList(), dataSourceProperties); } else { log.info("Polled and found %,d segments in the database", segments.size()); dataSourcesSnapshot = DataSourcesSnapshot.fromUsedSegments( Iterables.filter(segments, Objects::nonNull), dataSourceProperties ); } }

Target:
private void doPoll() { log.debug("Starting polling of segment table"); final List<DataSegment> segments = connector.inReadOnlyTransaction( new TransactionCallback<List<DataSegment>>() { @Override public List<DataSegment> inTransaction(Handle handle, TransactionStatus status) { return handle .createQuery(StringUtils.format("SELECT payload FROM %s WHERE used=true", getSegmentsTable())) .setFetchSize(connector.getStreamingFetchSize()) .map( new ResultSetMapper<DataSegment>() { @Override public DataSegment map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { DataSegment segment = jsonMapper.readValue(r.getBytes("payload"), DataSegment.class); return replaceWithExistingSegmentIfPresent(segment); } catch (IOException e) { log.makeAlert(e, "Failed to read segment from db.").emit(); return null; } } } ) .list(); } } ); Preconditions.checkNotNull( segments, "Unexpected 'null' when polling segments from the db, aborting snapshot update." ); ImmutableMap<String, String> dataSourceProperties = createDefaultDataSourceProperties(); if (segments.isEmpty()) { log.info("No segments found in the database!"); } else { log.info("Polled and found %,d segments in the database", segments.size()); } dataSourcesSnapshot = DataSourcesSnapshot.fromUsedSegments( Iterables.filter(segments, Objects::nonNull), dataSourceProperties ); }
Source:
public <B extends BlockStateHolder<B>> void sendFakeBlock(BlockVector3 pos, B block) { World world = getWorld(); if (!(world instanceof ForgeWorld)) { return; } BlockPos loc = ForgeAdapter.toBlockPos(pos); if (block == null) { final SChangeBlockPacket packetOut = new SChangeBlockPacket(((ForgeWorld) world).getWorld(), loc); player.connection.sendPacket(packetOut); } else { final SChangeBlockPacket packetOut = new SChangeBlockPacket(); PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); buf.writeBlockPos(loc); buf.writeVarInt(Block.getStateId(ForgeAdapter.adapt(block.toImmutableState()))); try { packetOut.readPacketData(buf); } catch (IOException e) { return; } player.connection.sendPacket(packetOut); if (block instanceof BaseBlock) { final BaseBlock baseBlock = (BaseBlock) block; final CompoundTag nbtData = baseBlock.getNbtData(); if (nbtData != null) { player.connection.sendPacket(new SUpdateTileEntityPacket( new BlockPos(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()), 7, NBTConverter.toNative(nbtData)) ); } } } }

Target:
public <B extends BlockStateHolder<B>> void sendFakeBlock(BlockVector3 pos, B block) { World world = getWorld(); if (!(world instanceof ForgeWorld)) { return; } BlockPos loc = ForgeAdapter.toBlockPos(pos); if (block == null) { final SChangeBlockPacket packetOut = new SChangeBlockPacket(((ForgeWorld) world).getWorld(), loc); player.connection.sendPacket(packetOut); } else { final SChangeBlockPacket packetOut = new SChangeBlockPacket(); PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); buf.writeBlockPos(loc); buf.writeVarInt(Block.getStateId(ForgeAdapter.adapt(block.toImmutableState()))); try { packetOut.readPacketData(buf); } catch (IOException e) { return; } player.connection.sendPacket(packetOut); if (block instanceof BaseBlock && block.getBlockType().equals(BlockTypes.STRUCTURE_BLOCK)) { final BaseBlock baseBlock = (BaseBlock) block; final CompoundTag nbtData = baseBlock.getNbtData(); if (nbtData != null) { player.connection.sendPacket(new SUpdateTileEntityPacket( new BlockPos(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()), STRUCTURE_BLOCK_PACKET_ID, NBTConverter.toNative(nbtData)) ); } } } }
Source:
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes( EnableModule.class.getName(), false); List<String> registeredChannelNames = new ArrayList<>(); for (Class<?> type : collectClasses(attributes.get("value"))) { registeredChannelNames.addAll(MessageChannelBeanDefinitionRegistryUtils.registerChannelBeanDefinitions(type, registry)); MessageChannelBeanDefinitionRegistryUtils.registerChannelsQualifiedBeanDefinitions( ClassUtils.resolveClassName(metadata.getClassName(), null), type, registry); } Properties defaultChannelNameProperties = new Properties(); for (String registeredChannelName : registeredChannelNames) { defaultChannelNameProperties.put(SPRING_CLOUD_STREAM_BINDINGS_PREFIX + "." + registeredChannelName, "${spring.application.name:spring.cloud.stream}" + "." + registeredChannelName); } if (environment != null) { environment.getPropertySources().addLast( new PropertiesPropertySource("default-spring-cloud-stream-channel-bindings", defaultChannelNameProperties)); } }

Target:
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes( EnableModule.class.getName(), false); List<String> registeredChannelNames = new ArrayList<>(); for (Class<?> type : collectClasses(attributes.get("value"))) { registeredChannelNames.addAll(MessageChannelBeanDefinitionRegistryUtils.registerChannelBeanDefinitions(type, registry)); MessageChannelBeanDefinitionRegistryUtils.registerChannelsQualifiedBeanDefinitions( ClassUtils.resolveClassName(metadata.getClassName(), null), type, registry); } Properties defaultChannelNameProperties = new Properties(); for (String registeredChannelName : registeredChannelNames) { defaultChannelNameProperties.put(SPRING_CLOUD_STREAM_BINDINGS_PREFIX + "." + registeredChannelName, "${spring.application.name:spring.cloud.stream}" + "." + registeredChannelName); } environment.getPropertySources().addLast( new PropertiesPropertySource("default-spring-cloud-stream-channel-bindings", defaultChannelNameProperties)); }
Source:
protected void onStart() { super.onStart(); if (searchQuery != null) { setTitle(getString(R.string.discussion_posts_search_title)); return; } if (discussionTopic != null && discussionTopic.getName() != null) { if (discussionTopic.getIdentifier().equals(DiscussionTopic.FOLLOWING_TOPICS_ID)) { SpannableString title = new SpannableString(" " + discussionTopic.getName()); Drawable starIcon = new IconDrawable(this, FontAwesomeIcons.fa_star) .colorRes(this, R.color.edx_grayscale_neutral_white_t) .sizeRes(this, R.dimen.edx_base); starIcon.setBounds(0, 0, starIcon.getIntrinsicWidth(), starIcon.getIntrinsicHeight()); ImageSpan iSpan = new ImageSpan(starIcon, ImageSpan.ALIGN_BASELINE); title.setSpan(iSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); setTitle(title); } else { setTitle(discussionTopic.getName()); } } }

Target:
protected void onStart() { super.onStart(); if (searchQuery != null) { setTitle(getString(R.string.discussion_posts_search_title)); return; } if (discussionTopic != null && discussionTopic.getName() != null) { if (discussionTopic.getIdentifier().equals(DiscussionTopic.FOLLOWING_TOPICS_ID)) { SpannableString title = new SpannableString(" " + discussionTopic.getName()); IconDrawable starIcon = new IconDrawable(this, FontAwesomeIcons.fa_star) .colorRes(this, R.color.edx_grayscale_neutral_white_t) .sizeRes(this, R.dimen.edx_base); starIcon.setBounds(0, 0, starIcon.getIntrinsicWidth(), starIcon.getIntrinsicHeight()); starIcon.setTintList(null); ImageSpan iSpan = new ImageSpan(starIcon, ImageSpan.ALIGN_BASELINE); title.setSpan(iSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); setTitle(title); } else { setTitle(discussionTopic.getName()); } } }
Source:
public UnaliasSymbolReferences(FunctionManager functionManager) { this.functionManager = functionManager; }

Target:
public UnaliasSymbolReferences(FunctionManager functionManager) { this.functionManager = requireNonNull(functionManager, "functionManager is null"); }
Source:
protected void prepareBuffer() { bufferToSend = PooledByteBufAllocator.DEFAULT.ioBuffer( (int) super.sizeInBytes() + (Partition_Response_Info_List_Size + partitionResponseInfoSize)); writeHeader(); if (partitionResponseInfoList != null) { bufferToSend.writeInt(partitionResponseInfoList.size()); for (PartitionResponseInfo partitionResponseInfo : partitionResponseInfoList) { partitionResponseInfo.writeTo(bufferToSend); } } if (toSend != null) { if (toSend.content() != null) { int maxNumComponent = 1 + toSend.content().nioBufferCount(); CompositeByteBuf compositeByteBuf = bufferToSend.alloc().compositeHeapBuffer(maxNumComponent); compositeByteBuf.addComponent(true, bufferToSend); compositeByteBuf.addFlattenedComponents(true, toSend.content()); bufferToSend = compositeByteBuf; toSend = null; } } }

Target:
protected void prepareBuffer() { bufferToSend = PooledByteBufAllocator.DEFAULT.ioBuffer( (int) super.sizeInBytes() + (Partition_Response_Info_List_Size + partitionResponseInfoSize)); writeHeader(); if (partitionResponseInfoList != null) { bufferToSend.writeInt(partitionResponseInfoList.size()); for (PartitionResponseInfo partitionResponseInfo : partitionResponseInfoList) { partitionResponseInfo.writeTo(bufferToSend); } } if (toSend != null) { ByteBuf toSendContent = toSend.content(); if (toSendContent != null) { int maxNumComponent = 1 + toSendContent.nioBufferCount(); CompositeByteBuf compositeByteBuf = bufferToSend.alloc().compositeDirectBuffer(maxNumComponent); compositeByteBuf.addComponent(true, bufferToSend); if (toSendContent instanceof CompositeByteBuf) { Iterator<ByteBuf> iterator = ((CompositeByteBuf) toSendContent).iterator(); while (iterator.hasNext()) { compositeByteBuf.addComponent(true, iterator.next()); } } else { compositeByteBuf.addComponent(true, toSendContent); } bufferToSend = compositeByteBuf; sendSizeInBufferToSend = toSendContent.readableBytes(); toSend = null; } } }
Source:
@Override public void setCard(@NonNull AnnouncementCard card) { super.setCard(card); if (!TextUtils.isEmpty(card.extract())) { textView.setText(StringUtil.fromHtml(card.extract())); } if (!card.hasAction()) { actionViewPositive.setVisibility(GONE); actionViewNegative.setVisibility(GONE); } else { actionViewPositive.setVisibility(VISIBLE); actionViewNegative.setVisibility(VISIBLE); actionViewPositive.setText(card.actionTitle()); } if (!TextUtils.isEmpty(card.negativeText())) { actionViewNegative.setText(card.negativeText()); } else { actionViewNegative.setVisibility(GONE); } if (card.hasImage()) { headerImageView.setVisibility(VISIBLE); headerImageView.loadImage(card.image()); } else { headerImageView.setVisibility(GONE); } if (card.imageHeight() > 0) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) headerImageView.getLayoutParams(); params.height = DimenUtil.roundedDpToPx(card.imageHeight()); headerImageView.setLayoutParams(params); } if (card.hasFooterCaption()) { footerTextView.setText(StringUtil.fromHtml(card.footerCaption())); RichTextUtil.removeUnderlinesFromLinks(footerTextView); } else { footerTextView.setVisibility(GONE); footerBorderView.setVisibility(GONE); } if (card.hasBorder()) { } }

Target:
@Override public void setCard(@NonNull AnnouncementCard card) { super.setCard(card); if (!TextUtils.isEmpty(card.extract())) { textView.setText(StringUtil.fromHtml(card.extract())); } if (!card.hasAction()) { actionViewPositive.setVisibility(GONE); actionViewNegative.setVisibility(GONE); } else { actionViewPositive.setVisibility(VISIBLE); actionViewNegative.setVisibility(VISIBLE); actionViewPositive.setText(card.actionTitle()); } if (!TextUtils.isEmpty(card.negativeText())) { actionViewNegative.setText(card.negativeText()); } else { actionViewNegative.setVisibility(GONE); } if (card.hasImage()) { headerImageView.setVisibility(VISIBLE); headerImageView.loadImage(card.image()); } else { headerImageView.setVisibility(GONE); } if (card.imageHeight() > 0) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) headerImageView.getLayoutParams(); params.height = DimenUtil.roundedDpToPx(card.imageHeight()); headerImageView.setLayoutParams(params); } if (card.hasFooterCaption()) { footerTextView.setText(StringUtil.fromHtml(card.footerCaption())); RichTextUtil.removeUnderlinesFromLinks(footerTextView); } else { footerTextView.setVisibility(GONE); footerBorderView.setVisibility(GONE); } if (card.hasBorder()) { container.setStrokeColor(getResources().getColor(R.color.red30)); container.setStrokeWidth(10); } else { container.setDefaultBorder(); } }