Squirt the metrics over UDP

@param array $data
@param int|float $sampleRate
165065
public function send(array $data, $sampleRate = 1)
    {
        if (!$this->enable) {
            return;
        }

        // sampling
        $sampledData = array();
        if ($sampleRate < 1) {
            foreach ($data as $stat => $value) {
                if ((mt_rand() / mt_getrandmax()) <= $sampleRate) {
                    $sampledData[$stat] = "$value|@$sampleRate";
                }
            }
        } else {
            $sampledData = $data;
        }
        if (empty($sampledData)) {
            return;
        }

        $fp = fsockopen('udp://' . $this->host, $this->port, $errno, $errstr);
        if (!$fp) {
            return;
        }
        foreach ($sampledData as $stat => $value) {
            fwrite($fp, $stat . ':' . $value);
        }
        fclose($fp);
    }
677826
protected function calculate_sample($sampleid, $samplesorigin, $starttime = false, $endtime = false) {
        $user = $this->retrieve('user', $sampleid);
        return ($user->trackforums) ? self::get_max_value() : self::get_min_value();
    }
968032
public function setSamplingRate($samplingRate)
    {
        if ($samplingRate <= 0.0 || 1.0 < $samplingRate) {
            throw new \LogicException('Sampling rate shall be within ]0, 1]');
        }
        $this->samplingRate = $samplingRate;
        $this->samplingFunction = function($min, $max){
            return rand($min, $max);
        };
    }
1119211
protected function calculate_sample($sampleid, \core_analytics\analysable $analysable, $starttime = false, $endtime = false) {

        $noteachersindicator = $this->retrieve('\core_course\analytics\indicator\no_teacher', $sampleid);
        $nostudentsindicator = $this->retrieve('\core_course\analytics\indicator\no_student', $sampleid);
        if ($noteachersindicator == \core_course\analytics\indicator\no_teacher::get_min_value() ||
                $nostudentsindicator == \core_course\analytics\indicator\no_student::get_min_value()) {
            // No teachers or no students :(.
            return 1;
        }
        return 0;
    }
798955
def sample_rate(self, value):
        
        if value == self._defaults['sampleRate'] and 'sampleRate' in self._values:
            del self._values['sampleRate']
        else:
            self._values['sampleRate'] = value
1084000
public function send($data, $sampleRate = 1, array $tags = null)
    {

        // sampling
        $sampledData = array();

        if ($sampleRate < 1) {
            foreach ($data as $stat => $value) {
                if ((mt_rand() / mt_getrandmax()) <= $sampleRate) {
                    $sampledData[] = [$stat, "$value|@$sampleRate"];
                }
            }
        } else {
            foreach ($data as $stat => $value) {
                $sampledData[] = [$stat, $value];
            }
        }

        if (empty($sampledData)) {
            return Observable::emptyObservable();
        }

        $observableSequence = Observable::fromArray($sampledData)
            ->map(function($d) use ($tags) {
                $stat = $d[0];
                $value = $d[1];
                if ($tags !== null && is_array($tags) && count($tags) > 0) {
                    $value .= '|';
                    foreach ($tags as $tag_key => $tag_val) {
                        if (is_array($tag_val)) {
                            $flattenTagVal = array();
                            array_walk_recursive($array, function($a) use (&$return) { $flattenTagVal[] = $a; });
                            $tag_val = implode("\n", $flattenTagVal);
                        }
                        $value .= '#' . $tag_key . ':' . $tag_val . ',';
                    }
                    $value = substr($value, 0, -1);
                }
                elseif (isset($tags) && !empty($tags)) {
                    $value .= '|#' . $tags;
                }
                return $this->reportMetric("$stat:$value");
            });
        return $observableSequence->mergeAll();
    }
