List of usage examples for java.util.function Supplier Supplier
Supplier
From source file:edu.cudenver.bios.power.GLMMPowerCalculator.java
/** * Calculate power by integrating over all possible values of the * non-centrality parameter. Best used for designs with a * baseline covariate/*w w w . j a v a 2 s . c om*/ * * @param params GLMM input parameters * @return unconditional power * @throws PowerException */ private double getUnconditionalPower(GLMMTest glmmTest, NonCentralityDistribution nonCentralityDist, double alpha) throws PowerException { // get the approximate critical F value (central F) under the null hypothesis double Fcrit = glmmTest.getCriticalF(GLMMTest.DistributionType.POWER_NULL, alpha); // get the distribution of the noncentrality parameter double ndf = glmmTest.getNumeratorDF(GLMMTest.DistributionType.POWER_ALTERNATIVE); double ddf = glmmTest.getDenominatorDF(GLMMTest.DistributionType.POWER_ALTERNATIVE); debug("Fcrit = " + Fcrit + ", ndf = " + ndf + ", ddf = " + ddf); double h1 = nonCentralityDist.getH1(); double h0 = nonCentralityDist.getH0(); debug("h0 = " + h0 + ", h1 = " + h1); try { if (h1 < h0) { throw new IllegalArgumentException("Integration bounds are " + h0 + " and " + h1 + "."); } double integralResult; numberOfEvaluations = BigInteger.ZERO; if (h1 > h0) { // integrate over all values of non-centrality parameter from h0 to h1 SimpsonIntegrator integrator = new SimpsonIntegrator(); UnconditionalPowerIntegrand integrand = new UnconditionalPowerIntegrand(nonCentralityDist, Fcrit, ndf, ddf); integralResult = integrator.integrate(MAX_EVALUATIONS, integrand, h0, h1); } else { integralResult = 0; } final double I = integralResult; debug(new Supplier<Object>() { @Override public Object get() { return "done with integration: " + "result = " + I + ", " + "number of evaluations = " + numberOfEvaluations + ", " + "log = " + (int) (Math.log(numberOfEvaluations.longValue() - 3) / LOG2 + 0.5); } }); // create a noncentral F dist with non-centrality of H1 NonCentralFDistribution fdist = new NonCentralFDistribution(ndf, ddf, h1); return (1 - fdist.cdf(Fcrit) - 0.5 * integralResult); } catch (RuntimeException e) { LOGGER.warn("exiting getUnconditionalPower abnormally", e); throw new PowerException(e.getMessage(), PowerErrorEnum.INTEGRATION_OVER_DISTRIBUTION_NONCENTRALITY_PARAMETER_FAILED); } }
From source file:org.aesh.terminal.telnet.TelnetHandlerTest.java
@Test public void testSendBinary() throws Exception { final CountDownLatch latch = new CountDownLatch(1); server.start(new Supplier<TelnetHandler>() { @Override/*from w w w. j a va 2 s. c om*/ public TelnetHandler get() { return new TelnetHandler() { private TelnetConnection conn; @Override protected void onOpen(TelnetConnection conn) { this.conn = conn; conn.writeWillOption(Option.BINARY); } @Override protected void onSendBinary(boolean binary) { if (binary) { conn.write(new byte[] { 'h', 'e', 'l', 'l', 'o', -1 }); latch.countDown(); } else { fail("Was not expecting a don't for binary option"); } } @Override protected void onReceiveBinary(boolean binary) { if (binary) { fail("Was not expecting a will for binary option"); } } }; } }); client.setOptionHandler(new SimpleOptionHandler(0, false, false, false, true)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); client.client.registerSpyStream(baos); client.connect("localhost", 4000); latch.await(); Reader reader = new InputStreamReader(client.client.getInputStream()); char[] hello = new char[5]; int num = reader.read(hello); assertEquals(5, num); assertEquals("hello", new String(hello)); byte[] data = baos.toByteArray(); assertEquals(10, data.length); assertEquals((byte) 'h', data[3]); assertEquals((byte) 'e', data[4]); assertEquals((byte) 'l', data[5]); assertEquals((byte) 'l', data[6]); assertEquals((byte) 'o', data[7]); assertEquals((byte) -1, data[8]); assertEquals((byte) -1, data[9]); }
From source file:org.apache.gobblin.writer.PartitionedDataWriter.java
public PartitionedDataWriter(DataWriterBuilder<S, D> builder, final State state) throws IOException { this.isSpeculativeAttemptSafe = true; this.isWatermarkCapable = true; this.baseWriterId = builder.getWriterId(); this.closer = Closer.create(); this.writerBuilder = builder; this.controlMessageHandler = new PartitionDataWriterMessageHandler(); this.partitionWriters = CacheBuilder.newBuilder().build(new CacheLoader<GenericRecord, DataWriter<D>>() { @Override/*w w w . j a va 2 s . co m*/ public DataWriter<D> load(final GenericRecord key) throws Exception { /* wrap the data writer to allow the option to close the writer on flush */ return PartitionedDataWriter.this.closer.register(new InstrumentedPartitionedDataWriterDecorator<>( new CloseOnFlushWriterWrapper<D>(new Supplier<DataWriter<D>>() { @Override public DataWriter<D> get() { try { return createPartitionWriter(key); } catch (IOException e) { throw new RuntimeException("Error creating writer", e); } } }, state), state, key)); } }); if (state.contains(ConfigurationKeys.WRITER_PARTITIONER_CLASS)) { Preconditions.checkArgument(builder instanceof PartitionAwareDataWriterBuilder, String.format("%s was specified but the writer %s does not support partitioning.", ConfigurationKeys.WRITER_PARTITIONER_CLASS, builder.getClass().getCanonicalName())); try { this.shouldPartition = true; this.builder = Optional.of(PartitionAwareDataWriterBuilder.class.cast(builder)); this.partitioner = Optional.of(WriterPartitioner.class.cast(ConstructorUtils.invokeConstructor( Class.forName(state.getProp(ConfigurationKeys.WRITER_PARTITIONER_CLASS)), state, builder.getBranches(), builder.getBranch()))); Preconditions.checkArgument( this.builder.get().validatePartitionSchema(this.partitioner.get().partitionSchema()), String.format("Writer %s does not support schema from partitioner %s", builder.getClass().getCanonicalName(), this.partitioner.getClass().getCanonicalName())); } catch (ReflectiveOperationException roe) { throw new IOException(roe); } } else { this.shouldPartition = false; // Support configuration to close the DataWriter on flush to allow publishing intermediate results in a task CloseOnFlushWriterWrapper closeOnFlushWriterWrapper = new CloseOnFlushWriterWrapper<D>( new Supplier<DataWriter<D>>() { @Override public DataWriter<D> get() { try { return builder.withWriterId(PartitionedDataWriter.this.baseWriterId + "_" + PartitionedDataWriter.this.writerIdSuffix++).build(); } catch (IOException e) { throw new RuntimeException("Error creating writer", e); } } }, state); DataWriter<D> dataWriter = (DataWriter) closeOnFlushWriterWrapper.getDecoratedObject(); InstrumentedDataWriterDecorator<D> writer = this.closer .register(new InstrumentedDataWriterDecorator<>(closeOnFlushWriterWrapper, state)); this.isSpeculativeAttemptSafe = this.isDataWriterForPartitionSafe(dataWriter); this.isWatermarkCapable = this.isDataWriterWatermarkCapable(dataWriter); this.partitionWriters.put(NON_PARTITIONED_WRITER_KEY, writer); this.partitioner = Optional.absent(); this.builder = Optional.absent(); } }
From source file:org.apache.pulsar.broker.PulsarService.java
/** * Start the pulsar service instance./*from w w w . j av a 2s .c o m*/ */ public void start() throws PulsarServerException { mutex.lock(); LOG.info("Starting Pulsar Broker service; version: '{}'", (brokerVersion != null ? brokerVersion : "unknown")); LOG.info("Git Revision {}", PulsarBrokerVersionStringUtils.getGitSha()); LOG.info("Built by {} on {} at {}", PulsarBrokerVersionStringUtils.getBuildUser(), PulsarBrokerVersionStringUtils.getBuildHost(), PulsarBrokerVersionStringUtils.getBuildTime()); try { if (state != State.Init) { throw new PulsarServerException("Cannot start the service once it was stopped"); } // Now we are ready to start services localZooKeeperConnectionProvider = new LocalZooKeeperConnectionService(getZooKeeperClientFactory(), config.getZookeeperServers(), config.getZooKeeperSessionTimeoutMillis()); localZooKeeperConnectionProvider.start(shutdownService); // Initialize and start service to access configuration repository. this.startZkCacheService(); this.bkClientFactory = newBookKeeperClientFactory(); managedLedgerClientFactory = new ManagedLedgerClientFactory(config, getZkClient(), bkClientFactory); this.brokerService = new BrokerService(this); // Start load management service (even if load balancing is disabled) this.loadManager.set(LoadManager.create(this)); // Start the leader election service startLeaderElectionService(); // needs load management service this.startNamespaceService(); this.offloader = createManagedLedgerOffloader(this.getConfiguration()); brokerService.start(); this.webService = new WebService(this); Map<String, Object> attributeMap = Maps.newHashMap(); attributeMap.put(WebService.ATTRIBUTE_PULSAR_NAME, this); Map<String, Object> vipAttributeMap = Maps.newHashMap(); vipAttributeMap.put(VipStatus.ATTRIBUTE_STATUS_FILE_PATH, this.config.getStatusFilePath()); vipAttributeMap.put(VipStatus.ATTRIBUTE_IS_READY_PROBE, new Supplier<Boolean>() { @Override public Boolean get() { // Ensure the VIP status is only visible when the broker is fully initialized return state == State.Started; } }); this.webService.addRestResources("/", VipStatus.class.getPackage().getName(), false, vipAttributeMap); this.webService.addRestResources("/", "org.apache.pulsar.broker.web", false, attributeMap); this.webService.addRestResources("/admin", "org.apache.pulsar.broker.admin.v1", true, attributeMap); this.webService.addRestResources("/admin/v2", "org.apache.pulsar.broker.admin.v2", true, attributeMap); this.webService.addRestResources("/admin/v3", "org.apache.pulsar.broker.admin.v3", true, attributeMap); this.webService.addRestResources("/lookup", "org.apache.pulsar.broker.lookup", true, attributeMap); this.webService.addServlet("/metrics", new ServletHolder( new PrometheusMetricsServlet(this, config.isExposeTopicLevelMetricsInPrometheus(), config.isExposeConsumerLevelMetricsInPrometheus())), false, attributeMap); if (config.isWebSocketServiceEnabled()) { // Use local broker address to avoid different IP address when using a VIP for service discovery this.webSocketService = new WebSocketService(new ClusterData(webServiceAddress, webServiceAddressTls, brokerServiceUrl, brokerServiceUrlTls), config); this.webSocketService.start(); final WebSocketServlet producerWebSocketServlet = new WebSocketProducerServlet(webSocketService); this.webService.addServlet(WebSocketProducerServlet.SERVLET_PATH, new ServletHolder(producerWebSocketServlet), true, attributeMap); this.webService.addServlet(WebSocketProducerServlet.SERVLET_PATH_V2, new ServletHolder(producerWebSocketServlet), true, attributeMap); final WebSocketServlet consumerWebSocketServlet = new WebSocketConsumerServlet(webSocketService); this.webService.addServlet(WebSocketConsumerServlet.SERVLET_PATH, new ServletHolder(consumerWebSocketServlet), true, attributeMap); this.webService.addServlet(WebSocketConsumerServlet.SERVLET_PATH_V2, new ServletHolder(consumerWebSocketServlet), true, attributeMap); final WebSocketServlet readerWebSocketServlet = new WebSocketReaderServlet(webSocketService); this.webService.addServlet(WebSocketReaderServlet.SERVLET_PATH, new ServletHolder(readerWebSocketServlet), true, attributeMap); this.webService.addServlet(WebSocketReaderServlet.SERVLET_PATH_V2, new ServletHolder(readerWebSocketServlet), true, attributeMap); } if (LOG.isDebugEnabled()) { LOG.debug("Attempting to add static directory"); } this.webService.addStaticResources("/static", "/static"); // Register heartbeat and bootstrap namespaces. this.nsservice.registerBootstrapNamespaces(); schemaRegistryService = SchemaRegistryService.create(this); webService.start(); this.metricsGenerator = new MetricsGenerator(this); // By starting the Load manager service, the broker will also become visible // to the rest of the broker by creating the registration z-node. This needs // to be done only when the broker is fully operative. this.startLoadManagementService(); state = State.Started; acquireSLANamespace(); // start function worker service if necessary this.startWorkerService(); LOG.info( "messaging service is ready, bootstrap service on port={}, broker url={}, cluster={}, configs={}", config.getWebServicePort().get(), brokerServiceUrl, config.getClusterName(), ReflectionToStringBuilder.toString(config)); } catch (Exception e) { LOG.error(e.getMessage(), e); throw new PulsarServerException(e); } finally { mutex.unlock(); } }
From source file:org.polymap.model2.store.geotools.MemoryFeatureCollection.java
@Override public ReferencedEnvelope getBounds() { return bounds.get(new Supplier<ReferencedEnvelope>() { public ReferencedEnvelope get() { ReferencedEnvelope result = new ReferencedEnvelope(); for (Feature feature : data.values()) { BoundingBox featureBounds = feature.getBounds(); if (!featureBounds.isEmpty()) { result.include(featureBounds); }/* w w w . jav a 2 s. com*/ } return result; } }); }
From source file:shuffle.fwk.service.roster.EditRosterService.java
private Component makeUpperPanel() { JPanel ret = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0;/*from w w w .ja v a 2 s. co m*/ c.weighty = 0.0; c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.gridheight = 1; c.gridx += 1; c.weightx = 0.0; JPanel typePanel = new JPanel(); typePanel.add(new JLabel(getString(KEY_TYPE))); typeChooser = new TypeChooser(true); typePanel.add(typeChooser); typePanel.setToolTipText(getString(KEY_TYPE_TOOLTIP)); typeChooser.setToolTipText(getString(KEY_TYPE_TOOLTIP)); ret.add(typePanel, c); c.gridx += 1; c.weightx = 0.0; JPanel levelPanel = new JPanel(); levelPanel.add(new JLabel(getString(KEY_LEVEL))); SpinnerNumberModel snm = new SpinnerNumberModel(0, 0, Species.MAX_LEVEL, 1); levelSpinner = new JSpinner(snm); levelPanel.add(levelSpinner); levelPanel.setToolTipText(getString(KEY_LEVEL_TOOLTIP)); levelSpinner.setToolTipText(getString(KEY_LEVEL_TOOLTIP)); JButton applyAllButton = new JButton(getString(KEY_SET_FOR_ALL)); applyAllButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { applyLevelToAll(); } }); applyAllButton.setToolTipText(getString(KEY_SET_FOR_ALL_TOOLTIP)); levelPanel.add(applyAllButton); ret.add(levelPanel, c); c.gridx += 1; c.weightx = 1.0; JPanel stringPanel = new JPanel(new GridBagLayout()); GridBagConstraints sc = new GridBagConstraints(); sc.fill = GridBagConstraints.HORIZONTAL; sc.gridx = 1; stringPanel.add(new JLabel(getString(KEY_NAME)), sc); textField = new JTextField(); sc.gridx += 1; sc.weightx = 1.0; sc.insets = new Insets(0, 5, 0, 5); stringPanel.add(textField, sc); stringPanel.setToolTipText(getString(KEY_NAME_TOOLTIP)); textField.setToolTipText(getString(KEY_NAME_TOOLTIP)); ret.add(stringPanel, c); c.gridx += 1; c.weightx = 0.0; megaFilter = new JCheckBox(getString(KEY_MEGA_FILTER)); megaFilter.setToolTipText(getString(KEY_MEGA_FILTER_TOOLTIP)); ret.add(megaFilter, c); c.gridx += 1; c.weightx = 0.0; effectFilter = new EffectChooser(false, EffectChooser.DefaultEntry.NO_FILTER); effectFilter.setToolTipText(getString(KEY_EFFECT_FILTER_TOOLTIP)); ret.add(effectFilter, c); getMinUpperPanel = new Supplier<Dimension>() { @Override public Dimension get() { Dimension ret = new Dimension(10 + 50, 0); for (Component c : new Component[] { typePanel, levelPanel, stringPanel, megaFilter, effectFilter }) { Dimension temp = c.getPreferredSize(); int width = temp.width + ret.width; int height = Math.max(temp.height, ret.height); ret.setSize(width, height); } return ret; } }; return ret; }
From source file:shuffle.fwk.service.teams.EditTeamService.java
private Component makeUpperPanel() { JPanel ret = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0;// w w w . java2 s. co m c.weighty = 0.0; c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.gridheight = 1; c.gridx += 1; c.weightx = 0.0; JPanel typePanel = new JPanel(); typePanel.add(new JLabel(getString(KEY_TYPE))); typeChooser = new TypeChooser(true); typePanel.add(typeChooser); typePanel.setToolTipText(getString(KEY_TYPE_TOOLTIP)); typeChooser.setToolTipText(getString(KEY_TYPE_TOOLTIP)); ret.add(typePanel, c); c.gridx += 1; c.weightx = 0.0; JPanel levelPanel = new JPanel(); levelPanel.add(new JLabel(getString(KEY_LEVEL))); SpinnerNumberModel snm = new SpinnerNumberModel(0, 0, Species.MAX_LEVEL, 1); levelSpinner = new JSpinner(snm); levelPanel.add(levelSpinner); levelPanel.setToolTipText(getString(KEY_LEVEL_TOOLTIP)); levelSpinner.setToolTipText(getString(KEY_LEVEL_TOOLTIP)); ret.add(levelPanel, c); c.gridx += 1; c.weightx = 1.0; JPanel stringPanel = new JPanel(new GridBagLayout()); GridBagConstraints sc = new GridBagConstraints(); sc.fill = GridBagConstraints.HORIZONTAL; sc.gridx = 1; stringPanel.add(new JLabel(getString(KEY_NAME)), sc); textField = new JTextField(); sc.gridx += 1; sc.weightx = 1.0; sc.insets = new Insets(0, 5, 0, 5); stringPanel.add(textField, sc); stringPanel.setToolTipText(getString(KEY_NAME_TOOLTIP)); textField.setToolTipText(getString(KEY_NAME_TOOLTIP)); ret.add(stringPanel, c); c.gridx += 1; c.weightx = 0.0; megaFilter = new JCheckBox(getString(KEY_MEGA_FILTER)); megaFilter.setToolTipText(getString(KEY_MEGA_FILTER_TOOLTIP)); ; ret.add(megaFilter, c); c.gridx += 1; c.weightx = 0.0; effectFilter = new EffectChooser(false, EffectChooser.DefaultEntry.NO_FILTER); effectFilter.setToolTipText(getString(KEY_EFFECT_FILTER_TOOLTIP)); ret.add(effectFilter, c); c.gridx += 1; c.weightx = 0.0; @SuppressWarnings("serial") JButton copyToLauncher = new JButton(new AbstractAction(getString(KEY_MAKE_DEFAULT)) { @Override public void actionPerformed(ActionEvent e) { makeTeamDefault(); } }); copyToLauncher.setToolTipText(getString(KEY_MAKE_DEFAULT_TOOLTIP)); ret.add(copyToLauncher, c); getMinUpperPanel = new Supplier<Dimension>() { @Override public Dimension get() { Dimension ret = new Dimension(10 + 50, 0); for (Component c : new Component[] { typePanel, levelPanel, stringPanel, megaFilter, effectFilter, copyToLauncher }) { Dimension temp = c.getPreferredSize(); int width = temp.width + ret.width; int height = Math.max(temp.height, ret.height); ret.setSize(width, height); } return ret; } }; return ret; }