Momentum

@param array $real       Array of real values.
@param int   $timePeriod [OPTIONAL] [DEFAULT 10] Number of period. Valid range from 2 to 100000.

@return array Returns an array with calculated data or false on failure.
@throws \Exception
767199
public static function mom(array $real, int $timePeriod = null): array
    {
        $timePeriod = $timePeriod ?? 10;
        $return     = trader_mom($real, $timePeriod);
        static::checkForError();

        return $return;
    }
120400
public function getStaticRealm(): StaticData\StaticRealmDto
    {
	    $result = false;
	    try
	    {
		    // Fetch StaticData from JSON files
		    $result = DataDragonAPI::getStaticRealms($this->getSetting(self::SET_REGION));
		    if (!$result) throw new ServerException("StaticData failed to be loaded.");

		    $this->result_data = $result;
	    }
	    catch (DataDragonExceptions\ArgumentException $ex)
	    {
		    throw new RequestException($ex->getMessage(), $ex->getCode());
	    }
	    finally
	    {
		    // Parse array and create instances
		    return new StaticData\StaticRealmDto($result, $this);
	    }
    }
1365392
public static function niceDuration($seconds, $limitPeriods = 7, $zeros = false)
    {
        // Define time periods
        $periods = [
            'years'     => 31556926,
            'months'    => 2629743,
            //'weeks'     => 604800,
            'days'      => 86400,
            'hours'     => 3600,
            'minutes'   => 60,
            'seconds'   => 1,
        ];

        // Break into periods
        $seconds = (float) $seconds;
        $segments = [];
        foreach ($periods as $period => $value) {
            if ($limitPeriods >= 1) {
                $count = floor($seconds / $value);
                $seconds = $seconds % $value;
            } else {
                $count = round($seconds / $value);
                $seconds = 0;
            }
            if (($count == 0 && !$zeros) or $limitPeriods < 1) {
                continue;
            }
            $segments[strtolower($period)] = $count;

            $limitPeriods--;
        }

        // Build the string
        $string = [];
        foreach ($segments as $key => $value) {
            $segment_name = substr($key, 0, -1);
            $segment = $value . ' ' . $segment_name;
            if ($value != 1) {
                $segment .= 's';
            }
            $string[] = $segment;
        }

        return implode(', ', $string);
    }
914225
public function getTransitionsForAction($actionName, $actionType, $idSite, $period, $date,
                                            $segment = false, $limitBeforeGrouping = false, $parts = 'all')
    {
        Piwik::checkUserHasViewAccess($idSite);

        // get idaction of the requested action
        $idaction = $this->deriveIdAction($actionName, $actionType);
        if ($idaction < 0) {
            throw new Exception('NoDataForAction');
        }

        // prepare log aggregator
        $segment = new Segment($segment, $idSite);
        $site = new Site($idSite);
        $period = Period\Factory::build($period, $date);
        $params = new ArchiveProcessor\Parameters($site, $period, $segment);
        $logAggregator = new LogAggregator($params);

        // prepare the report
        $report = array(
            'date' => Period\Factory::build($period->getLabel(), $date)->getLocalizedShortString()
        );

        $partsArray = explode(',', $parts);
        if ($parts == 'all' || in_array('internalReferrers', $partsArray)) {
            $this->addInternalReferrers($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping);
        }
        if ($parts == 'all' || in_array('followingActions', $partsArray)) {
            $includeLoops = $parts != 'all' && !in_array('internalReferrers', $partsArray);
            $this->addFollowingActions($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping, $includeLoops);
        }
        if ($parts == 'all' || in_array('externalReferrers', $partsArray)) {
            $this->addExternalReferrers($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping);
        }

        // derive the number of exits from the other metrics
        if ($parts == 'all') {
            $report['pageMetrics']['exits'] = $report['pageMetrics']['pageviews']
                - $this->getTotalTransitionsToFollowingActions()
                - $report['pageMetrics']['loops'];
        }

        // replace column names in the data tables
        $reportNames = array(
            'previousPages'         => true,
            'previousSiteSearches'  => false,
            'followingPages'        => true,
            'followingSiteSearches' => false,
            'outlinks'              => true,
            'downloads'             => true
        );
        foreach ($reportNames as $reportName => $replaceLabel) {
            if (isset($report[$reportName])) {
                $columnNames = array(Metrics::INDEX_NB_ACTIONS => 'referrals');
                if ($replaceLabel) {
                    $columnNames[Metrics::INDEX_NB_ACTIONS] = 'referrals';
                }
                $report[$reportName]->filter('ReplaceColumnNames', array($columnNames));
            }
        }

        return $report;
    }