567522
public function populate($data = array())
    {
        parent::populate($data);

        if (isset($data['winners']) && $data['winners'] !== null) {
            $this->winners = $data['winners'];
        }

        if (isset($data['timer']) && $data['timer'] !== null) {
            $this->timer = $data['timer'];
        }
        if (isset($data['timerDuration']) && $data['timerDuration'] !== null) {
            $this->timerDuration = $data['timerDuration'];
        }
        if (isset($data['questionGrouping']) && $data['questionGrouping'] !== null) {
            $this->questionGrouping = $data['questionGrouping'];
        }

        if (isset($data['maxPoints']) && $data['maxPoints'] !== null) {
            $this->maxPoints = $data['maxPoints'];
        }

        if (isset($data['maxCorrectAnswers']) && $data['maxCorrectAnswers'] !== null) {
            $this->maxCorrectAnswers = $data['maxCorrectAnswers'];
        }

        if (isset($data['displayGoodAnswers']) && $data['displayGoodAnswers'] !== null) {
            $this->displayGoodAnswers = $data['displayGoodAnswers'];
        }

        if (isset($data['displayStats']) && $data['displayStats'] !== null) {
            $this->displayStats = $data['displayStats'];
        }
    }
781133
public static function insertStats( array $data )
    {
        foreach( $data as $datapoint)
        {

            $url = $datapoint['url'];
            // always remove fragments
            $url = preg_replace( '/#.*^/', '', $url );
            // optionally remove query string
            if ( self::$options['keep_query_string'] == false )
            {
                $url = preg_replace( '/\?.*/', '', $url );
            }
            // optionally remove unordered view parameters
            if ( self::$options['keep_view_params'] == false )
            {
                $url = preg_replace( '!/\([^?]*!', '', $url );
            }
            $idx = md5( $url );
            if ( isset( self::$urls[$idx] ) )
            {
                self::$urls[$idx]['count'] = self::$urls[$idx]['count'] + 1;
                // we assume increasing monotonic time
                self::$urls[$idx]['last'] = $datapoint['time'];
            }
            else
            {
                self::$urls[$idx] = array(
                    'url' => $url,
                    'count' => 1,
                    'first' => $datapoint['time'],
                    'last' => $datapoint['time']
                );
            }
        }
    }
576053
public function gauge($metric, $level, array $tags = array(), $sampleRate = AbstractMetric::DEFAULT_SAMPLE_RATE)
    {
        return new Gauge($this->prefix($metric), $level, array_merge($this->defaultTags, $tags), $sampleRate);
    }
997070
protected function wavToMp3($data)
    {
        if (!file_exists(self::$lame_binary_path) || !is_executable(self::$lame_binary_path)) {
            throw new Exception('Lame binary "' . $this->lame_binary_path . '" does not exist or is not executable');
        }

        // size of wav data input
        $size = strlen($data);

        // file descriptors for reading and writing to the Lame process
        $descriptors = array(
                0 => array('pipe', 'r'), // stdin
                1 => array('pipe', 'w'), // stdout
                2 => array('pipe', 'a'), // stderr
        );

        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            // workaround for Windows conversion
            // writing to STDIN seems to hang indefinitely after writing approximately 0xC400 bytes
            $wavinput = tempnam(sys_get_temp_dir(), 'wav');
            if (!$wavinput) {
                throw new Exception('Failed to create temporary file for WAV to MP3 conversion');
            }
            file_put_contents($wavinput, $data);
            $size = 0;
        } else {
            $wavinput = '-'; // stdin
        }

        // Mono, variable bit rate, 32 kHz sampling rate, read WAV from stdin, write MP3 to stdout
        $cmd  = sprintf("%s -m m -v -b 32 %s -", self::$lame_binary_path, $wavinput);
        $proc = proc_open($cmd, $descriptors, $pipes);

        if (!is_resource($proc)) {
            throw new Exception('Failed to open process for MP3 encoding');
        }

        stream_set_blocking($pipes[0], 0); // set stdin to be non-blocking

        for ($written = 0; $written < $size; $written += $len) {
            // write to stdin until all WAV data is written
            $len = fwrite($pipes[0], substr($data, $written, 0x20000));

            if ($len === 0) {
                // fwrite wrote no data, make sure process is still alive, otherwise wait for it to process
                $status = proc_get_status($proc);
                if ($status['running'] === false) break;
                usleep(25000);
            } else if ($written < $size) {
                // couldn't write all data, small pause and try again
                usleep(10000);
            } else if ($len === false) {
                // fwrite failed, should not happen
                break;
            }
        }

        fclose($pipes[0]);

        $data = stream_get_contents($pipes[1]);
        $err  = trim(stream_get_contents($pipes[2]));

        fclose($pipes[1]);
        fclose($pipes[2]);

        $return = proc_close($proc);

        if ($wavinput != '-') unlink($wavinput); // delete temp file on Windows

        if ($return !== 0) {
            throw new Exception("Failed to convert WAV to MP3.  Shell returned ({$return}): {$err}");
        } else if ($written < $size) {
            throw new Exception('Failed to convert WAV to MP3.  Failed to write all data to encoder');
        }

        return $data;
    }
