Whether to sample events, and if so how much to allow through to the server (from 0.0 to 1.0).

@param dsn Sentry server DSN which may contain options.
@return The ratio of events to allow through to server, or null if sampling is disabled.
517937
protected Double getSampleRate(Dsn dsn) {
        return Util.parseDouble(Lookup.lookup(SAMPLE_RATE_OPTION, dsn), null);
    }
184178
@Bean Tracing tracing(
      @Lazy Reporter<Span> reporter, @Value("${zipkin.self-tracing.sample-rate:1.0}") float rate) {
    return Tracing.newBuilder()
        .localServiceName("zipkin-server")
        .sampler(rate < 0.01 ? BoundarySampler.create(rate) : Sampler.create(rate))
        .currentTraceContext(currentTraceContext())
        .spanReporter(reporter)
        .build();
  }
518563
protected Connection createHttpConnection(Dsn dsn) {
        URL sentryApiUrl = HttpConnection.getSentryApiUrl(dsn.getUri(), dsn.getProjectId());

        String proxyHost = getProxyHost(dsn);
        String proxyUser = getProxyUser(dsn);
        String proxyPass = getProxyPass(dsn);
        int proxyPort = getProxyPort(dsn);

        Proxy proxy = null;
        if (proxyHost != null) {
            InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
            proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
            if (proxyUser != null && proxyPass != null) {
                Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass));
            }
        }

        Double sampleRate = getSampleRate(dsn);
        EventSampler eventSampler = null;
        if (sampleRate != null) {
            eventSampler = new RandomEventSampler(sampleRate);
        }

        HttpConnection httpConnection = new HttpConnection(sentryApiUrl, dsn.getPublicKey(),
            dsn.getSecretKey(), proxy, eventSampler);

        Marshaller marshaller = createMarshaller(dsn);
        httpConnection.setMarshaller(marshaller);

        int timeout = getTimeout(dsn);
        httpConnection.setConnectionTimeout(timeout);

        boolean bypassSecurityEnabled = getBypassSecurityEnabled(dsn);
        httpConnection.setBypassSecurity(bypassSecurityEnabled);

        return httpConnection;
    }
1163728
public static int sampleFromDistribution(double[] d, Random random) {
    // sample from the uniform [0,1]
    double r = random.nextDouble();
    // now compare its value to cumulative values to find what interval it falls in
    double total = 0;
    for (int i = 0; i < d.length - 1; i++) {
      if (Double.isNaN(d[i])) {
        throw new RuntimeException("Can't sample from NaN");
      }
      total += d[i];
      if (r < total) {
        return i;
      }
    }
    return d.length - 1; // in case the "double-math" didn't total to exactly 1.0
  }
1142128
@Test(groups = {SAMPLES})
    public void getDE1MonitoringStatsForLastHourGroupedByServers() {
        List<MonitoringStatsEntry> stats = statisticsService
            .monitoringStats()
            .forDataCenters(
                new DataCenterFilter()
                    .dataCenters(DE_FRANKFURT)
            )
            .forTime(new ServerMonitoringFilter()
                .last(Duration.ofHours(1))
                .type(MonitoringType.REALTIME)
                .interval(Duration.ofMinutes(10)))
            .groupByDataCenter();

        assertNotNull(stats);
    }
436304
@Override
  public Regions getAvailableRegions(Integer pageNo)
      throws DigitalOceanException, RequestUnsuccessfulException {
    validatePageNo(pageNo);
    return (Regions) perform(new ApiRequest(ApiAction.AVAILABLE_REGIONS, pageNo, DEFAULT_PAGE_SIZE))
        .getData();
  }
63099
private static boolean checkForSamplingProperties(Node node) {
        Set<Property> samplingProperties = node instanceof ContainerNode ?
                ((ContainerNode) node).getPropertiesIncludingDescendants(Tags.SAMPLING_PRIORITY.getKey()) :
                node.getProperties(Tags.SAMPLING_PRIORITY.getKey());

        for (Property prop: samplingProperties) {
            int priority = 0;
            try {
                priority = Integer.parseInt(prop.getValue());
            } catch (NumberFormatException ex) {
                // continue on error
            }

            if (priority > 0) {
                return true;
            }
        }

        return false;
    }
1023861
private static boolean sample(Long rootId) {
        if (Double.compare(sampleRate, 1.0d) >= 0)
            return true;
        int mod = (int) (Math.abs(rootId) % PRECISION);
        int threshold = (int) (sampleRate * PRECISION);
        return mod < threshold;
    }
