focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( List<ExecutionAttemptID> executionAttemptIds) { final Map<ExecutionVertexID, ExecutionAttemptID> vertexIdToExecutionId = new HashMap<>(); executionAttemptIds.forEach( executionId -> ...
@Test void testPhysicalSlotReleaseLogicalSlots() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext.newBuilder().addGroup(EV1, EV2).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2);...
@Override public void upgrade() { if (shouldSkip()) { return; } final ImmutableSet<String> eventIndexPrefixes = ImmutableSet.of( elasticsearchConfig.getDefaultEventsIndexPrefix(), elasticsearchConfig.getDefaultSystemEventsIndexPrefix()); ...
@Test void usesEventIndexPrefixesFromElasticsearchConfig() { mockConfiguredEventPrefixes("events-prefix", "system-events-prefix"); this.sut.upgrade(); verify(elasticsearchAdapter) .addGl2MessageIdFieldAlias(ImmutableSet.of("events-prefix", "system-events-prefix")); }
@Override public PipelineJobProgressUpdatedParameter write(final String ackId, final Collection<Record> records) { if (records.isEmpty()) { return new PipelineJobProgressUpdatedParameter(0); } while (!channel.isWritable() && channel.isActive()) { doAwait(); } ...
@Test void assertWrite() throws IOException { Channel mockChannel = mock(Channel.class); when(mockChannel.isWritable()).thenReturn(false, true); when(mockChannel.isActive()).thenReturn(true); ShardingSphereDatabase mockDatabase = mock(ShardingSphereDatabase.class); when(mockD...
public LocationIndex prepareIndex() { return prepareIndex(EdgeFilter.ALL_EDGES); }
@Test public void testWayGeometry() { Graph g = createTestGraphWithWayGeometry(); LocationIndex index = createIndexNoPrepare(g, 500000).prepareIndex(); assertEquals(3, findClosestEdge(index, 0, 0)); assertEquals(3, findClosestEdge(index, 0, 0.1)); assertEquals(3, findClosestE...
static Predicate obtainPredicateFromExpression( final CamelContext camelContext, final String predExpression, final String expressionLanguage) { try { return camelContext.resolveLanguage(expressionLanguage).createPredicate(predExpression); } catch (Excepti...
@Test void obtainPredicateFromExpressionWithError() { String expression = "not a valid expression"; assertThrows(IllegalArgumentException.class, () -> DynamicRouterControlService.obtainPredicateFromExpression(context, expression, expressionLanguage)); }
public Set<Integer> nodesThatShouldBeDown(ClusterState state) { return calculate(state).nodesThatShouldBeDown(); }
@Test void min_ratio_of_zero_never_takes_down_groups_implicitly() { GroupAvailabilityCalculator calc = calcForHierarchicCluster( DistributionBuilder.withGroups(2).eachWithNodeCount(4), 0.0); assertThat(calc.nodesThatShouldBeDown(clusterState( "distributor:8 storage:8"...
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String colType; String colName ...
@Test public void testAggregateMultiStatsWhenUnmergeableBitVectors() throws MetaException { List<String> partitions = Arrays.asList("part1", "part2", "part3"); long[] values1 = { DATE_1.getDaysSinceEpoch(), DATE_2.getDaysSinceEpoch(), DATE_3.getDaysSinceEpoch() }; ColumnStatisticsData data1 = new ColStat...
@Udf(description = "Returns the sine of an INT value") public Double sin( @UdfParameter( value = "value", description = "The value in radians to get the sine of." ) final Integer value ) { return sin(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleNull() { assertThat(udf.sin((Integer) null), is(nullValue())); assertThat(udf.sin((Long) null), is(nullValue())); assertThat(udf.sin((Double) null), is(nullValue())); }
public static Iterable<List<Object>> fixData(List<Column> columns, Iterable<List<Object>> data) { if (data == null) { return null; } requireNonNull(columns, "columns is null"); List<TypeSignature> signatures = columns.stream() .map(column -> parseTypeSigna...
@Test public void testFixData() { testFixDataWithTypePrefix(""); }
@Override public int run(String[] args) throws Exception { if (args.length != 2) { return usage(args); } String action = args[0]; String name = args[1]; int result; if (A_LOAD.equals(action)) { result = loadClass(name); } else if (A_CREATE.equals(action)) { //first load t...
@Test public void testCreateFailsInConstructor() throws Throwable { run(FindClass.E_CREATE_FAILED, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass$FailInConstructor"); }
@Override public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext) { doEvaluateDisruptContext(request, requestContext); return _client.sendRequest(request, requestContext); }
@Test public void testSendRequest7() { when(_builder.build()).thenReturn(_request); when(_controller.getDisruptContext(any(String.class), any(ResourceMethod.class))).thenReturn(_disrupt); _client.sendRequest(_builder, _context, _behavior); verify(_underlying, times(1)).sendRequest(eq(_request), eq(_...
@SuppressWarnings("unchecked") @Override public RegisterNodeManagerResponse registerNodeManager( RegisterNodeManagerRequest request) throws YarnException, IOException { NodeId nodeId = request.getNodeId(); String host = nodeId.getHost(); int cmPort = nodeId.getPort(); int httpPort = requ...
@Test public void testNodeRegistrationFailure() throws Exception { writeToHostsFile("host1"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); ResourceTrackerService re...
@Override public void close() { if (!ObjectUtils.isEmpty(watchConfigChangeListener)) { configService.removeChangeListener(watchConfigChangeListener); } }
@Test public void testClose() { Config configService = mock(Config.class); ApolloDataService apolloDataService = new ApolloDataService(configService, null, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); apolloDataService.c...
@Override public void preflight(final Path directory) throws BackgroundException { final Acl acl = directory.attributes().getAcl(); if(Acl.EMPTY == acl) { // Missing initialization log.warn(String.format("Unknown ACLs on %s", directory)); return; } ...
@Test public void testListChildrenInbox() throws Exception { final DeepboxIdProvider nodeid = new DeepboxIdProvider(session); final Path folder = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Inbox/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final PathAttributes attributes = ne...
public List<String> tokenize(String text) { List<String> tokens = new ArrayList<>(); Matcher regexMatcher = regexExpression.matcher(text); int lastIndexOfPrevMatch = 0; while (regexMatcher.find(lastIndexOfPrevMatch)) // this is where the magic happens: ...
@Test void testTokenize_happyPath_9() { // given CompoundCharacterTokenizer tokenizer = new CompoundCharacterTokenizer( new HashSet<>(Arrays.asList("_101_102_", "_101_102_"))); String text = "_100_101_102_103_104_"; // when List<String> tokens = tokenizer...
public static <K> KStreamHolder<K> build( final KStreamHolder<K> stream, final StreamSelectKey<K> selectKey, final RuntimeBuildContext buildContext ) { return build(stream, selectKey, buildContext, PartitionByParamsFactory::build); }
@Test public void shouldReturnRekeyedStream() { // When: final KStreamHolder<GenericKey> result = StreamSelectKeyBuilder .build(stream, selectKey, buildContext, paramBuilder); // Then: assertThat(result.getStream(), is(rekeyedKstream)); }
public abstract VoiceInstructionValue getConfigForDistance( double distance, String turnDescription, String thenVoiceInstruction);
@Test public void germanInitialVICMetricTest() { InitialVoiceInstructionConfig configMetric = new InitialVoiceInstructionConfig(FOR_HIGHER_DISTANCE_PLURAL.metric, trMap, Locale.GERMAN, 4250, 250, DistanceUtils.Unit.METRIC); compareVoiceInstructionValues( 4000, ...
public <T> Mono<CosmosItemResponse<T>> createItem( final T item, final PartitionKey partitionKey, final CosmosItemRequestOptions itemRequestOptions) { CosmosDbUtils.validateIfParameterIsNotEmpty(item, PARAM_ITEM); CosmosDbUtils.validateIfParameterIsNotEmpty(partitionKey, PARAM_PARTITION_KEY)...
@Test void testCreateItem() { final CosmosDbContainerOperations operations = new CosmosDbContainerOperations(Mono.just(mock(CosmosAsyncContainer.class))); CosmosDbTestUtils.assertIllegalArgumentException(() -> operations.createItem(null, null, null)); CosmosDbTestUtils.asser...
public void declareTypes(final List<KiePMMLDroolsType> types) { logger.trace("declareTypes {} ", types); types.forEach(this::declareType); }
@Test void declareTypes() { List<KiePMMLDroolsType> types = new ArrayList<>(); types.add(KiePMMLDescrTestUtils.getDroolsType()); types.add(KiePMMLDescrTestUtils.getDottedDroolsType()); assertThat(builder.getDescr().getTypeDeclarations()).isEmpty(); KiePMMLDescrTypesFactory.fa...
@Override public synchronized Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) { selectedBundlesCache.clear(); final double threshold = conf.getLoadBalancerBrokerThresho...
@Test public void testFilterRecentlyUnloaded() { int numBundles = 10; LoadData loadData = new LoadData(); LocalBrokerData broker1 = new LocalBrokerData(); broker1.setBandwidthIn(new ResourceUsage(999, 1000)); broker1.setBandwidthOut(new ResourceUsage(999, 1000)); Lo...
@Override public BackgroundException map(final GenericException e) { final StringBuilder buffer = new StringBuilder(); this.append(buffer, e.getMessage()); final StatusLine status = e.getHttpStatusLine(); if(null != status) { this.append(buffer, String.format("%d %s", sta...
@Test public void testLoginFailure() { final GenericException f = new GenericException( "message", new Header[]{}, new BasicStatusLine(new ProtocolVersion("http", 1, 1), 403, "Forbidden")); assertTrue(new SwiftExceptionMappingService().map(f) instanceof AccessDeniedException); as...
public void removeDockerContainer(String containerId) { try { PrivilegedOperationExecutor privOpExecutor = PrivilegedOperationExecutor.getInstance(super.getConf()); if (DockerCommandExecutor.isRemovable( DockerCommandExecutor.getContainerStatus(containerId, privOpExecutor, ...
@Test public void testRemoveDockerContainer() throws Exception { ApplicationId appId = ApplicationId.newInstance(12345, 67890); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance(appId, 54321); String cid = ContainerId.newContainerId(attemptId, 9876).toString(); LinuxContainerEx...
public Response post(URL url, Request request) throws IOException { return call(HttpMethods.POST, url, request); }
@Test public void testPost() throws IOException { verifyCall(HttpMethods.POST, FailoverHttpClient::post); }
public static double conversion(String expression) { return (new Calculator()).calculate(expression); }
@Test public void conversationTest2(){ final double conversion = Calculator.conversion("77 * 12"); assertEquals(924.0, conversion, 0); }
public static ValueLabel formatPacketRate(long packets) { return new ValueLabel(packets, PACKETS_UNIT).perSec(); }
@Test public void formatPacketRateSmall() { vl = TopoUtils.formatPacketRate(37); assertEquals(AM_WL, "37 pps", vl.toString()); }
@Override public boolean enableSendingOldValues(final boolean forceMaterialization) { if (queryableName != null) { sendOldValues = true; return true; } if (parent.enableSendingOldValues(forceMaterialization)) { sendOldValues = true; } ret...
@Test public void shouldEnableSendingOldValuesOnParentIfMapValuesNotMaterialized() { final StreamsBuilder builder = new StreamsBuilder(); final String topic1 = "topic1"; final KTableImpl<String, String, String> table1 = (KTableImpl<String, String, String>) builder.table(topic1, ...
@VisibleForTesting void checkRemoteFoldernameField( String remoteFoldernameFieldName, SFTPPutData data ) throws KettleStepException { // Remote folder fieldname remoteFoldernameFieldName = environmentSubstitute( remoteFoldernameFieldName ); if ( Utils.isEmpty( remoteFoldernameFieldName ) ) { // remo...
@Test public void checkRemoteFoldernameField_NameIsSet_Found() throws Exception { RowMeta rowMeta = rowOfStringsMeta( "some field", "remoteFoldernameFieldName" ); step.setInputRowMeta( rowMeta ); SFTPPutData data = new SFTPPutData(); step.checkRemoteFoldernameField( "remoteFoldernameFieldName", data ...
public List<CloudtrailSNSNotification> parse(Message message) { LOG.debug("Parsing message."); try { LOG.debug("Reading message body {}.", message.getBody()); final SQSMessage envelope = objectMapper.readValue(message.getBody(), SQSMessage.class); if (envelope.messa...
@Test public void testParseWithTwoS3Objects() throws Exception { final Message doubleMessage = new Message() .withBody("{\n" + " \"Type\" : \"Notification\",\n" + " \"MessageId\" : \"11a04c4a-094e-5395-b297-00eaefda2893\",\n" + ...
public static <InputT> PTransform<PCollection<InputT>, PCollection<Row>> toRows() { return to(Row.class); }
@Test @Category(NeedsRunner.class) public void testToRows() { PCollection<Row> rows = pipeline.apply(Create.of(new POJO1())).apply(Convert.toRows()); PAssert.that(rows).containsInAnyOrder(EXPECTED_ROW1); pipeline.run(); }
@Override public void triggerProbe(DeviceId deviceId) { LOG.debug("Triggering probe on device {}", deviceId); final Dpid dpid = dpid(deviceId.uri()); OpenFlowSwitch sw = controller.getSwitch(dpid); if (sw == null || !sw.isConnected()) { LOG.error("Failed to probe device ...
@Test public void triggerProbe() { int cur = SW1.sent.size(); provider.triggerProbe(DID1); assertEquals("OF message not sent", cur + 1, SW1.sent.size()); }
int sampleRunnable(Runnable runnable) { if (runnable instanceof LocalEventDispatcher eventDispatcher) { return sampleLocalDispatcherEvent(eventDispatcher); } occurrenceMap.add(runnable.getClass().getName(), 1); return 1; }
@Test public void testSampleRunnable() { Address caller = new Address(); Data data = mock(Data.class); EntryEventData mapEventAdded = new EntryEventData("source", "mapName", caller, data, data, data, ADDED.getType()); EntryEventData mapEventUpdated = new EntryEventData("source", "ma...
public int filterEntriesForConsumer(List<? extends Entry> entries, EntryBatchSizes batchSizes, SendMessageInfo sendMessageInfo, EntryBatchIndexesAcks indexesAcks, ManagedCursor cursor, boolean isReplayRead, Consumer consumer) { return filterEntriesForConsumer(null, 0, entries, batchSizes...
@Test public void testFilterEntriesForConsumerOfEntryFilter() throws Exception { Topic mockTopic = mock(Topic.class); when(this.subscriptionMock.getTopic()).thenReturn(mockTopic); final EntryFilterProvider entryFilterProvider = mock(EntryFilterProvider.class); final ServiceConfigura...
public CombinedServiceDiscovery(List<ServiceDiscovery> delegates) { this.delegates = Collections.unmodifiableList(delegates); }
@Test public void testCombinedServiceDiscovery() { StaticServiceDiscovery discovery1 = new StaticServiceDiscovery(); discovery1.addServer(new DefaultServiceDefinition("discovery1", "localhost", 1111)); discovery1.addServer(new DefaultServiceDefinition("discovery1", "localhost", 1112)); ...
public static PostgreSQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find PostgreSQL type '%s' in column type when process binary protocol value", binaryColumnType); return ...
@Test void assertGetInt8BinaryProtocolValue() { PostgreSQLBinaryProtocolValue binaryProtocolValue = PostgreSQLBinaryProtocolValueFactory.getBinaryProtocolValue(PostgreSQLColumnType.INT8); assertThat(binaryProtocolValue, instanceOf(PostgreSQLInt8BinaryProtocolValue.class)); }
public static void main(String[] args) throws Exception { Arguments arguments = new Arguments(); CommandLine commander = new CommandLine(arguments); try { commander.parseArgs(args); if (arguments.help) { commander.usage(commander.getOut()); ...
@Test public void testMainGenerateDocs() throws Exception { PrintStream oldStream = System.out; try { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); Class argumentsClass = Class.forNam...
public Duration computeReadTimeout(HttpRequestMessage request, int attemptNum) { IClientConfig clientConfig = getRequestClientConfig(request); Long originTimeout = getOriginReadTimeout(); Long requestTimeout = getRequestReadTimeout(clientConfig); long computedTimeout; if (origin...
@Test void computeReadTimeout_requestOnly() { requestConfig.set(CommonClientConfigKey.ReadTimeout, 1000); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(1000, timeout.toMillis()); }
public static SchemaBuilder builder(final Schema schema) { requireDecimal(schema); return builder(precision(schema), scale(schema)); }
@Test public void shouldFailIfBuilderWithScaleGTPrecision() { // When: final Exception e = assertThrows( SchemaException.class, () -> builder(1, 2) ); // Then: assertThat(e.getMessage(), containsString("DECIMAL precision must be >= scale")); }
@Override public int run(String[] argv) { // initialize FsShell init(); Tracer tracer = new Tracer.Builder("FsShell"). conf(TraceUtils.wrapHadoopConf(SHELL_HTRACE_PREFIX, getConf())). build(); int exitCode = -1; if (argv.length < 1) { printUsage(System.err); } else { ...
@Test public void testExceptionNullMessage() throws Exception { final String cmdName = "-cmdExNullMsg"; final Command cmd = Mockito.mock(Command.class); Mockito.when(cmd.run(Mockito.any())).thenThrow( new IllegalArgumentException()); Mockito.when(cmd.getUsage()).thenReturn(cmdName); final...
@Override public void close() throws IOException { in.close(); }
@Test public void testClose() throws Exception { try (InputStream sample = new ByteArrayInputStream(sample1.getBytes()); JsonArrayFixingInputStream instance = new JsonArrayFixingInputStream(sample)) { int i = instance.read(); } }
@Override public void info(String msg) { logger.info(msg); }
@Test public void testInfo() { Logger mockLogger = mock(Logger.class); when(mockLogger.getName()).thenReturn("foo"); InternalLogger logger = new Slf4JLogger(mockLogger); logger.info("a"); verify(mockLogger).getName(); verify(mockLogger).info("a"); }
public void setThreadAffinity(ThreadAffinity threadAffinity) { this.threadAffinity = threadAffinity; }
@Test public void test_setThreadAffinity_nullAffinityIsAllowed() { ReactorBuilder builder = newBuilder(); builder.setThreadAffinity(null); assertNull(builder.threadAffinity); }
public Canvas canvas() { Canvas canvas = new Canvas(getLowerBound(), getUpperBound()); canvas.add(this); if (name != null) { canvas.setTitle(name); } return canvas; }
@Test public void testHistogram3D() throws Exception { System.out.println("Histogram 3D"); double[] mu = {0.0, 0.0}; double[][] v = { {1.0, 0.6}, {0.6, 2.0} }; var gauss = new MultivariateGaussianDistribution(mu, Matrix.of(v)); var data = Stream.generate(gauss::rand).limit(1...
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createPort(InputStream input) { log.trace(String.format(MESSAGE, "CREATE")); URI location; try { ObjectNode jsonTree = readTreeFromStream(mapper(), input); final...
@Test public void testCreatePortWithCreateOperation() { mockAdminService.createPort(anyObject()); replay(mockAdminService); final WebTarget wt = target(); InputStream jsonStream = K8sPortWebResourceTest.class .getResourceAsStream("k8s-port.json"); Response re...
@CheckForNull public static String includeRenamedMetrics(@Nullable String metric) { if (REMOVED_METRIC.equals(metric)) { return DEPRECATED_METRIC_REPLACEMENT; } else { return metric; } }
@Test void includeRenamedMetrics_whenAcceptedIssuesPassed_shouldReturnAccepted() { String upToDateMetric = RemovedMetricConverter.includeRenamedMetrics("accepted_issues"); assertThat(upToDateMetric).isEqualTo("accepted_issues"); }
public void removeChannelFromBuffer( String id ) { buffer.values().stream().filter( line -> id.equals( getLogChId( line ) ) ).forEach( line -> buffer.remove( line.getNr() ) ); tailMap.remove( id ); /* for ( BufferLine line : buffer.values() ) { if ( id.equals( getLogChId( line ) ) ) { buffer.r...
@Test public void testRemoveChannelFromBuffer() { String logChannelId = "1"; String otherLogChannelId = "2"; LoggingBuffer loggingBuffer = new LoggingBuffer( 20 ); for ( int i = 0; i < 10; i++ ) { KettleLoggingEvent event = new KettleLoggingEvent(); event.setMessage( new LogMessage( "testW...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testFetchPositionAfterException() { // verify the advancement in the next fetch offset equals to the number of fetched records when // some fetched partitions cause Exception. This ensures that consumer won't lose record upon exception buildFetcher(OffsetResetStrategy.NONE,...
public <T> T submitRequest(String pluginId, String requestName, PluginInteractionCallback<T> pluginInteractionCallback) { if (!pluginManager.isPluginOfType(extensionName, pluginId)) { throw new RecordNotFoundException(format("Did not find '%s' plugin with id '%s'. Looks like plugin is missing", exte...
@Test void shouldErrorOutOnValidationFailure() { when(response.responseCode()).thenReturn(DefaultGoApiResponse.VALIDATION_ERROR); when(pluginManager.submitTo(eq(pluginId), eq(extensionName), any(GoPluginApiRequest.class))).thenReturn(response); assertThatThrownBy(() -> helper.submitRequest(...
public DataConnectionConfig load(DataConnectionConfig dataConnectionConfig) { // Make a copy to preserve the original configuration DataConnectionConfig loadedConfig = new DataConnectionConfig(dataConnectionConfig); // Try XML file first if (loadConfig(loadedConfig, HazelcastDataConnect...
@Test public void testLoadYml() { DataConnectionConfig dataConnectionConfig = new DataConnectionConfig(); Path path = Paths.get("src", "test", "resources", "hazelcast-client-test-external.yaml"); dataConnectionConfig.setProperty(HazelcastDataConnection.CLIENT_YML_PATH, path.toString()); ...
public void setThreadpool(final String threadpool) { this.threadpool = threadpool; }
@Test public void testEqualsAndHashCode() { GrpcRegisterConfig config1 = new GrpcRegisterConfig(); GrpcRegisterConfig config2 = new GrpcRegisterConfig(); config1.setThreadpool("threadPool"); config2.setThreadpool("threadPool"); assertThat(ImmutableSet.of(con...
public static void hideExpandedContent() { hideExpandedContent( spoonInstance().getActiveTransGraph() ); }
@Test public void testHideExpandedContentManager() throws Exception { TransGraph transGraph = mock( TransGraph.class ); Browser browser = mock( Browser.class ); SashForm sashForm = mock( SashForm.class ); Composite parent = setupExpandedContentMocks( transGraph, browser, sashForm ); ExpandedConte...
public static NotPlaceholderExpr get() { return instance; }
@Test public void testGet() { NotPlaceholderExpr instance = NotPlaceholderExpr.get(); // Check that the returned instance is not null assertEquals(instance, NotPlaceholderExpr.get()); }
Record convert(Object data) { return convert(data, null); }
@Test public void testMapValueInMapConvert() { Table table = mock(Table.class); when(table.schema()).thenReturn(STRUCT_IN_MAP_SCHEMA); RecordConverter converter = new RecordConverter(table, config); Map<String, Object> data = createNestedMapData(); Record record = converter.convert(Immuta...
@Override public void addChildren(Deque<Expression> expressions) { addChildren(expressions, 2); }
@Test public void testFinish() throws IOException { And and = new And(); Expression first = mock(Expression.class); Expression second = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); ...
@Bean public SyncDataService nacosSyncDataService(final ObjectProvider<ConfigService> configService, final ObjectProvider<PluginDataSubscriber> pluginSubscriber, final ObjectProvider<List<MetaDataSubscriber>> metaSubscribers, final ObjectProvider<List<AuthDataSubscrib...
@Test public void nacosSyncDataServiceTest() { assertNotNull(syncDataService); }
@Override public List<String> getLineHashesMatchingDBVersion(Component component) { return cache.computeIfAbsent(component, this::createLineHashesMatchingDBVersion); }
@Test public void should_create_hash_without_significant_code_if_db_has_no_significant_code() { when(dbLineHashVersion.hasLineHashesWithoutSignificantCode(file)).thenReturn(true); List<String> lineHashes = underTest.getLineHashesMatchingDBVersion(file); assertLineHashes(lineHashes, "line1", "line2", "lin...
public FileObject convertToFileObject( VariableSpace variables ) throws KettleFileException { return KettleVFS.getFileObject( path, variables ); }
@Test public void convertToFileObject() throws Exception { Element element = new Element( NAME, TYPE, adjustSlashes( PATH ), LOCAL_PROVIDER ); FileObject fileObject = element.convertToFileObject( space ); assertEquals( NAME, fileObject.getName().getBaseName() ); assertEquals( adjustSlashes( PATH ), fi...
boolean isContainerizable() { String moduleSpecification = getProperty(PropertyNames.CONTAINERIZE); if (project == null || Strings.isNullOrEmpty(moduleSpecification)) { return true; } // modules can be specified in one of three ways: // 1) a `groupId:artifactId` // 2) an `:artifactId` ...
@Test public void testIsContainerizable_artifactId() { project.setGroupId("group"); project.setArtifactId("artifact"); Properties projectProperties = project.getProperties(); projectProperties.setProperty("jib.containerize", ":artifact"); assertThat(testPluginConfiguration.isContainerizable()).is...
@Override public void error(final ErrorMessage msg) { inner.error(() -> throwIfNotRightSchema(msg.get(config))); }
@Test public void shouldLogError() { // When: processingLogger.error(errorMsg); // Then: final SchemaAndValue msg = verifyErrorMessage(); assertThat(msg, is(msg)); }
CacheConfig<K, V> asCacheConfig() { return this.copy(new CacheConfig<>(), false); }
@Test public void serializationSucceeds_cacheWriterFactory() { CacheConfig<String, Person> cacheConfig = newDefaultCacheConfig("test"); cacheConfig.setCacheWriterFactory(new PersonCacheWriterFactory()); PreJoinCacheConfig preJoinCacheConfig = new PreJoinCacheConfig(cacheConfig); Data...
public Optional<Distance> horizontalDistAtVerticalClosureTime(Instant time) { Optional<Duration> timeUntilClosure = timeUntilVerticalClosure(time); //not closing in the vertical direction if (!timeUntilClosure.isPresent()) { return Optional.empty(); } Speed closureR...
@Test public void testHorizontalDistAtVerticalClosureTime() { //decreasing vertical separation... Distance[] verticalDistances = new Distance[]{ Distance.ofFeet(200), Distance.ofFeet(100), Distance.ofFeet(50) }; //increasing horizontal separation...
protected Object createSchemaDefaultValue(Type type, Field field, Schema fieldSchema) { Object defaultValue; if (defaultGenerated) { defaultValue = getOrCreateDefaultValue(type, field); if (defaultValue != null) { return deepCopy(fieldSchema, defaultValue); } // if we can't get t...
@Test void createSchemaDefaultValue() { Meta meta = new Meta(); validateSchema(meta); meta.f4 = 0x1987; validateSchema(meta); }
@Override public AsyncEntry asyncEntry(String name, EntryType type, int count, Object... args) throws BlockException { StringResourceWrapper resource = new StringResourceWrapper(name, type); return asyncEntryInternal(resource, count, args); }
@Test public void testAsyncEntryNormalPass() { String resourceName = "testAsyncEntryNormalPass"; ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN); AsyncEntry entry = null; // Prepare a slot that "should pass". ShouldPassSlot slot = addS...
@SuppressWarnings({"checkstyle:ParameterNumber"}) public static Pod createStatefulPod( Reconciliation reconciliation, String name, String namespace, Labels labels, String strimziPodSetName, String serviceAccountName, PodTemplate tem...
@Test public void testCreateStatefulPodWithEmptyTemplate() { Pod pod = WorkloadUtils.createStatefulPod( Reconciliation.DUMMY_RECONCILIATION, NAME + "-0", // => Pod name NAMESPACE, LABELS, NAME, // => Workload name ...
@UdafFactory(description = "Compute average of column with type Long.", aggregateSchema = "STRUCT<SUM bigint, COUNT bigint>") public static TableUdaf<Long, Struct, Double> averageLong() { return getAverageImplementation( 0L, STRUCT_LONG, (sum, newValue) -> sum.getInt64(SUM) + newValu...
@Test public void undoShouldHandleNull() { final TableUdaf<Long, Struct, Double> udaf = AverageUdaf.averageLong(); Struct agg = udaf.initialize(); final Long[] values = new Long[] {1L, 1L, 1L, 1L, null}; for (final Long thisValue : values) { agg = udaf.aggregate(thisValue, agg); } agg =...
@Override public boolean isDetected() { String ci = system.envVariable("CI"); String revision = system.envVariable("BITBUCKET_COMMIT"); return "true".equals(ci) && isNotEmpty(revision); }
@Test public void isDetected() { setEnvVariable("CI", "true"); setEnvVariable("BITBUCKET_COMMIT", "bdf12fe"); assertThat(underTest.isDetected()).isTrue(); setEnvVariable("CI", "true"); setEnvVariable("BITBUCKET_COMMIT", null); assertThat(underTest.isDetected()).isFalse(); }
public void validate(AlmSettingDto almSettingDto) { String gitlabUrl = almSettingDto.getUrl(); String accessToken = almSettingDto.getDecryptedPersonalAccessToken(encryption); validate(ValidationMode.COMPLETE, gitlabUrl, accessToken); }
@Test public void validate_success() { String token = "personal-access-token"; AlmSettingDto almSettingDto = new AlmSettingDto() .setUrl(GITLAB_API_URL) .setPersonalAccessToken("personal-access-token"); when(encryption.isEncrypted(token)).thenReturn(false); underTest.validate(almSettingDt...
public synchronized Command heartbeat(final long workerId, final Map<String, Long> capacityBytesOnTiers, final Map<String, Long> usedBytesOnTiers, final List<Long> removedBlocks, final Map<BlockStoreLocation, List<Long>> addedBlocks, final Map<String, List<String>> lostStorage, final List<Metric> metr...
@Test public void heartBeat() throws Exception { final long workerId = 1L; final Map<String, Long> capacityBytesOnTiers = ImmutableMap.of("MEM", 1024 * 1024L); final Map<String, Long> usedBytesOnTiers = ImmutableMap.of("MEM", 1024L); final List<Long> removedBlocks = ImmutableList.of(); final Map<B...
@Override public boolean validate(Path path, ResourceContext context) { // explicitly call a method not depending on LinkResourceService return validate(path); }
@Test public void testNotSatisfyWaypoint() { sut = new WaypointConstraint(DID4); assertThat(sut.validate(path, resourceContext), is(false)); }
@Override public final void aroundWriteTo(WriterInterceptorContext context) throws IOException { final String contentEncoding = (String) context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); if ((contentEncoding != null) && (contentEncoding.equals("gzip") || contentEncoding.eq...
@Test void aroundWriteToSpecX_GZip() throws IOException, WebApplicationException { MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); headers.add(HttpHeaders.CONTENT_ENCODING, "x-gzip"); WriterInterceptorContextMock context = new WriterInterceptorContextMock(headers); ...
public final synchronized List<E> getAllAddOns() { Logger.d(mTag, "getAllAddOns has %d add on for %s", mAddOns.size(), getClass().getName()); if (mAddOns.size() == 0) { loadAddOns(); } Logger.d( mTag, "getAllAddOns will return %d add on for %s", mAddOns.size(), getClass().getName()); r...
@Test public void testGetAllAddOns() throws Exception { TestableAddOnsFactory factory = new TestableAddOnsFactory(true); List<TestAddOn> list = factory.getAllAddOns(); Assert.assertTrue(list.size() > 0); HashSet<String> seenIds = new HashSet<>(); for (AddOn addOn : list) { Assert.assertNotN...
@Nullable @Override public Message decode(@Nonnull final RawMessage rawMessage) { final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress()); final String json = gelfMessage.getJSON(decompressSizeLimit, charset); final JsonNode node; ...
@Test public void decodeFailsWithWrongTypeForShortMessage() throws Exception { final String json = "{" + "\"version\": \"1.1\"," + "\"host\": \"example.org\"," + "\"short_message\": 42" + "}"; final RawMessage rawMessage = new RawMessa...
@Override public SubClusterId getHomeSubcluster( ApplicationSubmissionContext appSubmissionContext, List<SubClusterId> blackListSubClusters) throws YarnException { // null checks and default-queue behavior validate(appSubmissionContext); List<ResourceRequest> rrList = appSubmissionCo...
@Test public void testNodeNotExists() throws YarnException { List<ResourceRequest> requests = new ArrayList<ResourceRequest>(); boolean relaxLocality = true; requests.add(ResourceRequest .newInstance(Priority.UNDEFINED, "node5", Resource.newInstance(10, 1), 1, relaxLocality)); requ...
@Override public List<SnowflakeIdentifier> listDatabases() { List<SnowflakeIdentifier> databases; try { databases = connectionPool.run( conn -> queryHarness.query( conn, "SHOW DATABASES IN ACCOUNT", DATABASE_RESULT_SET_HANDLER)); } catc...
@SuppressWarnings("unchecked") @Test public void testListDatabasesInAccount() throws SQLException { when(mockResultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); when(mockResultSet.getString("name")).thenReturn("DB_1").thenReturn("DB_2").thenReturn("DB_3"); List<Snowf...
@Override public Method getMethod() { return Method.POST; }
@Test public void post_is_post() { PostRequest request = new PostRequest("api/issues/search"); assertThat(request.getMethod()).isEqualTo(WsRequest.Method.POST); }
@Nonnull public static Map<Integer, Accumulator> getAccumulators(QueryCacheContext context, String mapName, String cacheId) { PartitionAccumulatorRegistry partitionAccumulatorRegistry = getAccumulatorRegistryOrNull(context, mapName, cacheId); if (partitionAccumulatorRegistry == null) { r...
@Test public void getAccumulators_whenNoAccumulatorsRegistered_thenReturnEmptyMap() { Map<Integer, Accumulator> accumulators = getAccumulators(context, "myMap", "myCache"); assertNotNull(accumulators); assertEquals(0, accumulators.size()); }
public <T> boolean parse(Handler<T> handler, T target, CharSequence input) { if (input == null) throw new NullPointerException("input == null"); return parse(handler, target, input, 0, input.length()); }
@Test void toleratesButIgnores_emptyMembers() { for (String w : Arrays.asList(" ", "\t")) { entrySplitter.parse(parseIntoMap, map, ","); entrySplitter.parse(parseIntoMap, map, w + ","); entrySplitter.parse(parseIntoMap, map, "," + w); entrySplitter.parse(parseIntoMap, map, ",,"); entry...
public void delete(DeletionTask deletionTask) { if (debugDelay != -1) { LOG.debug("Scheduling DeletionTask (delay {}) : {}", debugDelay, deletionTask); recordDeletionTaskInStateStore(deletionTask); sched.schedule(deletionTask, debugDelay, TimeUnit.SECONDS); } }
@Test public void testAbsDelete() throws Exception { Random r = new Random(); long seed = r.nextLong(); r.setSeed(seed); System.out.println("SEED: " + seed); List<Path> dirs = buildDirs(r, base, 20); createDirs(new Path("."), dirs); FakeDefaultContainerExecutor exec = new FakeDefaultContai...
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentImportExecutor, TokensAndUrlAuthData authData, MusicContainerResource data) throws Exception { if (data == null) { // Nothing to do return ImportResult.OK; } // Update playli...
@Test public void importPlaylist() throws Exception { // Set up MusicPlaylist playlist = new MusicPlaylist("p1_id", "p1_title", null, null, null); ImmutableList<MusicPlaylist> playlists = ImmutableList.of(playlist); MusicContainerResource data = new MusicContainerResource(playlists, null, null, null);...
@Override public List<ImportValidationFeedback> verifyRule( Object subject ) { List<ImportValidationFeedback> feedback = new ArrayList<>(); if ( !isEnabled() || !( subject instanceof JobMeta ) ) { return feedback; } JobMeta jobMeta = (JobMeta) subject; String description = jobMeta.getDesc...
@Test public void testVerifyRule_NotJobMetaParameter_EnabledRule() { JobHasDescriptionImportRule importRule = getImportRule( 10, true ); List<ImportValidationFeedback> feedbackList = importRule.verifyRule( "" ); assertNotNull( feedbackList ); assertTrue( feedbackList.isEmpty() ); }
public CompletableFuture<List<BatchAckResult>> batchAckMessage( ProxyContext ctx, List<ReceiptHandleMessage> handleMessageList, String consumerGroup, String topic, long timeoutMillis ) { CompletableFuture<List<BatchAckResult>> future = new CompletableFuture<>(); ...
@Test public void testBatchAckMessage() throws Throwable { String brokerName1 = "brokerName1"; String brokerName2 = "brokerName2"; String errThrowBrokerName = "errThrowBrokerName"; MessageExt expireMessage = createMessageExt(TOPIC, "", 0, 3000, System.currentTimeMillis() - 10000, ...
@Override public DirectPipelineResult run(Pipeline pipeline) { try { options = MAPPER .readValue(MAPPER.writeValueAsBytes(options), PipelineOptions.class) .as(DirectOptions.class); } catch (IOException e) { throw new IllegalArgumentException( "Pipeli...
@Test public void testMutatingInputCoderDoFnError() throws Exception { Pipeline pipeline = getPipeline(); pipeline .apply(Create.of(new byte[] {0x1, 0x2, 0x3}, new byte[] {0x4, 0x5, 0x6})) .apply( ParDo.of( new DoFn<byte[], Integer>() { @ProcessEl...
@Override public MavenArtifact searchSha1(String sha1) throws IOException { if (null == sha1 || !sha1.matches("^[0-9A-Fa-f]{40}$")) { throw new IllegalArgumentException("Invalid SHA1 format"); } final List<MavenArtifact> collectedMatchingArtifacts = new ArrayList<>(1); ...
@Test(expected = FileNotFoundException.class) @Ignore public void testMissingSha1() throws Exception { searcher.searchSha1("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); }
public void processVerstrekkingAanAfnemer(VerstrekkingAanAfnemer verstrekkingAanAfnemer){ if (logger.isDebugEnabled()) logger.debug("Processing verstrekkingAanAfnemer: {}", marshallElement(verstrekkingAanAfnemer)); Afnemersbericht afnemersbericht = afnemersberichtRepository.findByOnzeRefere...
@Test public void testProcessAg31(){ String testBsn = "SSSSSSSSS"; Ag31 testAg31 = TestDglMessagesUtil.createTestAg31(testBsn,"O", "SSSSSSSS"); VerstrekkingInhoudType inhoudType = new VerstrekkingInhoudType(); inhoudType.setAg31(testAg31); GeversioneerdType type = new Geversi...
@Override @SuppressWarnings({ "rawtypes" }) synchronized public Value put(Transaction tx, Key key, Value value) throws IOException { Value oldValue = null; if (lastGetNodeCache != null && tx.equals(lastCacheTxSrc.get())) { if(lastGetEntryCache.getKey().equals(key)) { ...
@Test(timeout=60000) public void testPut() throws Exception { createPageFileAndIndex(100); ListIndex<String, Long> listIndex = ((ListIndex<String, Long>) this.index); this.index.load(tx); tx.commit(); int count = 30; tx = pf.tx(); doInsert(count); tx...
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) { return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs)); }
@Test public void testGroupingKeyTypeWithAddingBackSamePartitionFieldInV2Table() { TestTables.TestTable table = TestTables.create(tableDir, "test", SCHEMA, BY_CATEGORY_DATA_SPEC, V2_FORMAT_VERSION); table.updateSpec().removeField("data").commit(); table.updateSpec().addField("data").commit(); ...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testOrderedListInterleavedLocalAddClearReadRange() { Future<Map<Range<Instant>, RangeSet<Long>>> orderedListFuture = Futures.immediateFuture(null); Future<Map<Range<Instant>, RangeSet<Instant>>> deletionsFuture = Futures.immediateFuture(null); when(mockReader.valueFuture( sys...
public void delete( String name ) { initialize(); delete( metaStoreSupplier.get(), name, true ); }
@Test public void testDelete() { addOne(); connectionManager.delete( CONNECTION_NAME ); Assert.assertNull( connectionManager.getConnectionDetails( TestConnectionWithBucketsProvider.SCHEME, CONNECTION_NAME ) ); }
public int poll(final long now) { int expiredTimers = 0; final Timer[] timers = this.timers; final TimerHandler timerHandler = this.timerHandler; while (size > 0 && expiredTimers < POLL_LIMIT) { final Timer timer = timers[0]; if (timer.deadline > now)...
@Test void pollIsANoOpWhenNoTimersWhereScheduled() { final TimerHandler timerHandler = mock(TimerHandler.class); final PriorityHeapTimerService timerService = new PriorityHeapTimerService(timerHandler); assertEquals(0, timerService.poll(Long.MIN_VALUE)); verifyNoInteractions(ti...
public CruiseConfig deserializeConfig(String content) throws Exception { String md5 = md5Hex(content); Element element = parseInputStream(new ByteArrayInputStream(content.getBytes())); LOGGER.debug("[Config Save] Updating config cache with new XML"); CruiseConfig configForEdit = classPa...
@Test void shouldThrowExceptionWhenCommandIsEmpty() { String jobWithCommand = """ <job name="functional"> <tasks> <exec command="" arguments="" /> </tasks> ...
public static InMemoryJobService create( GrpcFnServer<ArtifactStagingService> stagingService, Function<String, String> stagingServiceTokenProvider, ThrowingConsumer<Exception, String> cleanupJobFn, JobInvoker invoker) { return new InMemoryJobService( stagingService, stagingSe...
@Test public void testInvocationCleanup() { final int maxInvocationHistory = 3; service = InMemoryJobService.create( stagingServer, session -> "token", null, invoker, maxInvocationHistory); assertThat(getNumberOfInvocations(), is(0)); Job job1 = runJob(); assertThat(getNumber...
@Override public TagPosition deleteTag(int bucketIndex, int tag) { for (int slotIndex = 0; slotIndex < mTagsPerBucket; slotIndex++) { if (readTag(bucketIndex, slotIndex) == tag) { writeTag(bucketIndex, slotIndex, 0); return new TagPosition(bucketIndex, slotIndex, CuckooStatus.OK); } ...
@Test public void deleteTagTest() { CuckooTable cuckooTable = createCuckooTable(); Random random = new Random(); for (int i = 0; i < NUM_BUCKETS; i++) { for (int j = 0; j < TAGS_PER_BUCKET; j++) { int tag = random.nextInt(0xff); cuckooTable.writeTag(i, j, tag); assertEquals(C...
@Override @Nonnull public ProgressState call() { if (receptionDone) { return collector.offerBroadcast(DONE_ITEM); } if (connectionChanged) { throw new RestartableException("The member was reconnected: " + sourceAddressString); } tracker.reset(); ...
@Test public void when_receiveTwoObjects_then_emitThem() throws IOException { pushObjects(1, 2); t.call(); assertEquals(asList(1, 2), collector.getBuffer()); }
static PrimitiveIterator.OfInt rangeTranslate(int from, int to, IntUnaryOperator translator) { return new IndexIterator(from, to + 1, i -> true, translator); }
@Test public void testRangeTranslate() { assertEquals(IndexIterator.rangeTranslate(11, 18, i -> i - 10), 1, 2, 3, 4, 5, 6, 7, 8); }
public static Subject.Factory<Re2jStringSubject, String> re2jString() { return Re2jStringSubject.FACTORY; }
@Test public void doesNotMatch_string_succeeds() { assertAbout(re2jString()).that("world").doesNotMatch(PATTERN_STR); }
@Override public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch) { return offsetsForTimes(timestampsToSearch, Duration.ofMillis(defaultApiTimeoutMs)); }
@Test public void testOffsetsForTimesTimeoutException() { consumer = newConsumer(); long timeout = 100; doThrow(new TimeoutException("Event did not complete in time and was expired by the reaper")) .when(applicationEventHandler).addAndGet(any()); Throwable t = assertThro...
@ApiOperation(value = "Send test email (sendTestMail)", notes = "Attempts to send test email to the System Administrator User using Mail Settings provided as a parameter. " + "You may change the 'To' email in the user profile of the System Administrator. " + SYSTEM_AUTHORITY_PARAGRAPH) ...
@Test public void testSendTestMail() throws Exception { Mockito.doNothing().when(mailService).sendTestMail(any(), anyString()); loginSysAdmin(); AdminSettings adminSettings = doGet("/api/admin/settings/mail", AdminSettings.class); doPost("/api/admin/settings/testMail", adminSettings)...
@Override public int hashCode() { return Objects.hash( threadName, threadState, activeTasks, standbyTasks, mainConsumerClientId, restoreConsumerClientId, producerClientIds, adminClientId); }
@Test public void shouldNotBeEqualIfDifferInThreadName() { final ThreadMetadata differThreadName = new ThreadMetadataImpl( "different", THREAD_STATE, MAIN_CONSUMER_CLIENT_ID, RESTORE_CONSUMER_CLIENT_ID, PRODUCER_CLIENT_IDS, ADMIN_CLIENT...
@Override public boolean mayHaveMergesPending(String bucketSpace, int contentNodeIndex) { if (!stats.hasUpdatesFromAllDistributors()) { return true; } ContentNodeStats nodeStats = stats.getStats().getNodeStats(contentNodeIndex); if (nodeStats != null) { Conten...
@Test void min_merge_completion_ratio_is_used_when_calculating_may_have_merges_pending() { // Completion ratio is (5-3)/5 = 0.4 assertTrue(Fixture.fromBucketsPending(3, 0.6).mayHaveMergesPending("default", 1)); // Completion ratio is (5-2)/5 = 0.6 assertFalse(Fixture.fromBucketsPendi...
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) { checkArgument( OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp); return new AutoValue_UBinary(binaryOp, lhs, rhs); }
@Test public void bitwiseXor() { assertUnifiesAndInlines( "4 ^ 17", UBinary.create(Kind.XOR, ULiteral.intLit(4), ULiteral.intLit(17))); }
public static <K, V> AsMap<K, V> asMap() { return new AsMap<>(false); }
@Test @Category(ValidatesRunner.class) public void testEmptyMapSideInput() throws Exception { final PCollectionView<Map<String, Integer>> view = pipeline .apply( "CreateEmptyView", Create.empty(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) .apply(View.asMa...