944418
private function setDataset(array $data = [])
    {
        // If we don't have any data, use input if we're allowed
        if ( ! count($data) && $this->allowHydrationFromInput) $data = Input::all();

        $this->dataset = $data;
    }
818141
public function transform(array &$samples) : void
    {
        foreach ($samples as &$sample) {
            $norm = 0.;

            foreach ($sample as &$feature) {
                $norm += $feature ** 2;
            }

            $norm = sqrt($norm ?: EPSILON);

            foreach ($sample as &$feature) {
                $feature /= $norm;
            }
        }
    }
421378
protected function localOutlierFactor(array $sample) : float
    {
        if (empty($this->lrds)) {
            throw new RuntimeException('Local reachability distances have'
                . ' not been computed, must train estimator first.');
        }

        $distances = $this->localRegion($sample);

        $lrd = $this->localReachabilityDensity($distances);

        $lrds = array_intersect_key($this->lrds, $distances);

        $ratios = [];

        foreach ($lrds as $lHat) {
            $ratios[] = $lHat / $lrd;
        }

        return Stats::mean($ratios);
    }
118263
protected function inertia(array $samples) : float
    {
        $inertia = 0.;

        foreach ($samples as $sample) {
            foreach ($this->centroids as $centroid) {
                $inertia += $this->kernel->compute($sample, $centroid);
            }
        }

        return $inertia;
    }
822121
void sampleReceived(SolverAggregatorInterface aggregator,
			SampleMessage sample) {
		if (!this.sampleQueue.offer(sample) && this.warnBufferFull) {
			log.warn("Unable to insert a sample due to a full buffer.");
		}
	}
516085
public function endTiming($key, $sampleRate = 1)
    {
        $end = gettimeofday(true);
        if (isset($this->timings[$key])) {
            $timing = ($end - $this->timings[$key]) * 1000;
            $this->timing($key, $timing, $sampleRate);
            unset($this->timings[$key]);
            return $timing;
        }
        return null;
    }
190187
public static function insertStats( array $data )
    {
        $vars = array_values( eZPerfLoggerINI::variable( 'GeneralSettings', 'TrackVariables' ) );
        foreach( $data as $datapoint )
        {
            foreach( $datapoint['counters'] as $i => $value )
            {
                $varname = $vars[$i];
                if ( !isset( self::$stats[$varname]['min'] ) || self::$stats[$varname]['min'] > $value )
                {
                    self::$stats[$varname]['min'] = $value;
                }
                if ( !isset( self::$stats[$varname]['max'] ) || self::$stats[$varname]['max'] < $value )
                {
                    self::$stats[$varname]['max'] = $value;
                }
                self::$stats[$varname]['total'] = self::$stats[$varname]['total'] + $value;
            }
        }
        self::$statsCount = self::$statsCount + count( $data );
    }