657635
protected int getAsyncThreads(Dsn dsn) {
        return Util.parseInteger(Lookup.lookup(ASYNC_THREADS_OPTION, dsn),
            Runtime.getRuntime().availableProcessors());
    }
290720
public GetOneDomainPlayCountResponse getOneDomainPlayCount(GetOneDomainStatisticsRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        checkNotNull(request.getDomain(), "The domain parameter can not be null");
        checkStringNotEmpty(request.getTimeInterval(), "timeInterval should NOT be null");
        checkStringNotEmpty(request.getStartTime(), "startTime should NOT be null");

        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request,
                STATISTICS, LIVE_DOMAIN, request.getDomain(), "playcount");

        internalRequest.addParameter("timeInterval", request.getTimeInterval());
        internalRequest.addParameter("startTime", request.getStartTime());
        if (request.getEndTime() != null) {
            internalRequest.addParameter("endTime", request.getEndTime());
        }
        return invokeHttpClient(internalRequest, GetOneDomainPlayCountResponse.class);
    }
663411
@Test(groups = {SAMPLES})
    public void getBillingStatisticsByAllDatacenters() {
        Statistics summarize = statisticsService
            .billingStats()
            .forDataCenters(
                new DataCenterFilter()
                    .dataCenters(DE_FRANKFURT, US_EAST_STERLING)
            )
            .summarize();

        assertNotNull(summarize);
    }
899593
protected RejectedExecutionHandler getRejectedExecutionHandler(Dsn dsn) {
        String overflowName = ASYNC_QUEUE_OVERFLOW_DEFAULT;
        String asyncQueueOverflowOption = Lookup.lookup(ASYNC_QUEUE_OVERFLOW_OPTION, dsn);
        if (!Util.isNullOrEmpty(asyncQueueOverflowOption)) {
            overflowName = asyncQueueOverflowOption.toLowerCase();
        }

        RejectedExecutionHandler handler = REJECT_EXECUTION_HANDLERS.get(overflowName);
        if (handler == null) {
            String options = Arrays.toString(REJECT_EXECUTION_HANDLERS.keySet().toArray());
            throw new RuntimeException("RejectedExecutionHandler not found: '" + overflowName
                + "', valid choices are: " + options);
        }

        return handler;
    }
773582
public boolean process(ContentEvent event) {
		InstanceContentEvent inEvent = (InstanceContentEvent) event; //((s4Event) event).getContentEvent();
		//InstanceEvent inEvent = (InstanceEvent) event;

		if (inEvent.getInstanceIndex() < 0) {
			// End learning
			predictionStream.put(event);
			return false;
		}


                if (inEvent.isTesting()){ 
			Instance trainInst = inEvent.getInstance();
			for (int i = 0; i < sizeEnsemble; i++) {
				Instance weightedInst = trainInst.copy();
				//weightedInst.setWeight(trainInst.weight() * k);
				InstanceContentEvent instanceContentEvent = new InstanceContentEvent(
						inEvent.getInstanceIndex(), weightedInst, false, true);
				instanceContentEvent.setClassifierIndex(i);
				instanceContentEvent.setEvaluationIndex(inEvent.getEvaluationIndex());	
				predictionStream.put(instanceContentEvent);
			}
		}
                
                		/* Estimate model parameters using the training data. */
		if (inEvent.isTraining()) {
			train(inEvent);
		} 
		return false;
	}
1057905
public synchronized Iterable<IGenericEvent<T>> getSubscribers(String eventName) {
        List<IGenericEvent<T>> subscribers = getSubscribers(eventName, false);
        return subscribers == null ? null : new ArrayList<>(subscribers);
    }
437518
@Override
	public List<CounterSample> getCounterSamples(String namePattern) {
		List<CounterSample> counterSamples = new ArrayList<>();
		for (Simon simon : manager.getSimons(SimonPattern.createForCounter(namePattern))) {
			counterSamples.add(sampleCounter(simon));
		}
		return counterSamples;
	}
713880
@Override
    public boolean allowChain ( CommonServerMessageBlockRequest next ) {
        return getConfig().isAllowCompound(getClass().getSimpleName()) && getConfig().isAllowCompound(next.getClass().getSimpleName());
    }
1033285
public final void sample()
  {
    long count = _count.get();
    long lastCount = _lastAvgCount.getAndSet(count);
    long time = _time.get();
    long lastTime = _lastAvgTime.getAndSet(time);

    if (count == lastCount)
      _value = 0;
    else
      _value = _scale * (time - lastTime) / (double) (count - lastCount);
  }