634271
public function getPeriodFirstDate($periodValue)
    {
        $result = $periodValue;
        if ($this->isPeriodYear($periodValue)) {
            $dt = date_create_from_format('Y', $periodValue);
            $ts = strtotime('first day of January', $dt->getTimestamp());
            $dt = $this->toDateTime($ts);
            $result = date_format($dt, 'Ymd');
        } else {
            if ($this->isPeriodMonth($periodValue)) {
                $dt = date_create_from_format('Ymd', $periodValue . '01');
                $ts = strtotime('first day of', $dt->getTimestamp());
                $dt = $this->toDateTime($ts);
                $result = date_format($dt, 'Ymd');
            }
        }
        return $result;
    }
292136
function getPeriodoSala (periodo) {
  assert.ok(typeof periodo === 'number' || periodo instanceof Date, '[senadores-asistencia]: El periodo ingresado debe ser un número o una fecha.')

  let _period = {}
  if (typeof periodo === 'number') {
    _period = periods.filter(period => period.legislatura === periodo)
    // search directly by period id
    if (_period.length > 0) return _period[0]
    // search only by year
    _period = periods.filter(period => {
      return period.desde.getFullYear() <= periodo && periodo <= period.hasta.getFullYear()
    })[0]
    assert.ok(_period, '[senadores-asistencia]: Periodo de busqueda no encontrado')
    console.warn('[senadores-asistencia]: Solo se puede consultar por periodo legislativo. Si para un mismo año existe más de un periodo legislativo, solo se obtendran los resultados del primer periodo encontrado, por lo que jamas se obtendran los periodos posteriores en caso de existir. Prefiera busquedas por fecha o id de legislatura.')
    return _period
  }
  if (periodo instanceof Date) {
    // search by date
    _period = periods.filter(period => {
      return period.desde.getTime() <= periodo.getTime() && periodo.getTime() <= period.hasta.getTime()
    })[0]
    assert.ok(_period, '[senadores-asistencia]: Periodo de busqueda no encontrado')
    return _period
  }
}
665963
private function getResumenPeriodo()
    {
        $resumen = [];
        foreach ($this->detalles as &$d) {
            // si el tipo de boleta no está en el resumen se crea
            if (!isset($resumen[$d['TpoDoc']])) {
                $resumen[$d['TpoDoc']] = [
                    'TpoDoc' => $d['TpoDoc'],
                    'TotAnulado' => false,
                    'TotalesServicio' => [],
                ];
            }
            // si no existe el tipo de servicio se agrega
            if (!isset($resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']])) {
                $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']] = [
                    'TpoServ' => $d['TpoServ'],
                    'PeriodoDevengado' => false,
                    'TotDoc' => false,
                    'TotMntExe' => false,
                    'TotMntNeto' => 0,
                    'TasaIVA' => 0,
                    'TotMntIVA' => 0,
                    'TotMntTotal' => false,
                    'TotMntNoFact' => false,
                    'TotMntPeriodo' => false,
                    'TotSaldoAnt' => false,
                    'TotVlrPagar' => false,
                    'TotTicket' => false,
                ];
            }
            // agregar detalle al resumen
            if (empty($d['Anulado'])) {
                // contabilizar documento
                $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotDoc'] += 1;
                // ir sumando valores
                $vals = ['MntExe'=>'TotMntExe', 'MntTotal'=>'TotMntTotal', 'MntNoFact'=>'TotMntNoFact', 'MntPeriodo'=>'TotMntPeriodo', 'SaldoAnt'=>'TotSaldoAnt', 'VlrPagar'=>'TotVlrPagar', 'TotTicketBoleta'=>'TotTicket'];
                foreach ($vals as $ori => $des) {
                    if ($d[$ori]) {
                        $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']][$des] += $d[$ori];
                    }
                }
                // determinar neto e iva
                $tasa = \sasco\LibreDTE\Sii::getIVA();
                $neto = round(($d['MntTotal'] - $d['MntExe']) / (1 + $tasa/100));
                if ($neto) {
                    $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'] += $neto;
                    $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TasaIVA'] = $tasa;
                    // WARNING: problema por aproximaciones al calcular el NETO e IVA a partir del BRUTO
                    //$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntIVA'] = round($resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'] * ($tasa/100));
                    $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntIVA'] = $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntTotal'] - $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntExe'] - $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'];
                }
            }
            // documento anulado
            else if ($d['Anulado']=='A') {
                $resumen[$d['TpoDoc']]['TotAnulado'] += 1;
            }
        }
        // armar resumen verdadero
        $ResumenPeriodo = ['TotalesPeriodo'=>[]];
        foreach ($resumen as $r) {
            $ResumenPeriodo['TotalesPeriodo'][] = $r;
        }
        // entregar resumen
        return $ResumenPeriodo;
    }
