-
Notifications
You must be signed in to change notification settings - Fork 0
/
clj_utils.clj
478 lines (402 loc) · 16.2 KB
/
clj_utils.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
(ns com.nomistech.clj-utils
(:require [clojure.set :as set]
[clojure.string :as str]
[clojure.walk :as walk]))
;;;; ___________________________________________________________________________
;;;; ---- do1 ----
(defmacro do1
"Evaluates all the forms and returns the result of the first form."
{:style/indent 1}
[form-1 & other-forms]
`(let [result# ~form-1]
~@other-forms
result#))
;;;; ___________________________________________________________________________
;;;; ---- do2 ----
(defmacro do2
"Evaluates all the forms and returns the result of the second form."
{:style/indent 2}
[form-1 form-2 & other-forms]
`(do
~form-1
(do1
~form-2
~@other-forms)))
;;;; ___________________________________________________________________________
;;;; ---- econd ----
(defmacro econd
"Like `cond`, except throws a RuntimeException if no clause matches."
[& clauses]
`(cond ~@clauses
:else (throw (RuntimeException. "econd has no matching clause"))))
;;;; ___________________________________________________________________________
;;;; Maybe use the following approach instead of `map-keys` and `map-vals`
#_
(->> m
(map (fn [[k v]] [k (f1 v)]))
(map (fn [[k v]] [(f2 k) v]))
(map (fn [[k v]] [(f3 k) (f4 v)]))
(into {}))
;;;; ___________________________________________________________________________
;;;; ---- map-keys ----
(defn map-keys
"Apply `f` to each of the keys of `m`."
[f m]
(into {}
(for [[k v] m]
[(f k) v])))
;;;; ___________________________________________________________________________
;;;; ---- map-vals ----
(defn map-vals
"Apply `f` to each of the vals of `m`."
[f m]
(into {}
(for [[k v] m]
[k (f v)])))
;;;; ___________________________________________________________________________
;;;; ---- map-kv ----
(defn map-kv
"Apply `f` to each of the entries of `m`. `f` takes two args, a key and
a value."
[f m]
(into {}
(for [[k v] m]
(f k v))))
;;;; ___________________________________________________________________________
;;;; ---- postwalk-applying-to-maps ----
(defn ^:private postwalk-applying-to-maps [entry-fn x]
(walk/postwalk (fn [xx] (if (map? xx)
(into {} (map entry-fn xx))
xx))
x))
;;;; ___________________________________________________________________________
;;;; ---- map-keys-recursively-applying-to-maps ----
(defn map-keys-recursively-applying-to-maps
"Walk `x`, applying `f` to the keys of any maps.
Call `f` when the keys are themselves maps."
[f x]
(let [entry-fn (fn [[k v]] [(f k) v])]
(postwalk-applying-to-maps entry-fn x)))
;;;; ___________________________________________________________________________
;;;; ---- map-keys-recursively ----
(defn map-keys-recursively
"Walk `x`, applying `f` to the keys of any maps.
Don't call `f` when the keys are themselves maps."
[f x]
(let [entry-fn (fn [[k v]] [(if (map? k)
;; leave untouched; walking deeper levels will
;; deal with this
k
(f k))
v])]
(postwalk-applying-to-maps entry-fn x)))
;;;; ___________________________________________________________________________
;;;; ---- map-vals-recursively-applying-to-maps ----
(defn map-vals-recursively-applying-to-maps
"Walk `x`, applying `f` to the vals of any maps.
Call `f` when the keys are themselves maps."
[f x]
(let [entry-fn (fn [[k v]] [k (f v)])]
(postwalk-applying-to-maps entry-fn x)))
;;;; ___________________________________________________________________________
;;;; ---- map-vals-recursively ----
(defn map-vals-recursively
"Walk `x`, applying `f` to the vals of any maps.
Don't call `f` when the keys are themselves maps."
[f x]
(let [entry-fn (fn [[k v]] [k
(if (map? v)
;; leave untouched; walking deeper levels will
;; deal with this
v
(f v))])]
(postwalk-applying-to-maps entry-fn x)))
;;;; ___________________________________________________________________________
;;;; ---- map-kv-recursively ----
(defn map-kv-recursively
"Walk `x`, applying `f` to any map entries."
[f x]
(let [entry-fn (fn [[k v]] (f k v))]
(postwalk-applying-to-maps entry-fn x)))
;;;; ___________________________________________________________________________
;;;; ---- group-by-kv ----
(defn group-by-kv [f m]
(map-vals #(into {} %)
(group-by (fn [[k v]] (f k v))
m)))
;;;; ___________________________________________________________________________
;;;; ---- group-by-k ----
(defn group-by-k [f m]
(group-by-kv (fn [k _] (f k))
m))
;;;; ___________________________________________________________________________
;;;; ---- group-by-v ----
(defn group-by-v [f m]
(group-by-kv (fn [_ v] (f v))
m))
;;;; ___________________________________________________________________________
;;;; ---- transitive-closure ----
(defn ^:private transitive-closure-helper [f visited sofar vs]
(letfn [(helper [visited sofar vs]
(if (empty? vs)
sofar
(let [next-vs (set (->> (mapcat f vs)
(remove visited)
(remove vs)))]
(recur (into visited next-vs)
(into sofar next-vs)
next-vs))))]
(helper visited sofar vs)))
(defn transitive-closure
"The set of values obtained by starting with v, then applying f to v,
then applying f to each of the results, and so on. v and all
intermediate values are included in the result."
[f v]
(transitive-closure-helper f #{v} #{v} #{v}))
;;;; ___________________________________________________________________________
;;;; ---- transitive-closure-excluding-self ----
(defn transitive-closure-excluding-self
"The set of values obtained by applying f to v,
then applying f to each of the results, and so on. All
intermediate values are included in the result."
[f v]
(transitive-closure-helper f #{v} #{} #{v}))
;;;; ___________________________________________________________________________
;;;; ---- invert-function invert-relation ----
(defn invert-function [f domain-subset]
"Return a map that represents the inverse of `f`.
`f` takes elements of `domain-subset` (and possibly other values, not
relevant here) as argument, and returns a single value.
For explanations of terminology, see:
https://www.mathsisfun.com/sets/domain-range-codomain.html"
(dissoc (group-by f domain-subset)
nil))
(defn invert-relation [rel domain-subset]
"Return a map which represents the inverse of `rel`.
`rel` takes elements of `domain-subset` (and possibly other values, not
relevant here) as argument, and returns a collection of values.
For explanations of terminology, see:
https://www.mathsisfun.com/sets/domain-range-codomain.html"
(let [domain-range-pairs (for [d domain-subset
r (rel d)]
[d r])]
(reduce (fn [sofar [d r]]
(update sofar
r
(fnil conj [])
d))
{}
domain-range-pairs)))
;;;; ___________________________________________________________________________
;;;; ---- with-extras ----
(defn fun-with-extras [before-f after-f f]
(before-f)
(let [result (f)]
(after-f result)
result))
(defmacro with-extras
{:style/indent 1}
[{:keys [before after]}
& body]
"Does `before`, then `body`, then `after`. Returns the result of `body`.
Within `after`, the result of `body` is available as `%result%`."
`(fun-with-extras (fn [] ~before)
(fn [~'%result%] ~after)
(fn [] ~@body)))
;;;; ___________________________________________________________________________
;;;; ---- member? ----
(defn member? [item coll]
(some #{item} coll))
;;;; ___________________________________________________________________________
;;;; ---- submap? ----
(defn submap? [m1 m2]
(= m1 (select-keys m2 (keys m1))))
(defn submap?-v2 [m1 m2]
(set/subset? (set m1) (set m2)))
;;;; ___________________________________________________________________________
;;;; ---- deep-merge ----
(defn deep-merge
"Recursively merges maps. If vals are not maps, the last value wins."
[& vals]
(if (every? map? vals)
(apply merge-with deep-merge vals)
(last vals)))
;;;; ___________________________________________________________________________
;;;; ---- select-keys-recursively ----
(defn select-keys-recursively
"Similar to `select-keys`, but with key paths digging in to a nested map.
`key-paths` is a sequence. Each element of `key-paths` begins with a key, k,
to be selected and is followed by a vector of key paths that specify the
things to be selected from the value corresponding to k.
Example:
(select-keys-recursively {:k-1 \"v-1\"
:k-2 {:k-2-1 \"v-2-1\"
:k-2-2 {:k-2-2-1 \"v-2-2-1\"
:k-2-2-2 \"v-2-2-2\"
:k-2-2-3 \"v-2-2-3\"}}
:k-3 \"v-3\"}
[[:k-1]
[:k-2 [:k-2-2
[:k-2-2-1]
[:k-2-2-3]]]])
=> {:k-1 \"v-1\"
:k-2 {:k-2-2 {:k-2-2-1 \"v-2-2-1\"
:k-2-2-3 \"v-2-2-3\"}}}"
[m key-paths]
(or (apply merge
(for [p key-paths]
(let [n (count p)]
(case n
0 (throw (Error. "Empty path in key-paths"))
1 (select-keys m [(first p)])
(if-not (contains? m (first p))
{}
{(first p) (select-keys-recursively (get m (first p))
(rest p))})))))
{}))
;;;; ___________________________________________________________________________
;;;; ---- indexed ----
(defn indexed
;; From http://stackoverflow.com/questions/4830900, with changes.
"Returns a lazy sequence of [index, item] pairs, where items come
from 's' and indexes count up from zero.
eg:
(indexed '(a b c d)) => ([0 a] [1 b] [2 c] [3 d])"
[s]
(map-indexed vector s))
;;;; ___________________________________________________________________________
;;;; ---- position ----
;;;; ---- positions ----
(defn positions
;; From http://stackoverflow.com/questions/4830900.
"Returns a lazy sequence containing the positions at which pred
is true for items in coll."
[pred coll]
(for [[idx elt] (indexed coll)
:when (pred elt)]
idx))
(defn position
[pred coll]
(first (positions pred coll)))
;;;; ___________________________________________________________________________
;;;; ---- unchunk ----
(defn unchunk
"Produce a fully-lazy sequence from `s`.
Sometimes Clojure sequences are not fully lazy.
See http://blog.fogus.me/2010/01/22/de-chunkifying-sequences-in-clojure/
for details.
See also Stuart Sierra comment at https://stackoverflow.com/questions/3407876/how-do-i-avoid-clojures-chunking-behavior-for-lazy-seqs-that-i-want-to-short-ci"
[s]
;; TODO Is there a reason to prefer one of these over the other?
;; - Isn't `rest` lazier than `next`?
;; - Add auto-test that would distinguish. (Or do you already have one?
(case 2
1 (when (seq s)
(lazy-seq
(cons (first s)
(unchunk (next s)))))
2 (lazy-seq
(when-let [[x] (seq s)]
(cons x (unchunk (rest s)))))))
;;;; ___________________________________________________________________________
;;;; ---- last-index-of-char-in-string ----
(defn last-index-of-char-in-string [^Character char ^String string]
;; Effect of type hints:
;; Without:
;; (time (dotimes [i 1000000] (last-index-of-char-in-string \c "abcdef")))
;; "Elapsed time: 2564.688 msecs"
;; With:
;; (time (dotimes [i 1000000] (last-index-of-char-in-string \c "abcdef")))
;; "Elapsed time: 18.44 msecs"
(.lastIndexOf string (int char)))
;;;; ___________________________________________________________________________
;;;; ---- limiting-n-executions ----
;;;; Functionality for limiting the number of concurrent executions of a
;;;; piece or pieces of code.
(def ^:private limiter-id->n-executions
(atom {}))
(defn limiting-n-executions
"If we currently do not have too many concurrent executions, call `fun`.
Otherwise call `fun-when-too-many`.
Not having too many concurrent executions is defined like this:
- consider the number of current executions of this function that share the
supplied `limiter-id`
- this number must be less than `max-executions`."
[limiter-id
max-executions
fun
fun-when-too-many]
(let [m (swap! limiter-id->n-executions update limiter-id (fnil inc 0))]
(try (if (<= (get m limiter-id)
max-executions)
(fun)
(fun-when-too-many))
(finally (swap! limiter-id->n-executions update limiter-id dec)))))
;;;; ___________________________________________________________________________
;;;; ---- with-return-429-if-too-many-requests ----
(defn ^:private retry-after-value-for-429-responses
"Return a random integer that is between the min and max retry-after values,
inclusive."
[min max]
(+ min (rand-int (inc (- max min)))))
(defn fun-with-return-429-if-too-many-requests
"`options` is a map with the following keys:
- :limiter-id
- :max-concurrent-requests
- :min-retry-after-secs
- :max-retry-after-secs
If we currently do not have too many concurrent executions, call `fun`.
Otherwise return a Ring response map with status 429 and a Retry-After value
that is between `min-retry-after-secs` and `max-retry-after-secs`.
Not having too many concurrent executions is defined like this:
- consider the number of current executions of this function that share the
supplied `limiter-id`
- this number must be less than `max-concurrent-requests`."
[options fun]
(let [{:keys [limiter-id
max-concurrent-requests
min-retry-after-secs
max-retry-after-secs]} options]
(assert (not (nil? limiter-id)))
(assert (not (nil? max-concurrent-requests)))
(assert (not (nil? min-retry-after-secs)))
(assert (not (nil? max-retry-after-secs)))
(let [retry-after-value (retry-after-value-for-429-responses
min-retry-after-secs
max-retry-after-secs)]
(limiting-n-executions limiter-id
max-concurrent-requests
fun
(fn []
{:status 429
:headers {"Retry-After" (str
retry-after-value)}
:body nil})))))
(defmacro with-return-429-if-too-many-requests
"Macro wrapper for `fun-with-return-429-if-too-many-requests`."
{:style/indent 1}
[options & body]
`(fun-with-return-429-if-too-many-requests ~options
(fn [] ~@body)))
;;;; ___________________________________________________________________________
;;;; Detection of Emacs temp files
;;;; - Copied from `stasis.core`.
(def ^:private fsep (java.io.File/separator))
(def ^:private fsep-regex (java.util.regex.Pattern/quote fsep))
(defn ^:private normalize-path [^String path]
(if (= fsep "/")
path
(.replaceAll path fsep-regex "/")))
(defn ^:private get-path [^java.io.File path]
(-> path
.getPath
normalize-path))
(defn ^:private path->filename [^String path]
(last (str/split path #"/")))
(defn emacs-temp-file-path? [^String path]
(let [filename (path->filename path)]
(or (.startsWith filename ".#")
(and (.startsWith filename "#")
(.endsWith filename "#")))))
(defn emacs-temp-file? [^java.io.File file]
(-> file get-path emacs-temp-file-path?))