/** * @param mixed $value * @param int $depth * * @return string */ public static function stringify($value, $depth = 1) { if ($depth >= self::$maxDepthStringify) { return self::$maxReplacementStringify; } if (is_array($value)) { return static::stringifyArray($value, $depth); } if (is_object($value)) { return static::stringifyObject($value, $depth); } if (is_resource($value)) { return sprintf('`[resource] (%s)`', get_resource_type($value)); } if (is_float($value)) { if (is_infinite($value)) { return ($value > 0 ? '' : '-') . 'INF'; } if (is_nan($value)) { return 'NaN'; } } $options = 0; if (version_compare(PHP_VERSION, '5.4.0', '>=')) { $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; } return @json_encode($value, $options) ?: $value; }
public function testINF() { $this->assertTrue(is_infinite(GreatestCommonDivisor::greatestCommonDivisor([10, INF]))); $this->assertTrue(is_infinite(GreatestCommonDivisor::greatestCommonDivisor([INF, INF]))); $this->assertTrue(is_infinite(GreatestCommonDivisor::greatestCommonDivisor([INF, 10]))); $this->assertTrue(is_infinite(GreatestCommonDivisor::greatestCommonDivisor([10, INF, 10]))); }
/** * Dumps a given PHP variable to a YAML string. * * @param mixed $value The PHP variable to convert * * @return string The YAML string representing the PHP array * * @throws DumpException When trying to dump PHP resource */ public static function dump($value) { switch (true) { case is_resource($value): throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value))); case is_object($value): return '!!php/object:' . serialize($value); case is_array($value): return self::dumpArray($value); case null === $value: return 'null'; case true === $value: return 'true'; case false === $value: return 'false'; case ctype_digit($value): return is_string($value) ? "'{$value}'" : (int) $value; case is_numeric($value): return is_string($value) ? "'{$value}'" : (is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : $value); case Escaper::requiresDoubleQuoting($value): return Escaper::escapeWithDoubleQuotes($value); case Escaper::requiresSingleQuoting($value): return Escaper::escapeWithSingleQuotes($value); case '' == $value: return "''"; case preg_match(self::getTimestampRegex(), $value): case in_array(strtolower($value), array('null', '~', 'true', 'false')): return "'{$value}'"; default: return $value; } }
/** * @covers Fisharebest\PhpPolyfill\Php::inf * @covers Fisharebest\PhpPolyfill\Php::isLittleEndian * @runInSeparateProcess */ public function testInf() { $this->assertTrue(is_float(Php::inf())); $this->assertTrue(is_double(Php::inf())); $this->assertTrue(is_infinite(Php::inf())); $this->assertFalse(is_finite(Php::inf())); }
/** * Parse a string of the form "number unit" where unit is optional. The * results are stored in the $number and $unit parameters. Returns an * error code. * @param $value string to parse * @param $number call-by-ref parameter that will be set to the numerical value * @param $unit call-by-ref parameter that will be set to the "unit" string (after the number) * @return integer 0 (no errors), 1 (no number found at all), 2 (number * too large for this platform) */ protected static function parseNumberValue($value, &$number, &$unit) { // Parse to find $number and (possibly) $unit $decseparator = NumberFormatter::getInstance()->getDecimalSeparatorForContentLanguage(); $kiloseparator = NumberFormatter::getInstance()->getThousandsSeparatorForContentLanguage(); $parts = preg_split('/([-+]?\\s*\\d+(?:\\' . $kiloseparator . '\\d\\d\\d)*' . '(?:\\' . $decseparator . '\\d+)?\\s*(?:[eE][-+]?\\d+)?)/u', trim(str_replace(array(' ', ' ', ' ', ' '), '', $value)), 2, PREG_SPLIT_DELIM_CAPTURE); if (count($parts) >= 2) { $numstring = str_replace($kiloseparator, '', preg_replace('/\\s*/u', '', $parts[1])); // simplify if ($decseparator != '.') { $numstring = str_replace($decseparator, '.', $numstring); } list($number) = sscanf($numstring, "%f"); if (count($parts) >= 3) { $unit = self::normalizeUnit($parts[2]); } } if (count($parts) == 1 || $numstring === '') { // no number found return 1; } elseif (is_infinite($number)) { // number is too large for this platform return 2; } else { return 0; } }
/** * @param float $maintainabilityIndexWithoutComment */ public function setMaintainabilityIndexWithoutComment($maintainabilityIndexWithoutComment) { if (is_infinite($maintainabilityIndexWithoutComment)) { $maintainabilityIndexWithoutComment = 171; } $this->maintainabilityIndexWithoutComment = round($maintainabilityIndexWithoutComment, 2); }
public function getHuman($max_groups = INF, $short = false) { $short = (bool) $short; if ($max_groups < 1) { $max_groups = INF; } $for_print = []; if ($this->_years > 0) { $for_print[] = sprintf("%d %s", $this->_years, MeasureWord::getFormByForms($this->_forms[$short][0], intval($this->_years))); // years } if ($this->_months > 0) { $for_print[] = sprintf("%d %s", $this->_months, MeasureWord::getFormByForms($this->_forms[$short][1], intval($this->_months))); // months } if ($this->_days > 0) { $for_print[] = sprintf("%d %s", $this->_days, MeasureWord::getFormByForms($this->_forms[$short][2], intval($this->_days))); // days } if ($this->_hours > 0) { $for_print[] = sprintf("%d %s", $this->_hours, MeasureWord::getFormByForms($this->_forms[$short][3], intval($this->_hours))); // hours } if ($this->_minutes > 0) { $for_print[] = sprintf("%d %s", $this->_minutes, MeasureWord::getFormByForms($this->_forms[$short][4], intval($this->_minutes))); // minutes } if ($this->_seconds > 0 || empty($for_print)) { $for_print[] = sprintf("%d %s", $this->_seconds, MeasureWord::getFormByForms($this->_forms[$short][5], intval($this->_seconds))); // seconds } return trim(preg_replace('/ {2,}/', ' ', join(' ', is_infinite($max_groups) ? $for_print : array_slice($for_print, 0, $max_groups)))); }
/** * Process the Truncate operator. * * @return integer|null The truncated value or NULL if the sub-expression is NaN or if the sub-expression is NULL. * @throws OperatorProcessingException */ public function process() { $operands = $this->getOperands(); if ($operands->containsNull() === true) { return null; } if ($operands->exclusivelySingle() === false) { $msg = "The Truncate operator only accepts operands with a single cardinality."; throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_CARDINALITY); } if ($operands->exclusivelyNumeric() === false) { $msg = "The Truncate operator only accepts operands with an integer or float baseType."; throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_BASETYPE); } $operand = $operands[0]; if (is_nan($operand->getValue())) { return null; } else { if (is_infinite($operand->getValue())) { return new Float(INF); } else { return new Integer(intval($operand->getValue())); } } }
public function logQuery(array $query) { dump($query); exit; if ($this->logger === NULL) { return; } if (isset($query['batchInsert']) && NULL !== $this->batchInsertTreshold && $this->batchInsertTreshold <= $query['num']) { $query['data'] = '**' . $query['num'] . ' item(s)**'; } array_walk_recursive($query, function (&$value, $key) { if ($value instanceof \MongoBinData) { $value = base64_encode($value->bin); return; } if (is_float($value) && is_infinite($value)) { $value = ($value < 0 ? '-' : '') . 'Infinity'; return; } if (is_float($value) && is_nan($value)) { $value = 'NaN'; return; } }); $this->logger->debug($this->prefix . json_encode($query)); }
/** * Returns the result of filtering $value * * @param mixed $value * @return mixed */ public function filter($value) { $unfilteredValue = $value; if (is_float($value) && !is_nan($value) && !is_infinite($value)) { ErrorHandler::start(); $formatter = $this->getFormatter(); $currencyCode = $this->setupCurrencyCode(); $result = $formatter->formatCurrency($value, $currencyCode); ErrorHandler::stop(); // FIXME: verify that this, given the initial IF condition, never happens // if ($result === false) { // return $unfilteredValue; // } // Retrieve the precision internally used by the formatter (i.e., depends from locale and currency code) $precision = $formatter->getAttribute(\NumberFormatter::FRACTION_DIGITS); // $result is considered valid if the currency's fraction digits can accomodate the $value decimal precision // i.e. EUR (fraction digits = 2) must NOT allow double(1.23432423432) $isFloatScalePrecise = $this->isFloatScalePrecise($value, $precision, $this->formatter->getAttribute(\NumberFormatter::ROUNDING_MODE)); if ($this->getScaleCorrectness() && !$isFloatScalePrecise) { return $unfilteredValue; } return $result; } return $unfilteredValue; }
/** * Dumps PHP array to YAML. * * @param mixed $value PHP * * @return string YAML */ public static function dump($value) { switch (true) { case is_resource($value): throw new InvalidArgumentException('Unable to dump PHP resources in a YAML file.'); case is_object($value): return '!!php/object:' . serialize($value); case is_array($value): return self::dumpArray($value); case is_null($value): return 'null'; case true === $value: return 'true'; case false === $value: return 'false'; case ctype_digit($value): return is_string($value) ? "'{$value}'" : (int) $value; case is_numeric($value): return is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'{$value}'" : $value); case false !== strpos($value, "\n"): return sprintf('"%s"', str_replace(array('"', "\n", "\r"), array('\\"', '\\n', '\\r'), $value)); case preg_match('/[ \\s \' " \\: \\{ \\} \\[ \\] , & \\* \\#]/x', $value): return sprintf("'%s'", str_replace('\'', '\'\'', $value)); case '' == $value: return "''"; case preg_match(self::getTimestampRegex(), $value): return "'{$value}'"; case in_array(strtolower($value), array('true', 'on', '+', 'yes', 'y')): return "'{$value}'"; case in_array(strtolower($value), array('false', 'off', '-', 'no', 'n')): return "'{$value}'"; default: return $value; } }
/** * @param float|int|string $value * * @return Decimal */ public static function fromNative($value) { if (\is_infinite((double) $value)) { return DecimalInfinite::fromNative($value); } return new self($value); }
/** * * * @param Edges $edges * @param int[] $totalCostOfCheapestPathTo * @param Vertex[] $predecessorVertexOfCheapestPathTo * * @return Vertex|NULL */ private function bigStep(Edges $edges, array &$totalCostOfCheapestPathTo, array &$predecessorVertexOfCheapestPathTo) { $changed = NULL; // check for all edges foreach ($edges as $edge) { // check for all "ends" of this edge (or for all targetes) foreach ($edge->getVerticesTarget() as $toVertex) { $fromVertex = $edge->getVertexFromTo($toVertex); // If the fromVertex already has a path if (isset($totalCostOfCheapestPathTo[$fromVertex->getId()])) { // New possible costs of this path $newCost = $totalCostOfCheapestPathTo[$fromVertex->getId()] + $edge->getWeight(); if (is_infinite($newCost)) { $newCost = $edge->getWeight() + 0; } // No path has been found yet if (!isset($totalCostOfCheapestPathTo[$toVertex->getId()]) || $totalCostOfCheapestPathTo[$toVertex->getId()] > $newCost) { $changed = $toVertex; $totalCostOfCheapestPathTo[$toVertex->getId()] = $newCost; $predecessorVertexOfCheapestPathTo[$toVertex->getId()] = $fromVertex; } } } } return $changed; }
/** * @param string|float|int * @throws InvalidArgumentException * @return float|int */ public static function parseNumber($s) { if (!is_numeric($s) || is_infinite($s)) { throw new InvalidArgumentException('Provided value cannot be converted to number'); } return $s * 1; }
/** * @Then /^I see a result of "Infinity"$/ */ public function iSeeAResultOfInfinity() { $result = $this->calculator->readScreen(); if (!is_infinite($result)) { throw new Exception("Wrong result, expected infinite, actual is [{$result}]"); } }
/** * Return the ulp for the given float argument. The ulp is the * difference between the argument and the next larger float. Note * that the sign of the float argument is ignored, that is, * ulp(x) == ulp(-x). If the argument is a NaN, then NaN is returned. * If the argument is an infinity, then +Inf is returned. If the * argument is zero (either positive or negative), then * {@link Float#MIN_VALUE} is returned. * * @param float $f * * @return float */ public static function ulp($f) { if (is_nan($f)) { return $f; } if (is_infinite($f)) { return INF; } // This handles both +0.0 and -0.0. if ($f == 0.0) { return self::implode(0, 0, 1); //returns closest value to 0 possible without being 0 } $bits = self::explode($f); $bits[0] = 0; $mantissa = $bits[2]; $exponent = $bits[1]; // Denormal number, so the answer is easy. if ($bits[1] == 0) { $bits[2] = 1; //set fraction to smallest possible value return self::implode($bits); } // Conceptually we want to have '1' as the mantissa. Then we would // shift the mantissa over to make a normal number. If this underflows // the exponent, we will make a denormal result. $bits[1] -= 23; $bits[2] = 0; if ($bits[1] == 0) { $bits[2] = 1 << -($bits[1] - 1); $bits[1] = 0; } return self::implode($bits); }
function var_info($value) { if ($value === NULL) { return 'null'; } if (is_array($value)) { if (is_callable($value)) { return 'callable array'; } return 'array'; } if (is_bool($value)) { return $value ? 'true' : 'false'; } if (is_float($value)) { if (is_infinite($value)) { return 'infinite float'; } if (is_nan($value)) { return 'invalid float'; } if ($value > 0.0) { return 'positive float'; } if ($value < 0.0) { return 'negative float'; } return 'zero float'; } if (is_int($value)) { if ($value > 0) { return 'positive int'; } if ($value < 0) { return 'negative int'; } return 'zero int'; } if (is_object($value)) { return get_class($value); } if (is_string($value)) { if (is_numeric($value)) { return 'numeric string'; } if (is_callable($value)) { return 'callable string'; } return 'string'; } $resource_type = @get_resource_type($value); if (is_resource($value)) { return $resource_type . ' resource'; } if (strtolower($resource_type) == 'unknown') { return 'invalid resource'; } return 'unknown'; }
/** * @param string $value */ protected function __construct($value) { if (\is_infinite($value)) { $this->value = $value; } else { throw new \InvalidArgumentException(sprintf('Argument "%s" is invalid. Allowed types for argument are "INF" or "-INF".', $value)); } }
public function testInfinite() { $expression = $this->createFakeExpression(); $operands = new OperandsCollection(array(new Float(INF), new Float(INF))); $processor = new PowerProcessor($expression, $operands); $result = $processor->process(); $this->assertTrue(is_infinite($result->getValue())); }
/** * @param mixed $data * @return int|bool|string|null|array */ protected function normalize($data, int $depth = 0) { if ($depth > 9) { return 'Over 9 levels deep, aborting normalization'; } if (null === $data || is_scalar($data)) { if (is_float($data)) { if (is_infinite($data)) { return ($data > 0 ? '' : '-') . 'INF'; } if (is_nan($data)) { return 'NaN'; } } return $data; } if (is_array($data) || $data instanceof \Traversable) { $normalized = []; $count = 1; if ($data instanceof \Generator && !$data->valid()) { return array('...' => 'Generator is already consumed, aborting'); } foreach ($data as $key => $value) { if ($count++ >= 1000) { $normalized['...'] = 'Over 1000 items (' . ($data instanceof \Generator ? 'generator function' : count($data) . ' total') . '), aborting normalization'; break; } $normalized[$key] = $this->normalize($value, $depth + 1); } return $normalized; } if ($data instanceof \DateTimeInterface) { return $this->formatDate($data); } if (is_object($data)) { if ($data instanceof Throwable) { return $this->normalizeException($data, $depth); } if ($data instanceof \JsonSerializable) { $value = $data->jsonSerialize(); } elseif (method_exists($data, '__toString')) { $value = $data->__toString(); } else { // the rest is normalized by json encoding and decoding it $encoded = $this->toJson($data, true); if ($encoded === false) { $value = 'JSON_ERROR'; } else { $value = json_decode($encoded, true); } } return [get_class($data) => $value]; } if (is_resource($data)) { return sprintf('[resource(%s)]', get_resource_type($data)); } return '[unknown(' . gettype($data) . ')]'; }
function sizeFormat($bytes) { $s = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB']; $e = floor(log($bytes, 1024)); if (is_infinite($e)) { return '0.00Bytes'; } return number_format($bytes / pow(1024, $e), 2) . $s[$e]; }
protected function matches($actual) { $asserter = new asserters\boolean(); try { $asserter->setWith(is_infinite($actual))->isTrue(); } catch (exception $exception) { throw new exception($asserter, $this->analyzer->getTypeOf($actual) . ' is not infinite'); } }
/** * Asserts that two values are equal. * * @param mixed $expected The first value to compare * @param mixed $actual The second value to compare * @param float $delta The allowed numerical distance between two values to * consider them equal * @param bool $canonicalize If set to TRUE, arrays are sorted before * comparison * @param bool $ignoreCase If set to TRUE, upper- and lowercasing is * ignored when comparing string values * * @throws ComparisonFailure Thrown when the comparison * fails. Contains information about the * specific errors that lead to the failure. */ public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = FALSE, $ignoreCase = FALSE) { if (is_infinite($actual) && is_infinite($expected)) { return; } if ((is_infinite($actual) xor is_infinite($expected)) || (is_nan($actual) or is_nan($expected)) || abs($actual - $expected) > $delta) { throw new ComparisonFailure($expected, $actual, '', '', FALSE, sprintf('Failed asserting that %s matches expected %s.', $this->exporter->export($actual), $this->exporter->export($expected))); } }
public static function dump($value, $exceptionOnInvalidType = false, $objectSupport = false) { switch (true) { case is_resource($value): if ($exceptionOnInvalidType) { throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value))); } return 'null'; case is_object($value): if ($objectSupport) { return '!php/object:' . serialize($value); } if ($exceptionOnInvalidType) { throw new DumpException('Object support when dumping a YAML file has been disabled.'); } return 'null'; case is_array($value): return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport); case null === $value: return 'null'; case true === $value: return 'true'; case false === $value: return 'false'; case ctype_digit($value): return is_string($value) ? "'{$value}'" : (int) $value; case is_numeric($value): $locale = setlocale(LC_NUMERIC, 0); if (false !== $locale) { setlocale(LC_NUMERIC, 'C'); } if (is_float($value)) { $repr = (string) $value; if (is_infinite($value)) { $repr = str_ireplace('INF', '.Inf', $repr); } elseif (floor($value) == $value && $repr == $value) { $repr = '!!float ' . $repr; } } else { $repr = is_string($value) ? "'{$value}'" : (string) $value; } if (false !== $locale) { setlocale(LC_NUMERIC, $locale); } return $repr; case '' == $value: return "''"; case Escaper::requiresDoubleQuoting($value): return Escaper::escapeWithDoubleQuotes($value); case Escaper::requiresSingleQuoting($value): case preg_match(self::getHexRegex(), $value): case preg_match(self::getTimestampRegex(), $value): return Escaper::escapeWithSingleQuotes($value); default: return $value; } }
public static function describe($var) { if (is_object($var) || $var instanceof \__PHP_Incomplete_Class) { return 'object of class ' . get_class($var); } elseif (is_resource($var)) { return 'resource of type ' . get_resource_type($var); } elseif (is_array($var)) { if (empty($var)) { return 'empty array'; } if (is_callable($var)) { return 'callable array'; } if (array_filter($var, 'is_int', ARRAY_FILTER_USE_KEY)) { return 'indexed array'; } return 'associative array'; } elseif (is_int($var)) { if ($var < 0) { return 'negative integer'; } if ($var > 0) { return 'positive integer'; } return 'zero integer'; } elseif (is_float($var)) { if (is_infinite($var)) { return 'infinite float'; } if (is_nan($var)) { return 'invalid float'; } if ($var < 0) { return 'negative float'; } if ($var > 0) { return 'positive float'; } return 'zero float'; } elseif (is_string($var)) { if (empty($var)) { return 'empty string'; } if (is_callable($var)) { return 'callable string'; } if (is_numeric($var)) { return 'numeric string'; } return 'string'; } elseif (is_bool($var)) { return true === $var ? 'boolean true' : 'boolean false'; } else { return 'unknown type'; } }
/** * Are two numbers equal within given delta. * * @param int|float $a * @param int|float $b * @param int|float $delta * * @return bool */ public static function equalWithin($a, $b, $delta) { if (is_infinite($a) xor is_infinite($b)) { return false; } if (is_nan($a) || is_nan($b) || is_nan($delta)) { return false; } return abs($a - $b) <= $delta; }
} public function writeInteger($integer) { if ($integer >= 0 && $integer <= 9) { $this->stream->write((string) $integer); } else { $this->stream->write(HproseTags::TagInteger . $integer . HproseTags::TagSemicolon); } } public function writeLong($long)
/** * Create random number with Box-Muller-Method * * @return float */ public static function number() { $u1 = mt_rand() / mt_getrandmax(); $u2 = mt_rand() / mt_getrandmax(); $z = sqrt(-2 * log($u1)); $z = $z * cos(2 * pi() * $u2); if (is_infinite($z)) { return static::number(); } return $z; }
/** * Перегрузка функции min для исключения бесконечностей * @param array $arr * @return mixed */ function min($arr) { foreach ($arr as $key => $value) { if (is_infinite($value)) { unset($arr[$key]); } else { break; } } return $arr ? \min($arr) : 0; }
/** * Multiply two values. * * @param $val1 * @param $val2 * @return float * @throws InvalidArgumentException */ public function multiply($val1, $val2) { $this->checkCurrentVal($val1, $val2); $val1 = $this->clear($val1); $val2 = $this->clear($val2); $result = $val1 * $val2; if (is_infinite($result)) { throw new InvalidArgumentException('Infinite amount.'); } return $result; }