Skip to content

Instantly share code, notes, and snippets.

@dduan
dduan / toTimestamp.swift
Created January 13, 2021 02:16
Convert date components (per RFC3339) to seconds since 1970-01-01
func toTimestamp(year: Int, month: Int, day: Int, hour: Int, minute: Int, seconds: Int, nanoseconds: Int, offsetInSeconds: Int) -> Double {
var year = year
year -= month <= 2 ? 1 : 0
let era = (year >= 0 ? year : year - 399) / 400
let yoe = year - era * 400
let doy = (153*(month + (month > 2 ? -3 : 9)) + 2)/5 + day - 1
let doe = yoe * 365 + yoe/4 - yoe/100 + doy
let dayCounts = era * 146097 + doe - 719468
let seconds = dayCounts * 86400 + hour * 3600 + minute * 60 + seconds - offsetInSeconds
return Double(seconds) + Double(nanoseconds) / 1_000_000_000
@dduan
dduan / bird.swift
Created November 14, 2020 22:16
Flappy bird as a CLI app written in Swift.
// This is the code for the Flappy Bird game running in a Unix terminal.
// Demo: https://twitter.com/daniel_duan/status/1327735679657250816?s=21
// To run it, simply do "swift bird.swift" in a Unix command line.
#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif
enum RawModeError: Error {
@dduan
dduan / cube.swift
Last active November 26, 2020 08:55
A rotating 3-D cube in terminal. Written in Swift
/// A rotating 3-D cube in terminal
/// Only works on macOS
/// Run `swift cube.swift` in a terminal application to run it.
/// For controlling the cube, see comments for `Key` in code.
import Darwin
enum RawModeError: Error {
case notATerminal
case failedToGetTerminalSetting
@dduan
dduan / EscapingClosurePropertyWrapper.swift
Created July 28, 2020 03:55
This property wrapper guarantees that a closure does nothing if its enclosing object is deinitialized.
@propertyWrapper
struct Escaping {
typealias Closure = () -> Void
var store: Closure
var wrappedValue: Closure {
get { self.store }
set { self.store = newValue }
}
@dduan
dduan / SpeakBubble.swift
Last active June 20, 2020 13:56
Twitter's voice tweet UI has an interesting animation on iOS. This is an attempt to recreate that animation with SwiftUI. Looks like this https://youtu.be/I6XZzIgWYAQ
import SwiftUI
struct ChaoticPhoto: View {
let image: Image
let radius: CGFloat
@Binding var activated: Bool
@State var scale: CGFloat = 1
var body: some View {
image
.resizable()
@dduan
dduan / drstring.sh
Created October 15, 2019 05:52
Run DrString anywhere docker is available!
#!/bin/bash
temp_file=$(mktemp)
echo 'FROM swift@sha256:c4d53af406c5dc48bd43c0d313f3ed80924eee4bf78907ce4ad6eb8f5513f376' >> temp_file
echo 'RUN git clone https://github.com/dduan/DrString.git; cd DrString; make build; cp .build/release/drstring /bin/drstring' >> temp_file
echo 'RUN rm -rf /data' >> temp_file
echo 'ADD . /data' >> temp_file
echo 'WORKDIR /data' >> temp_file
echo 'ENTRYPOINT ["drstring"]' >> temp_file
@dduan
dduan / CaseInsensitiveDictionary.swift
Last active June 18, 2019 11:58
A Dictionary implementation in which the key can be case-insensitive.
// CaseInsensitiveDictionary.swift
// Created by Daniel Duan on 12/19/14.
// Usaege Example:
// var test = CaseInsensitiveDictionary<String, Int>()
// test["Winter is coming"] = 1
//
// test["WINTER is Coming"] = test["Winter Is Coming"] // true
// test["Hear Our Roar?"] = 1
//
// test.count == 2 // true
@dduan
dduan / BidirectionalCollection+firstIndex.swift
Last active December 28, 2018 23:21
Find first index of occurrence of a collection in a collection.
/// Usage: myString.firstIndex(of: otherString)
extension BidirectionalCollection where Element: Equatable {
func firstIndex(of other: Self) -> Index? {
guard
let start = other.first.flatMap(self.firstIndex(of:)),
self[start...].count >= other.count,
case let end = self.index(start, offsetBy: other.count),
zip(self[start ..< end], other).allSatisfy(==)
else
{
import Dispatch
class Runner {
var observers = [String: () -> Void]()
let queue = DispatchQueue(label: "foo-queue")
func run() {
let observers = self.observers
for _ in 0..<20000 {
let c: () -> Void = { [weak self] in
@dduan
dduan / fixup-each-staged-file.py
Last active September 18, 2018 05:24
Generate commit for each staged file, such that each commit is a `--fixup` to the commit said file was last changed.
#!/usr/bin/env python
"""
Generate commit for each staged file, such that each commit is a `--fixup` to
the commit said file was last changed.
NOTE: this command will unstage all files. It also does not disninguish staged
and unstaged potion of the same file.
USAGE: stage files you want to commit, run this command. Interactive rebase with
autosquash: `git rebase -i --autosquash BASE`