588566
public function monthlyPerfomance($period = 2)
    {
        $categories = Category::all();
        foreach ($categories as $cat) {
            $records['categories'][] = $cat->name;
        }

        for ($m = $period; $m >= 0; $m--) {
            $from = Carbon::now();
            $from->day = 1;
            $from->subMonth($m);
            $to = Carbon::now();
            $to->day = 1;
            $to->subMonth($m);
            $to->endOfMonth();
            $records['interval'][$from->format('F Y')] = [];
            foreach ($categories as $cat) {
                $records['interval'][$from->format('F Y')][] = round($this->intervalPerformance($from, $to, $cat->id), 1);
            }
        }

        return $records;
    }
310354
public function getTotalTimestampInterval(): float
    {
        $retval = 0;
        foreach ($this->intervals as $interval) {
            $retval += $interval->getTimestampInterval();
        }

        return $retval;
    }
23325
public static function getDatesForPeriod($period)
    {
        /*
         * Type of period is incorrect?
         * Nothing to do
         */
        if (!(new DatePeriod())->isCorrectType($period)) {
            return null;
        }

        $dateStart = null;
        $dateEnd = null;

        switch ($period) {
            case DatePeriod::LAST_WEEK:
                $thisWeekStart = new DateTime('this week');

                $dateStart = clone $thisWeekStart;
                $dateEnd = clone $thisWeekStart;

                $dateStart->sub(new DateInterval('P7D'));
                $dateEnd->sub(new DateInterval('P1D'));

                break;
            case DatePeriod::THIS_WEEK:
                $dateStart = new DateTime('this week');

                $dateEnd = clone $dateStart;
                $dateEnd->add(new DateInterval('P6D'));

                break;
            case DatePeriod::NEXT_WEEK:
                $dateStart = new DateTime('this week');
                $dateStart->add(new DateInterval('P7D'));

                $dateEnd = clone $dateStart;
                $dateEnd->add(new DateInterval('P6D'));

                break;
            case DatePeriod::LAST_MONTH:
                $dateStart = new DateTime('first day of last month');
                $dateEnd = new DateTime('last day of last month');

                break;
            case DatePeriod::THIS_MONTH:
                $lastMonth = self::getDatesForPeriod(DatePeriod::LAST_MONTH);
                $nextMonth = self::getDatesForPeriod(DatePeriod::NEXT_MONTH);

                if (null !== $lastMonth) {
                    $dateStart = $lastMonth->getEndDate();
                    $dateStart->add(new DateInterval('P1D'));
                }

                if (null !== $nextMonth) {
                    $dateEnd = $nextMonth->getStartDate();
                    $dateEnd->sub(new DateInterval('P1D'));
                }

                break;
            case DatePeriod::NEXT_MONTH:
                $dateStart = new DateTime('first day of next month');
                $dateEnd = new DateTime('last day of next month');

                break;
            case DatePeriod::LAST_YEAR:
            case DatePeriod::THIS_YEAR:
            case DatePeriod::NEXT_YEAR:
                $dateStart = new DateTime();
                $dateEnd = new DateTime();

                $yearPeriod = [
                    DatePeriod::LAST_YEAR,
                    DatePeriod::NEXT_YEAR,
                ];

                if (in_array($period, $yearPeriod, true)) {
                    $yearDifference = 1;

                    if (DatePeriod::LAST_YEAR === $period) {
                        $yearDifference *= -1;
                    }

                    $modifyString = sprintf('%s year', $yearDifference);
                    $dateStart->modify($modifyString);
                    $dateEnd->modify($modifyString);
                }

                $year = $dateStart->format('Y');
                $dateStart->setDate($year, 1, 1);
                $dateEnd->setDate($year, 12, 31);

                break;
        }

        /*
         * Start or end date is unknown?
         * Nothing to do
         */
        if (null === $dateStart || null === $dateEnd) {
            return null;
        }

        $dateStart->setTime(0, 0);
        $dateEnd->setTime(23, 59, 59);

        return new DatePeriod($dateStart, $dateEnd);
    }
