Skip to content

Instantly share code, notes, and snippets.

View bcremer's full-sized avatar

Benjamin Cremer bcremer

View GitHub Profile
@bcremer
bcremer / Sieve_of_Eratosthenes.php
Created August 27, 2020 07:08
Generate prime numbers using the Sieve of Eratosthenes, Lazily evaluted with PHP
<?php
// Generate prime numbers using the Sieve of Eratosthenes
// Lazily evaluted
// Inspired by: https://www.youtube.com/watch?v=5jwV3zxXc8E
$primes = sieve(nat(2));
foreach ($primes as $value) {
echo $value . PHP_EOL;
<?php
declare(strict_types=1);
/**
* @psalm-template TKey
* @psalm-template TValue
* @psalm-param iterable<TKey, TValue> $list
* @psalm-param callable(TValue): bool $filter
* @psalm-return Generator<TKey, TValue>
*/
@bcremer
bcremer / measure_cpu_time.php
Last active May 8, 2020 06:40
Measure CPU Time / User / System Time in PHP Scripts
<?php
$measure = function (callable $lambda) {
$rUsage = getrusage();
$startUTime = $rUsage['ru_utime.tv_usec'] + $rUsage['ru_utime.tv_sec'] * 1000000;
$startSTime = $rUsage['ru_stime.tv_usec'] + $rUsage['ru_stime.tv_sec'] * 1000000;
$startHrTime = hrtime(true);
$lambda();
@bcremer
bcremer / 0_output.log
Last active April 20, 2020 14:56
Measure array unpack vs. array_merge
Array Unpack
user: 4.355 ms
system: 0 ms
wait: 25 ms
total: 4.381 ms
Array Merge
user: 6.798 ms
system: 0 ms
wait: 7 ms
<?php
declare(strict_types=1);
namespace AppTest;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use function assert;
use function strpos;
@bcremer
bcremer / mysql-alternative-insert-syntax.sql
Last active February 4, 2019 07:33
MySQL alternative insert syntax
-- Traditional insert
INSERT INTO `campaigns` (name, active) VALUES ('foobar', 1⁾;
-- Alternative insert
INSERT INTO `campaigns` SET name = 'foobar', active = 1;
@bcremer
bcremer / IEEE754.php
Last active January 29, 2019 14:59
Why IEEE 754 floating point numbers are a mess to debug
<?php
// Live Demo: https://3v4l.org/GWJFZ
// see also: http://0.30000000000000004.com/
var_dump(0.1 + 0.2); // float(0.3)
var_dump(0.3); // float(0.3)
var_dump(0.1 + 0.2 == 0.3); // bool(false)
// Set the number of significant digits displayed in floating point numbers.
ini_set('precision', 18);
<?php
// $clock implements Clock
// interface Clock
// {
// public function now() : DateTimeImmutable;
// }
// setup
$startDate = Date::fromString('2019-01-04');
set-option -g prefix C-a
unbind-key C-b
bind-key C-a last-window
# 0 start numbering at 1
set-option -g base-index 1
# Automatically set window title
setw -g automatic-rename
@bcremer
bcremer / fizzbuzz.php
Last active October 17, 2018 22:02
FizzBuzz without Conditionals in PHP
<?php
$fizzers = [1, 0, 0, 0];
$buzzers = [2, 0, 0, 0, 0];
$words = ['', 'Fizz', 'Buzz', 'FizzBuzz'];
foreach (range(1, 100) as $i) {
$words[0] = $i;
echo $words[$fizzers[$i % 3] + $buzzers[$i % 5]].PHP_EOL;
}