Useless but Precise

Sito in una pagina che offre tutti i tipi di counter, con codice in JavaScript, Python e Swift. Esempi basati su cose reali e precisissime, ma totalmente inutili.

Panoramica (live e superflua)

Millisecondi dal 2000 (UTC)
Giorni dall'ultimo 29 febbraio911
Venerdì 13esimi dal 200046
Paradosso del compleanno
Uptime pagina (ms)
Km orbita terrestre
Pixel scrollati
Countdown orario palindromo
“Non premere” (click)0
Respiri stimati
Gradi rotazione terrestre
Età della Luna (giorni)
Km del Sole nella Via Lattea
Pixel della viewport

Counter #1 — Millisecondi dal primo gennaio duemila (UTC)

Contatore live dei millisecondi dal 2000. Serve? No. È preciso? Sì.

/* Millisecondi dal 2000-01-01T00:00:00Z */
const y2k = Date.UTC(2000, 0, 1, 0, 0, 0, 0);
setInterval(() => console.log(Date.now() - y2k), 100);
# Millisecondi dal 2000-01-01T00:00:00Z
import time, datetime
y2k = datetime.datetime(2000,1,1,tzinfo=datetime.timezone.utc)
while True:
    now = datetime.datetime.now(datetime.timezone.utc)
    print(int((now - y2k).total_seconds() * 1000))
    time.sleep(0.1)
/// Millisecondi dal 2000-01-01T00:00:00Z
import Foundation
let y2k = ISO8601DateFormatter().date(from: "2000-01-01T00:00:00Z")!
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
  print(Int(Date().timeIntervalSince(y2k) * 1000))
}
RunLoop.main.run()

Counter #2 — Giorni dall'ultimo 29 febbraio

Esattamente quanti giorni sono passati dall’ultimo giorno bisestile.

