/*
Average

@param array $table of mixed numbers(integer or float)

@return float The average of all array numbers
490326
public static function average($table)
    {
        $cnt = count($table);
        $sum = 0;
        for ($x =0;$x < $cnt; $x++ ){
            $sum = $sum + $table[$x];
        }
        return ($sum/$cnt);
    }
253750
static public function mean(array $sample)
    {
        $count = count($sample);
        if ($count === 0) {
            return false;
        }

        $sum = 0;
        foreach ($sample as $s) {
            $sType = gettype($s);

            if ($sType !== 'integer' && $sType !== 'double') {
                // only deal with numeric values.
                return false;
            }

            $sum += $s;
        }

        return $sum / $count;
    }
1126778
public static function variance(array $values, $sample = false)
    {
        $average = self::mean($values);
        $sum = 0;

        foreach ($values as $value) {
            $diff = pow($value - $average, 2);
            $sum += $diff;
        }

        if (count($values) === 0) {
            return 0;
        }

        $variance = $sum / (count($values) - ($sample ? 1 : 0));

        return $variance;
    }
105433
public static function average($values, $precision = 0) {
		if (empty($values)) {
			return 0.0;
		}
		return round(array_sum($values) / count($values), $precision);
	}
1168080
public function filter($table)
    {
        // set of all column names in the pivoted table mapped with the sum of all column
        // values. used later in truncating and ordering the pivoted table's columns.
        $columnSet = array();

        // if no pivot column was set, use the first one found in the row
        if (empty($this->pivotColumn)) {
            $this->pivotColumn = $this->getNameOfFirstNonLabelColumnInTable($table);
        }

        Log::debug("PivotByDimension::%s: pivoting table with pivot column = %s", __FUNCTION__, $this->pivotColumn);

        foreach ($table->getRows() as $row) {
            $row->setColumns(array('label' => $row->getColumn('label')));

            $associatedTable = $this->getIntersectedTable($table, $row);
            if (!empty($associatedTable)) {
                foreach ($associatedTable->getRows() as $columnRow) {
                    $pivotTableColumn = $columnRow->getColumn('label');

                    $columnValue = $this->getColumnValue($columnRow, $this->pivotColumn);

                    if (isset($columnSet[$pivotTableColumn])) {
                        $columnSet[$pivotTableColumn] += $columnValue;
                    } else {
                        $columnSet[$pivotTableColumn] = $columnValue;
                    }

                    $row->setColumn($pivotTableColumn, $columnValue);
                }

                Common::destroy($associatedTable);
                unset($associatedTable);
            }
        }

        Log::debug("PivotByDimension::%s: pivoted columns set: %s", __FUNCTION__, $columnSet);

        $others = Piwik::translate('General_Others');
        $defaultRow = $this->getPivotTableDefaultRowFromColumnSummary($columnSet, $others);

        Log::debug("PivotByDimension::%s: un-prepended default row: %s", __FUNCTION__, $defaultRow);

        // post process pivoted datatable
        foreach ($table->getRows() as $row) {
            // remove subtables from rows
            $row->removeSubtable();
            $row->deleteMetadata('idsubdatatable_in_db');

            // use default row to ensure column ordering and add missing columns/aggregate cut-off columns
            $orderedColumns = $defaultRow;
            foreach ($row->getColumns() as $name => $value) {
                if (isset($orderedColumns[$name])) {
                    $orderedColumns[$name] = $value;
                } else {
                    $orderedColumns[$others] += $value;
                }
            }
            $row->setColumns($orderedColumns);
        }

        $table->clearQueuedFilters(); // TODO: shouldn't clear queued filters, but we can't wait for them to be run
                                      //       since generic filters are run before them. remove after refactoring
                                      //       processed metrics.

        // prepend numerals to columns in a queued filter (this way, disable_queued_filters can be used
        // to get machine readable data from the API if needed)
        $prependedColumnNames = $this->getOrderedColumnsWithPrependedNumerals($defaultRow, $others);

        Log::debug("PivotByDimension::%s: prepended column name mapping: %s", __FUNCTION__, $prependedColumnNames);

        $table->queueFilter(function (DataTable $table) use ($prependedColumnNames) {
            foreach ($table->getRows() as $row) {
                $row->setColumns(array_combine($prependedColumnNames, $row->getColumns()));
            }
        });
    }
484320
public function countAll(string $table): int
	{
		$sql = 'SELECT * FROM '.$this->driver->quoteTable($table);
		$res = $this->driver->query($sql);
		return (int) count($res->fetchAll());
	}
971288
public function filter($table)
    {
        // Add standard processed metrics
        parent::filter($table);

        $goals = $this->getGoalsInTable($table);
        if (!empty($this->goalsToProcess)) {
            $goals = array_unique(array_merge($goals, $this->goalsToProcess));
            sort($goals);
        }

        $idSite = DataTableFactory::getSiteIdFromMetadata($table);

        $extraProcessedMetrics = $table->getMetadata(DataTable::EXTRA_PROCESSED_METRICS_METADATA_NAME);

        $extraProcessedMetrics[] = new RevenuePerVisit();
        if ($this->processOnlyIdGoal != self::GOALS_MINIMAL_REPORT) {
            foreach ($goals as $idGoal) {
                if (($this->processOnlyIdGoal > self::GOALS_FULL_TABLE
                        || $this->isEcommerce)
                    && $this->processOnlyIdGoal != $idGoal
                ) {
                    continue;
                }

                $extraProcessedMetrics[] = new ConversionRate($idSite, $idGoal); // PerGoal\ConversionRate

                // When the table is displayed by clicking on the flag icon, we only display the columns
                // Visits, Conversions, Per goal conversion rate, Revenue
                if ($this->processOnlyIdGoal == self::GOALS_OVERVIEW) {
                    continue;
                }

                $extraProcessedMetrics[] = new Conversions($idSite, $idGoal); // PerGoal\Conversions or GoalSpecific\
                $extraProcessedMetrics[] = new GoalSpecificRevenuePerVisit($idSite, $idGoal); // PerGoal\Revenue
                $extraProcessedMetrics[] = new Revenue($idSite, $idGoal); // PerGoal\Revenue

                if ($this->isEcommerce) {
                    $extraProcessedMetrics[] = new AverageOrderRevenue($idSite, $idGoal);
                    $extraProcessedMetrics[] = new ItemsCount($idSite, $idGoal);
                }
            }
        }

        $table->setMetadata(DataTable::EXTRA_PROCESSED_METRICS_METADATA_NAME, $extraProcessedMetrics);
    }
386312
public function getTableIndexes( $table )
    {
        $query = "SELECT * FROM information_schema.statistics WHERE table_schema =
                 ? AND table_name = ?";

        $params = [ $this->name, $table ];

        $statement = $this->database->prepare( $query );
        $statement->execute( $params );

        $results = $statement->fetchAll();

        $indexes = [ ];

        if ( !empty( $results ) )
        {
            $name = NULL;

            $i = 0;

            foreach ( $results as $result )
            {
                if ( !in_array( $result[ 'INDEX_NAME' ], $indexes ) )
                {
                    $indexes[ ] = $result[ 'INDEX_NAME' ];
                }
            }
        }

        return $indexes;
    }
877477
public function avg($avg=null)
    {
        $avg = LambdaUtils::toSelectCallable($avg);
        return ($this->sum($avg)/$this->length());
    }
212280
public static function AVERAGE()
    {
        $returnValue = $aCount = 0;

        // Loop through arguments
        foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) {
            if ((is_bool($arg)) &&
                ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
                $arg = (integer) $arg;
            }
            // Is it a numeric value?
            if ((is_numeric($arg)) && (!is_string($arg))) {
                if (is_null($returnValue)) {
                    $returnValue = $arg;
                } else {
                    $returnValue += $arg;
                }
                ++$aCount;
            }
        }

        // Return
        if ($aCount > 0) {
            return $returnValue / $aCount;
        } else {
            return PHPExcel_Calculation_Functions::DIV0();
        }
    }
542689
public function serialize(array $table)
    {
        $buffer = '';

        foreach ($table as $key => $value) {
            $buffer .= $this->serializeShortString($key);
            $buffer .= $this->serializeField($value);
        }

        return $this->serializeByteArray($buffer);
    }
240467
public function avg($key = null)
    {
        if ($count = $this->count()) {
            return $this->sum($key) / $count;
        }
    }
1326948
public function avg($table, $field, $conditions = false)
    {
        return $this->executeAggregate('AVG', $table, $field, $conditions);
    }
536800
public static function average( $arr, $key = null ) 
	{
		if( !is_array( $arr ) ) 
		{
			throw new \InvalidArgumentException('CCArr::average - first argunent has to be an array.');
		}

		if ( is_string( $key ) && CCArr::is_multi( $arr ) ) 
		{
			$arr = CCArr::pick( $key, $arr );
		}

		return ( static::sum( $arr ) / count( $arr ) );
	}
959505
public function avg($column = null)
    {
        $this->prepare();

        $count = $this->count();
        $total = $this->sum($column);

        return ($total/$count);
    }
375987
public function countResults(string $table): int
    {
        $queryBuilder = $this->conn->createQueryBuilder();
        $rows = $queryBuilder->select('COUNT(1)')->from($table)->execute();

        return (int) $rows->fetch(\Doctrine\DBAL\FetchMode::NUMERIC)[0];
    }
689220
function avg(arr) {
    arr = arr || [];
    if (arr.length) {
        var total = sum(arr);
        if (number.isNumber(total)) {
            return total / arr.length;
        } else {
            throw new Error("Cannot average an array of non numbers.");
        }
    } else {
        return 0;
    }
}