/
misc.cljc
679 lines (610 loc) · 26.6 KB
/
misc.cljc
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
; Copyright (c) Alan Thompson. All rights reserved.
; The use and distribution terms for this software are covered by the Eclipse Public
; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can be found in the
; file epl-v10.html at the root of this distribution. By using this software in any
; fashion, you are agreeing to be bound by the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns tupelo.misc
"Miscellaneous functions."
; We use the self-require trick to force separate compilation stages for macros
; See "ClojureScript Macro Tower & Loop" by Mike Fikes (2015-12-18)
; https://code.thheller.com/blog/shadow-cljs/2019/10/12/clojurescript-macros.html
; http://blog.fikesfarm.com/posts/2015-12-18-clojurescript-macro-tower-and-loop.html
#?(:cljs
(:require-macros
[tupelo.misc :refer [with-dots]]))
(:require
[clojure.string :as str]
[clojure.walk :as walk]
[schema.core :as s]
[tupelo.core :as t :refer [glue grab thru kw->str validate it-> spyx spyxx vals->map]]
[tupelo.chars :as chars]
[tupelo.schema :as tsk]
[tupelo.string :as ts]
#?(:cljs [goog.crypt :as crypt])
#?(:cljs [goog.crypt.Sha1])
)
#?(:clj (:require ; #todo fix all #?(:clj[s]) requires to be like this
[clj-uuid :as clj-uuid]
[clojure.java.shell :as shell]
[tupelo.java-time :as time]
))
#?(:clj (:import
[java.lang Byte Integer]
[java.nio ByteBuffer]
[java.nio.file Paths]
[java.security MessageDigest]
[java.time Instant]
[java.util UUID]))
)
(s/defn find-pattern :- [s/Int]
"Searches for pattern-vec within data-vec, returning a lazy seq of indexes into data-vec."
[pattern-vec :- tsk/List
data-vec :- tsk/List]
(let [parts (partition (count pattern-vec) 1 data-vec)
idxs (keep-indexed
(fn [idx candidate]
(when (= candidate pattern-vec)
idx))
parts)]
idxs))
(defn take-dist
"Returns a sequence of n items from a collection, distributed
evenly between first & last elements, which are always included."
; #todo write tests, incl degenerate cases of N=0,1,2, etc
[n coll]
{:pre [(pos? n)] }
(let [coll (vec coll)]
(if (= n 1)
[ (first coll) ]
(let [interval (Math/round (double (/ (count coll) (- n 1))))
result (flatten [(take (- n 1) (take-nth interval coll))
(last coll)])]
result))))
(s/defn boolean->binary :- s/Int ; #todo => misc
"Convert true => 1, false => 0"
[arg :- s/Bool] (if arg 1 0))
;---------------------------------------------------------------------------------------------------
(defn walk-map->sorted
"Recursively walks a data structure, converting maps (but not records!) into (plain) sorted maps."
[data]
(walk/postwalk (fn [item]
(t/cond-it-> item
(t/xmap? it) (glue (sorted-map) it)))
data))
(defn walk-map->sorted-generic
"Recursively walks a data structure, converting maps (but not records!) into generic sorted maps.
A generic sort allows keys of different categories such as keyword, string, int, nil, etc."
[data]
(walk/postwalk (fn [item]
(t/cond-it-> item
(t/xmap? it) (glue (t/sorted-map-generic) it)))
data))
(defn walk-rec->map
[data]
(walk/postwalk (fn [item]
(t/cond-it-> item
(record? it) (into {} it)))
data))
; -----------------------------------------------------------------------------
; #todo maybe move to tupelo.bytes ns
(s/defn byte-unsigned->signed
"Converts an unsigned int value [0..255] into a signed byte [-128..127]."
[unsigned-int :- s/Int]
(t/when-clojure-1-9-plus
(when-not (int? unsigned-int)
(throw (ex-info "byte-unsigned->signed: value must be an int" (t/vals->map unsigned-int)))))
(when-not (<= 0 unsigned-int 255)
(throw (ex-info "byte-unsigned->signed: value out of range" (t/vals->map unsigned-int))))
(if (< unsigned-int 128)
unsigned-int
(- unsigned-int 256)))
(s/defn byte-signed->unsigned
"Converts a signed byte [-128..127] into an unsigned byte [0..255]."
[signed-byte :- s/Int]
(t/when-clojure-1-9-plus
(when-not (int? signed-byte)
(throw (ex-info "byte-signed->unsigned: value must be an int" (t/vals->map signed-byte)))))
(when-not (<= -128 signed-byte 127)
(throw (ex-info "byte-signed->unsigned: value out of range" (t/vals->map signed-byte))))
(if (neg? signed-byte)
(+ signed-byte 256)
signed-byte))
(s/defn bytes-unsigned->signed
"Converts a vector of unsigned byte values [0..255] into one of signed byte values [-128..127]"
[byte-vals]
(mapv byte-unsigned->signed byte-vals))
(s/defn bytes-signed->unsigned
"Converts a vector of signed byte values [-128..127] into one of unsigned byte values [0..255] "
[byte-vals]
(mapv byte-signed->unsigned byte-vals))
(def hex-chars [\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f])
(def int->hex (zipmap (range 16) hex-chars))
(def hex->int (zipmap hex-chars (range 16)))
(s/defn byte-unsigned->hex :- s/Str
"Converts a sequence of unsigned bytes [0..255] to a hex string, where each byte becomes 2 hex digits."
[unsigned-byte :- s/Int]
(t/when-clojure-1-9-plus
(when-not (int? unsigned-byte)
(throw (ex-info "unsigned-byte->hex value must be an int" (t/vals->map unsigned-byte)))))
(when-not (<= 0 unsigned-byte 255)
(throw (ex-info "unsigned-byte->hex value out of range" (t/vals->map unsigned-byte))))
(let [high-bits-val (quot unsigned-byte 16)
low-bits-val (mod unsigned-byte 16)
high-char (get hex-chars high-bits-val)
low-char (get hex-chars low-bits-val)]
(str high-char low-char))) ; (crypt/byteArrayToHex byte-arr) ; NOTE: requires unsigned vals [0..255]
(s/defn byte-signed->hex :- s/Str
"Converts a sequence of unsigned bytes [0..255] to a hex string, where each byte becomes 2 hex digits."
[signed-byte]
(-> signed-byte byte-signed->unsigned byte-unsigned->hex))
(s/defn hex-str->unsigned-bytes
"Converts a hex string to a vector of unsigned bytes"
[hex-str :- s/Str]
(when-not (even? (count hex-str))
(throw (ex-info "hex-str must have a whole number of bytes (even length)" {:hex-str hex-str :len (count hex-str)})))
(let [hex-pairs (partition 2 (t/str->chars hex-str))
bytes-unsigned (t/forv [hex-pair hex-pairs]
(let [char-high (first hex-pair)
char-low (second hex-pair)
val-high (grab char-high hex->int)
val-low (grab char-low hex->int)
byte-val (+ val-low (* 16 val-high)) ]
byte-val)) ]
bytes-unsigned) )
(s/defn hex-str->signed-bytes
"Converts a hex string to a vector of unsigned bytes"
[hex-str :- s/Str]
(bytes-unsigned->signed
(hex-str->unsigned-bytes hex-str)))
(s/defn bytes-unsigned->hex-str :- s/Str
"Converts a sequence of unsigned bytes [0..255] to a hex string, where each byte becomes 2 hex digits."
[unsigned-bytes :- [s/Int]]
(str/join (map byte-unsigned->hex unsigned-bytes)))
(s/defn bytes-signed->hex-str :- s/Str
"Converts a sequence of signed bytes [-128..127] to a hex string, where each byte becomes 2 hex digits."
[signed-bytes :- [s/Int]]
(str/join (map byte-signed->hex signed-bytes)))
; for ref: (crypt/stringToUtf8ByteArray s)
(s/defn str->byte-array ; #todo: move to tupelo.string and avoid duplicate!
[str-val :- s/Str]
(let [unsigned-bytes (mapv t/char->codepoint (t/str->chars str-val))
byte-arr (do
#?(:clj (byte-array (bytes-unsigned->signed unsigned-bytes)))
#?(:cljs (into-array unsigned-bytes)))]
byte-arr))
#?(:clj
(def str->sha ; #todo: move to tupelo.string
"Returns the SHA-1 hex string for a string"
(let [sha-1-instance (MessageDigest/getInstance "SHA")]
(s/fn str->sha :- s/Str
[str-val :- s/Str]
(let [byte-arr (str->byte-array str-val)]
(.reset sha-1-instance)
(.update sha-1-instance byte-arr)
(let [bytes (vec (.digest sha-1-instance))
hex-result (bytes-signed->hex-str bytes)]
hex-result))))))
#?(:cljs ; #todo: move to tupelo.string
(s/defn str->sha ; modeled after reagent-utils reagent.crypt
[str-val :- s/Str]
(let [sha-1-instance (goog.crypt.Sha1.)]
(let [byte-arr (str->byte-array str-val)]
(.update sha-1-instance byte-arr))
(let [bytes (vec (.digest sha-1-instance))
hex-result (bytes-unsigned->hex-str bytes)]
hex-result))))
(s/defn hash->hex :- s/Str
"Given arbitrary arguments, uses clojure.lang/hash to generate a 32-bit hex hashcode."
[& args] (format "%08x" (hash args)))
;---------------------------------------------------------------------------------------------------
;#?(:clj ; #todo old way; delete?
; (do
; ;(s/defn long->byte-array
; ; "Converts a Long into an array of bytes (big-endian)."
; ; [arg]
; ; (validate tt/long? arg)
; ; (it-> (ByteBuffer/allocate Long/BYTES)
; ; (.putLong it arg)
; ; (.array it)))
;
; (def uuid->str
; "Returns the SHA-1 hex string for a UUID string"
; (let [sha-1-instance (MessageDigest/getInstance "SHA")]
; (s/fn uuid->str :- s/Str
; [uuid :- java.util.UUID]
; (let [bytes-big (long->byte-array (.getMostSignificantBits ^UUID uuid))
; bytes-little (long->byte-array (.getLeastSignificantBits ^UUID uuid))
; bytes-all-vec (into (vec bytes-big) (vec bytes-little))
; bytes-all (byte-array bytes-all-vec)
; ]
; (spyx (vec bytes-all-vec))
; (.reset sha-1-instance)
; (.update sha-1-instance bytes-big)
; (.update sha-1-instance bytes-little)
; (let [bytes (.digest sha-1-instance)]
; (signed-bytes->hex-str (vec bytes)))))))))
(defn uuid->sha
"Returns the SHA-1 hex string for a UUID's string representation"
[uuid]
(t/when-clojure-1-9-plus
(when-not (uuid? uuid)
(throw (ex-info "arg must be a uuid" (t/vals->map uuid)))))
(let [uuid-str (do
#?(:clj (str uuid))
#?(:cljs (.-uuid uuid)))
usha (str->sha uuid-str)]
usha))
(s/defn sha-uuid :- s/Str
"Returns a string that is the SHA-1 hash of the
Clojure: (clj-uuid/v1)
ClojureScript: (cljs.core/random-uuid)
"
[]
(uuid->sha
#?(:clj (clj-uuid/v1))
#?(:cljs (random-uuid)) ))
(def HID s/Keyword) ; #todo find way to validate
(s/defn new-hid :- HID
"Returns a new HexID"
[]
(keyword (sha-uuid)))
(s/defn hid? :- s/Bool
"Returns true if the arg is a legal HexID"
[arg]
(and (keyword? arg)
(let [name-str (kw->str arg)]
(and (ts/hex? name-str)
; (= 40 (count name-str)) ; #todo make more robust re. with-debug-hid
))))
(defn normalized-sorted ; #todo need tests & docs. Use for datomic Entity?
"Walks EDN data, converting all collections to vector, sorted-map-generic, or sorted-set-generic"
[edn-data]
(let [unlazy-item (fn [item]
(cond
(sequential? item) (vec item)
(t/xmap? item) (t/->sorted-map-generic item)
(set? item) (t/->sorted-set-generic item)
:else item))
result (walk/postwalk unlazy-item edn-data)]
result))
(s/defn edn->sha :- s/Str
"Converts EDN data into a normalized SHA-1 string"
[edn-data]
(str->sha (pr-str (normalized-sorted edn-data))))
;---------------------------------------------------------------------------------------------------
(def ^:no-doc ^:dynamic *debug-flags* #{}) ; ***** for debugging use only *****
(defmacro with-debug-flag
"Merges `flag` into a global state map for the duration of `forms`"
[flag & forms]
`(let [dbg-flags-new# (conj *debug-flags* ~flag)]
(binding [*debug-flags* dbg-flags-new#]
~@forms)))
(defmacro when-debug-flag
"Merges `flag` into a global state map for the duration of `forms`"
[flag & forms]
`(when (contains? *debug-flags* ~flag)
~@forms))
;----- toptop -----------------------------------------------------------------------------
#?(:clj
(do
; #todo Make clojure versions of all pcapng stuff
;
; def split_float( fval ):
; """Splits a float into integer and fractional parts."""
; frac, whole = math.modf( fval )
; micros = int( round( frac * 1000000 ))
; return int(whole), micros
;
; def curr_utc_timetuple():
; """Returns the current UTC time as a (secs, usecs) tuple."""
; global test_ctx
; if test_ctx['enable']:
; utc_secs = test_ctx['utc_time']
; else:
; utc_secs = time.time()
; secs, usecs = split_float( utc_secs )
; return secs, usecs
;
; def curr_utc_secs():
; """Returns the current UTC time in integer seconds."""
; secs, usecs = curr_utc_timetuple()
; return secs
;
; def curr_utc_secs_hexstr()
; """Returns the current UTC time in integer seconds."""
; return int32_to_hexstr(curr_utc_secs())
(def ^:dynamic *os-shell* "/bin/bash") ; could also use /bin/zsh, etc
; #todo *warn-on-lazy* -> print warning on first usage of each lazy function:
; #todo for, map/indexed, flatten, line-seq, concat, distinct, drop/last/while, filter/remove/keep,
; #todo partition*, re-seq, take/nth/while
; #todo add functions:
; fibonacci-list(n) - 1ist n fibo's
; fibonacci-list-bounded(maxVal) - list of fibo's <= maxVal
; prime-list(n) - 1ist n fibo's
; prime-list-bounded(maxVal) - list of fibo's <= maxVal
; #todo
; (defn instaparse-failure? [result] (= (class result) instaparse.gll.Failure))
(defn shell-cmd
"Runs a command string in the default OS shell (/bin/bash); returns result in a Clojure map.
Example:
(shell-cmd \"ls -ldF *\")
;=> {:exit 0 ; unix exit status (0 -> normal)
:err '' ; text from any errors
:out '...' ; text output as would printed to console
}
"
[cmd-str]
(let [result (shell/sh *os-shell* "-c" cmd-str)]
(if (= 0 (grab :exit result))
result
(throw (ex-info "shell-cmd: clojure.java.shell/sh failed, cmd-str:" (vals->map cmd-str result))))))
(defn get-os []
(let [os-name (System/getProperty "os.name")]
(condp re-find (str/lower-case os-name) ; required to match os.name=" Windows 8.1"
#"windows" :windows
#"linux" :linux
#"mac" :mac
(throw (ex-info "get-os: Unknown operating system found: " (vals->map os-name))))))
(comment "stuff to make a generic run-shell-cmd"
(defn format-shell-cmd-vec [cmd-str]
(when-not (string? cmd-str)
(throw (ex-info "format-shell-cmd: cmd-str must be a string; received=" (vals->map cmd-str))))
(if (is-windows?)
["cmd.exe" "/c" cmd-str :dir "c:\\users"] ; windows
["bash" "-c" cmd-str] ; linux
))
(defn run-shell-cmd [cmd-str]
(when-not (string? cmd-str)
(throw (ex-info "format-shell-cmd: cmd-str must be a string; received=" (vals->map cmd-str))))
(apply shell/sh (util/format-shell-cmd-vec cmd-str)))
)
; #todo document in README
(def ^:no-doc dots-lock (Object.))
(def ^:no-doc dots-counter (atom 0))
(def ^:no-doc dots-ctx-default {:dots-per-row 100
:decimation 1
:enabled? true})
(def ^:no-doc dots-ctx
"An atom containing a configuration map for controlling dots printing. Default values:
{:dots-per-row 100
:decimation 1
:enabled? true }
Modify as via:
(alter-var-root (var misc/dots-ctx) glue {:decimation 10} ) ; *** don't forget (var ...) ***
or
(binding [misc/dots-ctx {:dots-per-row 50
:decimation 10
:enabled? true } ]
...) "
(atom nil))
(defn dots-reset!
"Reset dots-ctx to default values "
[] (reset! dots-ctx dots-ctx-default))
(dots-reset!) ; reset upon load
(s/defn dots-config!
"Will override default configuration with values from a map. Default values:
{:dots-per-row 100
:decimation 1
:enabled? true }
Sample Usage:
(dots-config! {:dots-per-row 50
:decimation 10} )
"
[ctx :- tsk/KeyMap]
(swap! dots-ctx glue ctx))
(defn dot
"Prints a single dot (flushed) to the console, keeping a running count of dots printed. Wraps to a
newline when 100 dots have been printed. Displays the running dot count at the beginning of each line.
Usage:
(ns demo.core
(:require [tupelo.misc :as tm]))
(alter-var-root tm/dots-ctx glue {:decimation 10} )
(tm/with-dots
(doseq [ii (range 2345)]
(tm/dot)
(Thread/sleep 5)))
"
[]
(locking dots-lock ; must serialize all printing code
(let [[old-count new-count] (swap-vals! dots-counter inc)
decimation (grab :decimation @dots-ctx)
enabled? (grab :enabled? @dots-ctx)
counts-per-row (* decimation (grab :dots-per-row @dots-ctx))]
(when enabled?
(when (zero? (rem old-count counts-per-row))
(it-> old-count
(str it)
(ts/pad-left it 10)
(glue it \space)
(print it))
(flush))
(when (zero? (rem old-count decimation))
(print \.)
(flush))
(when (zero? (rem new-count counts-per-row))
(newline)
(flush))))))
(defmacro with-dots ; #todo rework this
"Resets the dot counter and prints a total when completed."
[& body]
`(do
(reset! dots-counter 0)
(let [result# (do ~@body)]
(when (grab :enabled? @dots-ctx)
(newline)
(println (#?(:clj format
:cljs rfmt/format)
"%10d total" @dots-counter))
(newline))
result#)))
(s/defn hid->wid :- s/Keyword
"Uses an HID to look up a human-friendly Word-ID (WID) from an English dictionary.
Useful for debugging purposes."
[hid :- HID]
nil) ; #todo
;-----------------------------------------------------------------------------
; -> tupelo.files ?
(defn get-path
"Wrapper for Java Paths/get to work around the varargs strangeness"
[path-str]
(Paths/get "." (into-array String [path-str])))
;-----------------------------------------------------------------------------
; #todo -> tupelo.vector
; #todo README & more tests
;; Assuming require [clojure.tools.logging :as log]
(defn log-uncaught-exceptions []
(Thread/setDefaultUncaughtExceptionHandler
(reify Thread$UncaughtExceptionHandler
(uncaughtException [_ thread ex]
(println ex "Uncaught exception on" (.getName thread)))))) ; or (log/error ...)
(s/defn stacktrace-info :- [tsk/KeyMap] ; #todo make cljs version
"Returns a map with the caller's namespace and function names as strings, like:
{:ns-name 'tst.demo.core' :fn-name 'funky'} "
[throwable :- Throwable]
(let [stacktrace (.getStackTrace throwable)
stacktrace-info (t/distinct-using #(grab :class-name %)
(for [st-elem stacktrace]
(let [class-name (.getClassName st-elem)
file-name (.getFileName st-elem)
method-name (.getMethodName st-elem)
line-num (.getLineNumber st-elem)
; class-name-caller is (usually) like "tst.demo.core$funky".
; if no `$` is present, don't crash!
idx (str/index-of class-name \$)
ns-name (t/cond-it-> class-name
(t/not-nil? idx) (subs class-name 0 idx))
fn-name (if (t/not-nil? idx)
(subs class-name (inc idx))
"")]
(vals->map class-name file-name method-name line-num ns-name fn-name))))]
stacktrace-info))
(s/defn fn-info :- tsk/KeyMap ; #todo make cljs version
"Returns a map of info about the current function, like:
{:ns-name 'demo.core'
:fn-name 'add2'
:class-name 'demo.core$add2'
:file-name 'core.clj'
:line-num 57
:method-name 'invokeStatic' }
"
[]
(let [stacktrace-info (stacktrace-info (RuntimeException. "dummy"))
my-ns (grab :ns-name (t/xfirst stacktrace-info))
info-keep (t/drop-if (fn [ste]
(let [unwanted-flg (and (= my-ns (grab :ns-name ste))
(ts/contains-match? (grab :fn-name ste) #"fn.info"))]
; (spyx (vals->map ste unwanted-flg))
unwanted-flg))
stacktrace-info)]
(t/xfirst info-keep)))
(s/defn fn-info-caller :- tsk/KeyMap ; #todo make cljs version
"Returns a map of info about the caller of the current function, like:
{:ns-name 'demo.core'
:fn-name 'add2'
:class-name 'demo.core$add2'
:file-name 'core.clj'
:line-num 57
:method-name 'invokeStatic' }
"
[]
(let [stacktrace-info (stacktrace-info (RuntimeException. "dummy"))
my-ns (grab :ns-name (t/xfirst stacktrace-info))
info-keep (t/drop-if (fn [ste]
(let [unwanted-flg (and (= my-ns (grab :ns-name ste))
(ts/contains-match? (grab :fn-name ste) #"fn.info"))]
; (spyx (vals->map ste unwanted-flg))
unwanted-flg))
stacktrace-info)]
(t/xsecond info-keep)))
))
#?(:cljs
(do
(defn grouper
"Uses js/RegExp to find matching groups. Sample output:
(grouper #\"[a-z0-9][A-Z]\" \"aTaTa\") =>
[ {:groups [\"aT\"] :match \"aT\" :index 0 :last-index 2 :input \"aTaTa\" }
{:groups [\"aT\"] :match \"aT\" :index 2 :last-index 4 :input \"aTaTa\" } ]
(grouper #\"((\\d+)-(\\d+))\" \"672-345-456-3212\") =>
[ {:groups [\"672-345\" \"672-345\" \"672\" \"345\" ] :match \"672-345\" :index 0 :last-index 7 :input \"672-345-456-3212\" }
{:groups [\"456-3212\" \"456-3212\" \"456\" \"3212\"] :match \"456-3212\" :index 8 :last-index 16 :input \"672-345-456-3212\" } ]
Note that the JS value returned by `:last-index` is the index of the first char in the input string *after* the current match.
"
[re input-str]
(let [re-src (.-source re)] ; the source string from the regexp arg
(loop [groups []
regexp (js/RegExp. re-src "g")] ; 'g' => global search
(let [res-js (.exec regexp input-str)
res-clj (js->clj res-js)]
(if (nil? res-js)
groups
(recur
(conj groups {:groups res-clj :match (get res-clj 0)
:index (.-index res-js)
:input (.-input res-js)
:last-index (.-lastIndex regexp)})
regexp))))))
))
; #todo move to tupelo
;
;(def xml-file-name
; "data.xml"
; ;"data-1k.xml"
; ;"data-10k.xml"
; ;"data-full.xml"
; )
;(def bush-file-name "data-bush.edn")
;
;(defn load-xml-data []
; (-> xml-file-name
; (io/resource)
; (io/input-stream)
; (slurp)))
;
;(defn load-bush-data []
; (let [bush-data (with-timer :load-bush-data
; (-> bush-file-name
; (io/resource)
; (io/input-stream)
; (slurp)
; (edn/read-string)))]
; (spyx-pretty (clip-str 999 bush-data))
; ))
;
;
;(defn xml->bush []
; (with-forest (new-forest)
; (let [xml-data (with-timer :xml-data
; (load-xml-data))
; ;>> (println :xml-data \newline (clip-str 999 xml-data))
; enlive-data (with-timer :xml->enlive
; (xml->enlive xml-data))
; ;>> (println :enlive-data \newline (clip-str 999 enlive-data))
; tree-data (with-timer :enlive->tree
; (enlive->tree enlive-data))
; root-hid (with-timer :add-tree
; (add-tree tree-data))
; >> (with-timer :count-all-hid
; (spyx (count (all-hids))))
; bush-data (with-timer :hid->bush
; (hid->bush root-hid))
; ;>> (spyx-pretty (clip-str 999 bush-data))
; bush-data-str (with-timer :pretty-str (pretty-str bush-data))
; ]
; ;(println (clip-str 999 bush-data-str))
; (print "writing data...")
; (spit (str "resources/" bush-file-name) bush-data-str)
; (println " done.")))
; )
;
;
;(defn -main [& args]
; (println "main - enter")
; ;(println "main - hit <enter> to start:" ) (read-line)
; ;(xml->bush)
; (load-bush-data)
;
; ;(println "main - hit <enter> to exit:" ) (read-line)
; (println "main - leave")
; )
;