1183624
public function getTimePeriodInSeconds($timePeriod)
    {
        $timePeriod = StringUtil::deserialize($timePeriod, true);

        if (!isset($timePeriod['unit']) || !isset($timePeriod['value'])) {
            return null;
        }

        $factor = 1;

        switch ($timePeriod['unit']) {
            case 'm':
                $factor = 60;

                break;

            case 'h':
                $factor = 60 * 60;

                break;

            case 'd':
                $factor = 24 * 60 * 60;

                break;
        }

        return $timePeriod['value'] * $factor;
    }
982237
public long getResetMillis(RateBucketPeriod period) {
        long now = System.currentTimeMillis();
        long periodBoundary = getPeriodBoundary(now, period);
        return periodBoundary - now;
    }
876881
public static function variance(array $real, int $timePeriod = null, float $nbDev = null): array
    {
        return static::var($real, $timePeriod, $nbDev);
    }
957744
public function getPeriod($period, $mode = self::DAYS_ONLY)
    {
        $result = $this->parsePeriod($period);

        if ($result['max'] && $mode == self::DAYS_AND_TIME) {
            $result['max']->modify("+1 day -1 second");
        }

        foreach ($result as $key => $value) {
            if (!$value) {
                unset($result[$key]);
            } elseif ($mode == self::DAYS_ONLY) {
                $result[$key] = new DateTime($result[$key]->format('Y-m-d'), $this->getTimezoneTo());
            } elseif ($this->getTimezoneTo()) {
                $result[$key]->setTimezone($this->getTimezoneTo());
            }
        }

        return $result;
    }
251113
protected function incrementForPeriod($key, $value, \DatePeriod $period)
    {
        $ranges = $this->getRanges($period);

        if (count($ranges) > 0) {
            foreach ($ranges as $range) {
                $range instanceof DateRange
                    ? $this->repository->incrementForRange($key, $range->getStartDate(), $range->getEndDate(), $value)
                    : $this->repository->incrementFor($key, $range, $value);
            }
        }
    }
499773
public function getDuration()
    {
        $periods = $this->periods;
        $stopped = \count($periods);
        $left = \count($this->started) - $stopped;

        for ($i = 0; $i < $left; ++$i) {
            $index = $stopped + $i;
            $periods[] = new StopwatchPeriod($this->started[$index], $this->getNow(), $this->morePrecision);
        }

        $total = 0;
        foreach ($periods as $period) {
            $total += $period->getDuration();
        }

        return $total;
    }
1254624
public function getDay(): Period
    {
        $datepoint = $this->setTime(0, 0);

        return new Period($datepoint, $datepoint->add(new DateInterval('P1D')));
    }