911
/* Giorni dall'ultimo 29 febbraio (calcolato oggi) */
function isLeap(y){ return (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0); }
function lastLeapDay(d=new Date()){
  let y = d.getUTCFullYear();
  const feb29 = new Date(Date.UTC(y,1,29));
  if(isLeap(y) && d >= feb29) return feb29;
  y--; while(!isLeap(y)) y--; return new Date(Date.UTC(y,1,29));
}
const today = new Date();
console.log(Math.floor((today - lastLeapDay(today)) / 86400000));
# Giorni dall'ultimo 29 febbraio (calcolato oggi)
from datetime import date
def is_leap(y): return (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
def last_leap_day(today: date) -> date:
    y = today.year
    if is_leap(y) and date(y,2,29) <= today: return date(y,2,29)
    y -= 1
    while not is_leap(y): y -= 1
    return date(y,2,29)
print((date.today() - last_leap_day(date.today())).days)
/// Giorni dall'ultimo 29 febbraio
import Foundation
func isLeap(_ y:Int)->Bool{ (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) }
func lastLeapDay(today: Date = Date()) -> Date {
  let cal = Calendar(identifier: .gregorian)
  let y = cal.component(.year, from: today)
  func dateFrom(_ year:Int)->Date {
    var c = DateComponents(); c.year = year; c.month = 2; c.day = 29
    return cal.date(from: c)!
  }
  if isLeap(y) { let feb = dateFrom(y); if today >= feb { return feb } }
  var yy = y - 1; while !isLeap(yy) { yy -= 1 }; return dateFrom(yy)
}
let cal = Calendar(identifier: .gregorian)
let days = cal.dateComponents([.day], from: lastLeapDay(), to: Date()).day!
print(days)

Counter #3 — Venerdì 13 dal 2000 (conteggio reale)

Calcolato da 2000-01-01 a oggi.

46 eventi
/* Conta tutti i Friday 13th tra due date incluse */
function countFriday13(start, end){
  const s = new Date(start), e = new Date(end);
  let y = s.getUTCFullYear(), total = 0;
  while (y <= e.getUTCFullYear()){
    const mStart = (y === s.getUTCFullYear()) ? (s.getUTCMonth()+1) : 1;
    const mEnd = (y === e.getUTCFullYear()) ? (e.getUTCMonth()+1) : 12;
    for (let m = mStart; m <= mEnd; m++){
      const d = new Date(Date.UTC(y, m-1, 13));
      if (d >= s && d <= e && d.getUTCDay() === 5) total++;
    }
    y++;
  }
  return total;
}
console.log(countFriday13("2000-01-01T00:00:00Z", new Date().toISOString()));
# Conta tutti i Friday 13th tra due date incluse
from datetime import date
def count_friday13(start: date, end: date) -> int:
    total = 0
    y = start.year
    while y <= end.year:
        m_start = 1 if y > start.year else start.month
        m_end = 12 if y < end.year else end.month
        for m in range(m_start, m_end+1):
            d = date(y, m, 13)
            if d < start or d > end: continue
            if d.weekday() == 4: total += 1
        y += 1
    return total
print(count_friday13(date(2000,1,1), date.today()))
/// Conta tutti i Friday 13th tra due date incluse
import Foundation
let cal = Calendar(identifier: .gregorian)
func countFriday13(start: Date, end: Date) -> Int {
  var total = 0
  var y = cal.component(.year, from: start)
  let eY = cal.component(.year, from: end)
  while y <= eY {
    let mStart = (y == cal.component(.year, from: start)) ? cal.component(.month, from: start) : 1
    let mEnd = (y == eY) ? cal.component(.month, from: end) : 12
    for m in mStart...mEnd {
      var c = DateComponents(); c.year = y; c.month = m; c.day = 13
      let d = cal.date(from: c)!
      if d >= start && d <= end && cal.component(.weekday, from: d) == 6 { total += 1 }
    }
    y += 1
  }
  return total
}
print(countFriday13(start: cal.date(from: DateComponents(year:2000,month:1,day:1))!, end: Date()))

Counter #4 — Paradosso del compleanno

Probabilità che in un gruppo di n persone almeno due condividano il compleanno (365 giorni, indipendente, uniforme).

23
/* Birthday paradox: P(almeno una coppia) */
function birthdayProb(n){ let pNo=1; for(let k=0;k
      
# Birthday paradox
def birthday_prob(n:int)->float:
    p_no=1.0
    for k in range(n):
        p_no *= (365-k)/365
    return 1-p_no
print(round(birthday_prob(23), 4))  # ~0.5073
/// Birthday paradox
func birthdayProb(_ n:Int)->Double{
  var pNo = 1.0
  for k in 0..
    

Counter #5 — Millisecondi da quando hai aperto la pagina

/* Uptime della pagina in millisecondi */
const start = Date.now();
setInterval(()=> console.log(Date.now()-start), 100);
# Uptime (ms) via perf_counter
import time
t0 = time.perf_counter()
while True:
    print(int((time.perf_counter()-t0)*1000))
    time.sleep(0.1)
/// Uptime (ms)
import Foundation
let start = Date()
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
  print(Int(Date().timeIntervalSince(start)*1000))
}
RunLoop.main.run()

Counter #6 — Km percorsi dalla Terra (orbita) da quando sei qui

Velocità media ≈ 29.78 km/s.

/* Distanza orbitale (stima) a 29.78 km/s */
const v = 29.78; // km/s
const t0 = Date.now();
setInterval(()=> console.log(Math.floor(v * (Date.now()-t0)/1000)), 250);
# Distanza orbitale stimata (km)
import time
v = 29.78; t0 = time.time()
while True:
    print(int(v * (time.time()-t0)))
    time.sleep(0.25)
/// Distanza orbitale (km)
import Foundation
let v = 29.78, t0 = Date()
Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { _ in
  print(Int(v * Date().timeIntervalSince(t0)))
}
RunLoop.main.run()

Counter #7 — Scrollometro: pixel totali scrollati

Conta i pixel verticali percorsi. La barra sottostante è granulare come sabbia.

/* Pixel scrollati cumulativi nel browser */
let lastY = window.scrollY, total=0;
window.addEventListener('scroll', ()=>{ const dy = Math.abs(window.scrollY-lastY); total+=dy; lastY=window.scrollY; console.log(total); }, {passive:true});
# Pixel scrollati (Tkinter demo)
import tkinter as tk
total = 0; last = 0
def on_scroll(event):
    global total, last
    dy = event.delta if event.delta else 0
    total += abs(dy); print(total)
root = tk.Tk(); root.geometry("300x400")
c = tk.Canvas(root); c.pack(fill="both", expand=True)
for i in range(100): c.create_text(10, 20*i+10, anchor="w", text=f"Riga {i}")
c.bind_all("", on_scroll)
c.bind_all("", lambda e: on_scroll(type("e",(object,),{"delta":120})()))
c.bind_all("", lambda e: on_scroll(type("e",(object,),{"delta":-120})()))
root.mainloop()
/// Pixel scrollati (UIKit demo)
import UIKit
class VC: UIViewController, UIScrollViewDelegate {
  let scroll = UIScrollView(); var lastY: CGFloat = 0; var total: CGFloat = 0
  override func viewDidLoad() {
    super.viewDidLoad()
    scroll.frame = view.bounds; scroll.delegate = self; view.addSubview(scroll)
    let content = UIView(frame: CGRect(x:0,y:0,width:view.bounds.width,height:3000))
    content.backgroundColor = .systemBackground; scroll.addSubview(content); scroll.contentSize = content.bounds.size
  }
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let dy = abs(scrollView.contentOffset.y - lastY); total += dy; lastY = scrollView.contentOffset.y
    print(Int(total))
  }
}

Counter #8 — Countdown al prossimo orario palindromo

HH:MM:SS che, senza i due punti, leggono uguale avanti e indietro.

/* Prossimo orario palindromo HH:MM:SS */
function isPalTime(d){
  const hh = String(d.getHours()).padStart(2,'0');
  const mm = String(d.getMinutes()).padStart(2,'0');
  const ss = String(d.getSeconds()).padStart(2,'0');
  const s = hh+mm+ss;
  return s === s.split('').reverse().join('');
}
function nextPalTime(from=new Date()){
  let t = new Date(from.getTime());
  for(let i=0;i<=86400;i++){
    if(isPalTime(t)) return t;
    t = new Date(t.getTime()+1000);
  }
  return new Date(from.getTime()+86400000);
}
let target = nextPalTime(new Date(Date.now()+1000));
setInterval(()=>{
  const now = new Date();
  if(now > target) target = nextPalTime(new Date(now.getTime()+1000));
  let diff = Math.max(0, Math.floor((target - now)/1000));
  const h = String(Math.floor(diff/3600)).padStart(2,'0');
  diff %= 3600; const m = String(Math.floor(diff/60)).padStart(2,'0');
  const s = String(diff%60).padStart(2,'0');
  console.log(h+":"+m+":"+s);
}, 250);
# Prossimo orario palindromo HHMMSS
import time, datetime
def is_pal(t: datetime.datetime)->bool:
    s = t.strftime("%H%M%S")
    return s == s[::-1]
def next_pal(start=None):
    t = start or datetime.datetime.now()
    t = t.replace(microsecond=0) + datetime.timedelta(seconds=1)
    for _ in range(86400):
        if is_pal(t): return t
        t += datetime.timedelta(seconds=1)
    return t
target = next_pal()
while True:
    now = datetime.datetime.now()
    if now >= target: target = next_pal(now)
    diff = int((target-now).total_seconds())
    h, r = divmod(diff, 3600); m, s = divmod(r, 60)
    print(f"{h:02}:{m:02}:{s:02}")
    time.sleep(0.25)
/// Prossimo orario palindromo HHMMSS
import Foundation
func isPal(_ d: Date)->Bool{
  let f = DateFormatter(); f.dateFormat = "HHmmss"
  let s = f.string(from: d)
  return s == String(s.reversed())
}
func nextPal(from: Date = Date()) -> Date {
  var t = Date(timeIntervalSince1970: from.timeIntervalSince1970 + 1).rounded()
  for _ in 0..<86400 { if isPal(t) { return t }; t.addTimeInterval(1) }
  return t
}
var target = nextPal()
Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { _ in
  let now = Date()
  if now >= target { target = nextPal(from: now) }
  let diff = Int(target.timeIntervalSince(now))
  let h = diff/3600, m = (diff%3600)/60, s = diff%60
  print(String(format:"%02d:%02d:%02d", h,m,s))
}
RunLoop.main.run()

Counter #9 — Quante volte hai premuto “Non premere”

La curiosità incrementa questo numero. Le cifre sono su card giganti.

/* Click su “Non premere” con persistenza */
let n = parseInt(localStorage.getItem('dontpress')||'0',10);
document.getElementById('dont_btn').onclick = ()=>{ n++; localStorage.setItem('dontpress', n); console.log(n); };
# Bottone "Non premere" (Tkinter)
import tkinter as tk
n = 0
def click():
    global n; n+=1; print(n)
root = tk.Tk()
b = tk.Button(root, text="Non premere", command=click); b.pack()
root.mainloop()
/// Bottone "Non premere" (UIKit)
import UIKit
class VC: UIViewController {
  var n = 0
  override func viewDidLoad() {
    super.viewDidLoad()
    let b = UIButton(type: .system); b.setTitle("Non premere", for: .normal)
    b.addTarget(self, action: #selector(tap), for: .touchUpInside)
    b.frame = CGRect(x:40,y:100,width:200,height:44); view.addSubview(b)
  }
  @objc func tap(){ n+=1; print(n) }
}

Counter #10 — Respiri stimati

RPM 12–20 tipiche. Cambiare RPM non altera i respiri già conteggiati.

14
/* Respiri stimati con integrazione incrementale (RPM modificabile) */
let rpm = 14; let breathCum = 0; let lastTick = Date.now();
setInterval(()=> {
  const now = Date.now(); const dt = now - lastTick;
  breathCum += (rpm/60000) * dt; lastTick = now;
  console.log(Math.floor(breathCum));
}, 200);
# Respiri stimati (integrazione nel tempo)
import time
rpm = 14; cum = 0.0; last = time.time()
while True:
    now = time.time(); dt = now - last
    cum += rpm * dt / 60.0; last = now
    print(int(cum)); time.sleep(0.2)
/// Respiri stimati (integrazione nel tempo)
import Foundation
var rpm = 14.0, cum = 0.0, last = Date()
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { _ in
  let now = Date(); let dt = now.timeIntervalSince(last)
  cum += rpm * dt / 60.0; last = now
  print(Int(cum))
}
RunLoop.main.run()

Counter #11 — Gradi di rotazione terrestre da quando sei qui

Basato sul giorno siderale (~86164 s). Loader che si inclina.

/* Rotazione terrestre (gradi) da t0 — giorno siderale 86164 s */
const t0 = Date.now();
setInterval(()=> console.log(360 * ((Date.now()-t0)/1000) / 86164), 200);
# Rotazione terrestre (gradi)
import time
t0 = time.time()
while True:
    print(360 * (time.time() - t0) / 86164)
    time.sleep(0.2)
/// Rotazione terrestre (gradi)
import Foundation
let t0 = Date()
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { _ in
  print(360.0 * Date().timeIntervalSince(t0) / 86164.0)
}
RunLoop.main.run()

Counter #12 — Fase lunare approssimata

Età della Luna (giorni) e illuminazione stimata. Perfetto per lupi mannari IT.

giorni illuminazione
/* Età Luna (approx). Base: 2000-01-06 18:14 UTC, periodo sinodico 29.530588853 d */
function moonPhase(d=new Date()){
  const syn=29.530588853, base=Date.UTC(2000,0,6,18,14,0);
  const days=(d.getTime()-base)/86400000;
  let age=((days%syn)+syn)%syn;
  const illum=(1-Math.cos(2*Math.PI*age/syn))/2;
  return {age, illum};
}
const {age, illum} = moonPhase(new Date());
console.log(age.toFixed(2), (illum*100).toFixed(1)+"%");
# Età Luna (approx)
import math, time
syn = 29.530588853
base = 946727640  # 2000-01-06 18:14 UTC in epoch sec
def moon_phase(ts=None):
    t = ts or time.time()
    days = (t - base)/86400
    age = (days % syn + syn) % syn
    illum = (1 - math.cos(2*math.pi*age/syn))/2
    return age, illum
age, illum = moon_phase()
print(f"{age:.2f} giorni, {illum*100:.1f}%")
/// Età Luna (approx)
import Foundation
let syn = 29.530588853
let base = DateComponents(calendar: Calendar(identifier: .gregorian), timeZone: TimeZone(secondsFromGMT: 0), year:2000, month:1, day:6, hour:18, minute:14).date!
func moonPhase(_ d: Date = Date()) -> (age: Double, illum: Double) {
  let days = d.timeIntervalSince(base)/86400.0
  var age = days.truncatingRemainder(dividingBy: syn)
  if age < 0 { age += syn }
  let illum = (1 - cos(2*Double.pi*age/syn))/2
  return (age, illum)
}
let p = moonPhase()
print(String(format: "%.2f giorni, %.1f%%", p.age, p.illum*100))

Counter #13 — Km percorsi dal Sole nella Via Lattea (da quando sei qui)

Stima a 220 km/s. Loader con puntini in orbita.

/* Distanza del Sole vs Via Lattea (stima) a 220 km/s */
const v = 220; const t0 = Date.now();
setInterval(()=> console.log(Math.floor(v * (Date.now()-t0)/1000)), 250);
# Distanza del Sole nella Galassia (km)
import time
v = 220; t0 = time.time()
while True:
    print(int(v * (time.time()-t0)))
    time.sleep(0.25)
/// Distanza galattica (km)
import Foundation
let v = 220.0, t0 = Date()
Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { _ in
  print(Int(v * Date().timeIntervalSince(t0)))
}
RunLoop.main.run()

Counter #14 — Pixel della tua viewport

Larghezza × altezza della finestra. Cambia al resize.

/* Pixel della viewport */
function vp(){ return window.innerWidth * window.innerHeight; }
window.addEventListener('resize', ()=> console.log(vp())); console.log(vp());
# Pixel della finestra (tkinter)
import tkinter as tk
root = tk.Tk()
def log(_=None): print(root.winfo_width()*root.winfo_height())
root.bind("", log); root.mainloop()
/// Pixel della view (UIKit)
import UIKit
print(Int(UIScreen.main.bounds.width * UIScreen.main.bounds.height))