-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
9994 lines (9651 loc) · 431 KB
/
gulpfile.js
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview Gulp file for Lone Dissent
* @author <a href="mailto:[email protected]">Jeff Parsons</a> (@jeffpar)
* @copyright © Jeff Parsons 2018-2019
* @license GPL-3.0
*
* Gulp Tasks
* ----------
*
* To get *just* the latest SCOTUS transcripts, run the following command twice (once to get new HTML files, and
* again to get any new PDFs listed in the HTML files):
*
* gulp download --source=scotus
*
* NOTE: Now that the 2018 term has ended, I've updated _sources.json5 to advance the current term from 2018 to 2019.
*
* Notes on Supreme Court Terms
* ----------------------------
*
* The following excerpts from "Explanation of certain items in the 'Justices of the Supreme Court' Table"
* (https://www.thegreenpapers.com/Hx/JusticesExplanation.html) are helpful in understanding the evolution
* of Supreme Court terms; however, it doesn't touch on any of the "Special Terms" established by the Court
* from time to time -- a byproduct of the Court's ability to define its own terms, starting in 1911.
*
* "[T]he Supreme Court was to ... meet twice a year, beginning on the first Monday in February
* and again on the first Monday in August.... From February 1790, when the Court had its first quorum ...
* (though, as the highest appellate court in a new Federal System in which even its lower courts were
* still getting themselves organized, there was no judicial business to transact in that very first Term
* of Court other than the appointment of clerks and admitting various attorneys to the bar of the Supreme
* Court itself), through August 1801, this schedule of Terms of Court was followed."
*
* "[T]he [Judiciary Act of 1801 allowed] the Supreme Court to meet at different times of the year than
* heretofore, June and December, beginning in 1802."
*
* "[T]he Judiciary Act of 1802 restored the February Term (to begin on the first Monday in February)
* but permanently abolished the August one; from now on, the Supreme Court would meet in annual Terms
* of Court instead of twice a year.... [I]t being after February 1802 by the time the new Act became
* law (and with no more August Term), the next time the Supreme Court would meet would be February 1803."
*
* "In 1826, ... [t]he only relief for the Justices of the Supreme Court was moving the convening of the
* Term of Court up to the second Monday in January: this was in response to complaints that the Supreme
* Court had to complete its old February annual term by the end of March in order to give the Justices
* time to get out of Washington for Circuit Court duty."
*
* "Similar complaints nearly two decades later (after two new Circuits had been created, mind you!) led
* to the Act of 17 June 1844 which would, effective in 1845, move the start of the Court's Term up to
* the first Monday in December."
*
* "In 1873, Congress once again changed the start of Terms of the Supreme Court, moving the starting date
* up to the second Monday in October to help the Court clear their annual docket of an increasing amount
* of cases."
*
* "The 1911 Judicial Code also permitted the Supreme Court to determine its own Terms of Court under its
* own rules.... In 1917, the Supreme Court exercised its new authority and moved the start of its Term up
* to the present (and rather well-known) first Monday in October."
*
* Our own observations, based on examination of selected volumes of U.S. Reports:
*
* 1) In 1790, and continuing through 1800, we see Feb and Aug terms; eg:
*
* Feb Term 1790: http://cdn.loc.gov/service/ll/usrep/usrep002/usrep002399/usrep002399.pdf (the Court acknowledges appointments of the first five Justices)
* Aug Term 1790: http://cdn.loc.gov/service/ll/usrep/usrep002/usrep002400/usrep002400.pdf (the Court acknowledges appointment of Justice Iredell)
* Feb Term 1791: http://cdn.loc.gov/service/ll/usrep/usrep002/usrep002400/usrep002400.pdf (basically just admissions to the bar)
* Aug Term 1791: http://cdn.loc.gov/service/ll/usrep/usrep002/usrep002401/usrep002401.pdf (first opinion listed in SCDB)
* ...
* Feb Term 1800: http://cdn.loc.gov/service/ll/usrep/usrep004/usrep004012/usrep004012.pdf
* Aug Term 1800: http://cdn.loc.gov/service/ll/usrep/usrep004/usrep004028/usrep004028.pdf
*
* 2) In 1801, we see Aug and Dec terms (no Feb term, and NO terms in 1802):
*
* Aug Term 1801: http://cdn.loc.gov/service/ll/usrep/usrep005/usrep005001/usrep005001.pdf
* Dec Term 1801: http://cdn.loc.gov/service/ll/usrep/usrep005/usrep005117/usrep005117.pdf
*
* The presence of a Dec Term 1801 looks like an anomaly, perhaps due to the confusion wrought by
* the competing Judiciary Acts of 1801 and 1802.
*
* 3) In 1803, and continuing through 1826, we see only Feb terms:
*
* Feb Term 1803: http://cdn.loc.gov/service/ll/usrep/usrep005/usrep005137/usrep005137.pdf (Marbury v. Madison)
* ...
* Feb Term 1806: http://cdn.loc.gov/service/ll/usrep/usrep007/usrep007241/usrep007241.pdf
* ...
*
* 4) In 1827, we see the first January term (Jan Term 1827).
*
* 5) In 1850, we see the final January term (Jan Term 1850) and the first December term (Dec Term 1850);
* technically however, December terms began in 1844. The Court simply chose to continue calling them
* "January" terms until December 1850. Consequently, there weren't really two terms in 1850, as some
* would suggest; I think it's more correct to say there were two terms in 1844, since what's called the
* "January 1845" term actually began in December 1844.
*
* This is confirmed by the fact that, unlike 1843, there were numerous decisions handed down in
* December 1844. Thus I suspect that the comment above that "the Act of 17 June 1844" became "effective
* in 1845" is incorrect.
*
* 6) In 1873, we see the first October Term (Oct Term 1873), beginning on the *second* Monday of October.
*
* 7) In 1917, we see the first October Term (Oct Term 1917), beginning on the *first* Monday of October.
*
* TODO: Make a list of all "Special Terms" created by the Court (presumably they are all after 1911).
*/
import glob from "glob";
import gulp from "gulp";
import fs from "fs";
import json5 from "json5";
import mkdirp from "mkdirp";
import path from "path";
import request from "request";
import he from "he";
import xml2js from "xml2js";
let parseXML = xml2js.parseString;
import readLineSync from "readline-sync";
import puppeteer from "puppeteer";
import datelib from "./lib/datelib.js";
let parseDate = datelib.parseDate;
let isValidDate = datelib.isValidDate;
let adjustDays = datelib.adjustDays;
import proclib from "./lib/proclib.js";
import stdio from "./lib/stdio.js";
let printf = stdio.printf;
let sprintf = stdio.sprintf;
let rootDir = ".";
let _data = JSON.parse(fs.readFileSync(rootDir + "/_data/_data.json"));
let logs = JSON.parse(fs.readFileSync(rootDir + "/logs/_logs.json"));
let sources = json5.parse(fs.readFileSync(rootDir + "/sources/_sources.json5"));
let argv = proclib.args.argv;
let downloadTasks = [];
let warnings = 0;
let months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
/**
* @typedef {object} Justice
* @property {string} id
* @property {string} name
* @property {string} position
* @property {number} seat
* @property {string} start
* @property {string} startFormatted
* @property {string} stop
* @property {string} stopFormatted
* @property {string} stopReason
* @property {string} photo
* @property {number} scdbJustice
*/
/**
* @typedef {object} Court
* @property {string} id
* @property {string} name
* @property {Array.<Justice>} justices
* @property {string} start
* @property {string} startFormatted
* @property {string} stop
* @property {string} stopFormatted
* @property {string} reason
* @property {string} photo
*/
/**
* @typedef {object} Vote
* @property {string} justice
* @property {string} justiceName
* @property {string} vote
* @property {string} opinion
* @property {string} direction
* @property {string} majority
* @property {string} firstAgreement
* @property {string} secondAgreement
*/
/**
* For a complete list of possible values for the following decision variables, see sources/scdb/vars.json.
*
* @typedef {object} Decision
* @property {string} caseId
* @property {string} docketId
* @property {string} caseIssuesId
* @property {string} voteId
* @property {string} dateDecision
* @property {number} decisionType
* @property {string} usCite
* @property {string} sctCite
* @property {string} ledCite
* @property {string} lexisCite
* @property {number} term
* @property {number} naturalCourt
* @property {string} chief
* @property {string} docket
* @property {string} caseName
* @property {string} caseTitle
* @property {string} dateArgument
* @property {string} dateRearg
* @property {number} petitioner
* @property {number} petitionerState
* @property {number} respondent
* @property {number} respondentState
* @property {number} jurisdiction
* @property {number} adminAction
* @property {number} adminActionState
* @property {number} threeJudgeFdc
* @property {number} caseOrigin
* @property {number} caseOriginState
* @property {number} caseSource
* @property {number} caseSourceState
* @property {number} lcDisagreement
* @property {number} certReason
* @property {number} lcDisposition
* @property {number} lcDispositionDirection
* @property {number} declarationUncon
* @property {number} caseDisposition
* @property {number} caseDispositionUnusual
* @property {number} partyWinning
* @property {number} precedentAlteration
* @property {number} voteUnclear
* @property {number} issue
* @property {number} issueArea
* @property {number} decisionDirection
* @property {number} decisionDirectionDissent
* @property {number} authorityDecision1
* @property {number} authorityDecision2
* @property {number} lawType
* @property {number} lawSupp
* @property {string} lawMinor
* @property {number} majOpinWriter
* @property {number} majOpinAssigner
* @property {number} splitVote
* @property {number} majVotes
* @property {number} minVotes
* @property {number} justice
* @property {string} justiceName
* @property {number} vote
* @property {number} opinion
* @property {number} direction
* @property {number} majority
* @property {number} firstAgreement
* @property {number} secondAgreement
* @property {Array.<Vote>} justices (this array contains sets of the preceding 8 fields once all the records have been "factored")
*/
/**
* @typedef {object} Marker
* @property {number} page
* @property {number} line
* @property {string} text
*/
/**
* @typedef {object} RoleMarker
* @property {string} name
* @property {boolean} female
* @property {string} role
*/
/**
* @typedef {object} CaseMarker
* @property {number} page
* @property {number} line
* @property {string} text
* @property {string} caseNumber
* @property {string} caseName
* @property {string} caseEvent
* @property {boolean} argument
* @property {Array.<RoleMarker>} roles
*/
/**
* @typedef {object} DateMarker
* @property {number} page
* @property {number} line
* @property {string} text
* @property {string} weekday
* @property {number} day
* @property {string} month
* @property {number} year
* @property {string} date (ie, "YYYY-MM-DD")
* @property {Array.<CaseMarker>} cases
*/
/**
* assertMatch(s1, s2, comment)
*
* @param {*} s1
* @param {*} s2
* @param {string} [comment]
* @returns {boolean}
*/
function assertMatch(s1, s2, comment="")
{
if (s1 !== s2) {
warning("assertMatch(%s != %s): %s\n", s1, s2, comment);
return false;
}
return true;
}
/**
* warning(format, ...args)
*
* @param {string} format
* @param {...} args
*/
function warning(format, ...args)
{
printf("warning: " + format, ...args);
warnings++;
}
/**
* checkASCII(text, fileName, encoding)
*
* @param {string} text
* @param {string} [fileName]
* @param {boolean} [encoding] (if "ascii", then we warn if there are any characters > 0x7f)
* @return {boolean} (true if valid, false otherwise)
*/
function checkASCII(text, fileName, encoding)
{
if (text.indexOf("\u2014") >= 0) {
text = text.replace(/\u2014/g, "-");
}
let lines = text.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
for (let j = 0; j < line.length; j++) {
let ch = line.charCodeAt(j);
if (ch < 0x20 && ch != 0x09 && ch != 0x0c || encoding == "ascii" && ch > 0x7f) {
// warning("unexpected character \\u%04x%s at row %d col %d: '%s'\n", ch, fileName? (" in file " + fileName) : "", i+1, j+1, line);
}
}
}
return text;
}
/**
* fixASCII(text)
*
* @param {string} text
* @return {string}
*/
function fixASCII(text)
{
let textNew = "";
for (let i = 0; i < text.length; i++) {
let c = text.charCodeAt(i);
switch(c) {
case 0x91:
textNew += "‘";
break;
case 0x92:
textNew += "’";
break;
case 0x93:
textNew += "“";
break;
case 0x94:
textNew += "”";
break;
case 0x96:
textNew += "–";
break;
case 0xA7:
textNew += "§";
break;
default:
if (c >= 0x7f) {
warning("text '%s' contains unrecognized character '%c' (0x%02x) at pos %d\n", text, c, c, i + 1);
break;
}
textNew += String.fromCharCode(c);
break;
}
}
return textNew;
}
/**
* decodeString(text, decodeAs)
*
* @param {string} text
* @param {string} [decodeAs] (eg, "html")
*/
function decodeString(text, decodeAs)
{
if (decodeAs == "html") {
/**
* Replace any old-fashioned "&c" references that could be misinterpreted as HTML entities.
*/
text = text.replace(/&C\./g, "ETC.").replace(/&c\./g, "etc.").replace(/&/g, "&").replace(/&NBSP;/g, "");
text = he.decode(text);
}
return text;
}
/**
* encodeString(text, encodeAs, fAllowQuotes)
*
* @param {string} text
* @param {string} [encodeAs] (eg, "html")
* @param {string} [fAllowQuotes] (default is true)
* @return {string}
*/
function encodeString(text, encodeAs, fAllowQuotes=true)
{
if (encodeAs == "html") {
/**
* In case there are already HTML entities in the string, decode first to avoid double-encoding.
*/
text = decodeString(text, encodeAs);
text = he.encode(text, {
'encodeEverything': false,
"useNamedReferences": true
});
if (fAllowQuotes) text = text.replace(/'/g, "'").replace(/"/g, '"');
/**
* Some input (eg, "latin1") may contain extended ASCII characters that should be encoded as entities, too.
*/
text = fixASCII(text);
}
return text;
}
/**
* mapValues(o, vars, strict)
*
* @param {object} o
* @param {object} vars
* @param {boolean} [strict]
* @return {number}
*/
function mapValues(o, vars, strict=false)
{
let changes = 0;
let keys = Object.keys(o);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
if (vars[key]) {
let varType = vars[key].type;
if (varType != typeof o[key]) {
if (varType == "number") {
if (typeof o[key] == "string") {
o[key] = +o[key];
}
}
else if (varType == "string") {
if (typeof o[key] == "number") {
o[key] = o[key]? o[key].toString() : "";
}
}
}
let values = vars[key].values;
if (values && typeof values == "string") {
values = vars[values].values;
}
if (values && !Array.isArray(values)) {
let value = values[o[key]];
if (value !== undefined) {
o[key] = value;
if (changes >= 0) changes++;
}
else if (strict) {
if (vars[key].type != "number" || o[key]) {
if (strict) warning("code '%s' for key '%s' has no value\n", o[key], key);
changes = -1;
}
}
}
}
else if (Array.isArray(o[key])) {
for (let j = 0; j < o[key].length; j++) {
let n = mapValues(o[key][j], vars, strict);
if (n < 0) {
changes = -1;
} else {
changes += n;
}
}
}
else if (strict) {
warning("variable '%s' missing\n", key);
changes = -1;
}
}
return changes;
}
/**
* removeValues(a, values)
*
* @param {Array} a
* @param {Array} values
*/
function removeValues(a, values)
{
values.forEach((value) => {
let i = a.indexOf(value);
if (i >= 0) {
a.splice(i, 1);
}
});
}
/**
* binaryInsert(a, v, compare, fUnique)
*
* If element v already exists in array a AND fUnique is true, the array is unchanged (no duplicates);
* otherwise, the element is inserted into the array at the appropriate index.
*
* @param {Array} a
* @param {*} v (value to insert)
* @param {function(*,*} [compare]
* @param {boolean} [fUnique]
* @return {number}
*/
function binaryInsert(a, v, compare, fUnique=false)
{
let i = binarySearch(a, v, compare);
if (i < 0) {
i = -(i + 1);
} else if (fUnique) {
i = -1;
}
if (i >= 0) {
a.splice(i, 0, v);
}
return i;
}
/**
* binarySearch(a, v, compare)
*
* @param {Array} a
* @param {*} v
* @param {function(*,*} [compare]
* @return {number} the (positive) index of matching entry, or the (negative) index + 1 of the insertion point
*/
function binarySearch(a, v, compare)
{
let found = 0;
let left = 0, right = a.length;
if (compare === undefined) {
compare = function(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
};
}
while (left < right) {
let middle = (left + right) >> 1;
let compareResult;
compareResult = compare(v, a[middle]);
if (compareResult > 0) {
left = middle + 1;
} else {
right = middle;
found = !compareResult;
}
}
return found ? left : ~left;
}
/**
* cloneObject(obj)
*
* @param {object} obj
* @param {object}
*/
function cloneObject(obj)
{
let newObj = {};
let keys = Object.keys(obj);
keys.forEach((key) => {
newObj[key] = obj[key];
});
return newObj;
}
/**
* compareObjects(index, key, keyValue, oldObj, newObj, indent)
*
* @param {number} index
* @param {string} key
* @param {*} keyValue
* @param {object} oldObj
* @param {object} newObj
* @param {number} [indent]
* @return {boolean}
*/
function compareObjects(index, key, keyValue, oldObj, newObj, indent=0)
{
let success = true;
let iOld = 0, iNew = 0;
let oldKeys = Object.keys(oldObj);
let newKeys = Object.keys(newObj);
while (iOld < oldKeys.length && iNew < newKeys.length) {
if (oldKeys[iOld] != newKeys[iNew]) {
iOld++;
continue;
}
let keyProp = oldKeys[iOld];
let oldProp = oldObj[keyProp];
let newProp = newObj[keyProp];
if (typeof oldProp == typeof newProp) {
if (typeof oldProp == "object") {
compareObjects(iOld, key, keyValue, oldProp, newProp, indent+2);
} else if (oldProp != newProp) {
if (!oldObj.caseNotes || oldObj.caseNotes.indexOf(keyProp) < 0) {
warning("%*sindex %d %s '%s' property '%s': \"%s\" != \"%s\"\n", indent, ' ', index, key, keyValue, keyProp, oldProp, newProp);
success = false;
}
} else {
if (argv['detail']) {
printf("%*sindex %d %s '%s' property '%s': \"%s\" MATCHES \"%s\"\n", indent, ' ', index, key, keyValue, keyProp, oldProp, newProp);
}
}
}
iOld++;
iNew++;
}
return success;
}
/**
* compareObjectArrays(oldObjs, newObjs, key)
*
* @param {Array} oldObjs
* @param {Array} newObjs
* @param {string} [key]
* @return {boolean}
*/
function compareObjectArrays(oldObjs, newObjs, key)
{
let success = true;
let iOld = 0, iNew = 0;
while (iOld < oldObjs.length && iNew < newObjs.length) {
let keyValue;
if (key) {
if (oldObjs[iOld][key] < newObjs[iNew][key]) {
iOld++;
continue;
}
if (newObjs[iNew][key] < oldObjs[iOld][key]) {
iNew++;
continue;
}
keyValue = oldObjs[iOld][key];
}
if (!compareObjects(iOld, key, keyValue, oldObjs[iOld], newObjs[iNew])) {
success = false;
}
iOld++;
iNew++;
}
return success;
}
/**
* insertSortedArray(a, v)
*
* @param {Array} a
* @param {*} v
* @return {number}
*/
function insertSortedArray(a, v)
{
return binaryInsert(a, v);
}
/**
* insertSortedObject(rows, row, keys, fUnique)
*
* @param {Array.<object>} rows
* @param {object} row
* @param {Array.<string>} keys
* @param {boolean} [fUnique]
* @return {number}
*/
function insertSortedObject(rows, row, keys, fUnique)
{
let compare = function(row1, row2) {
for (let k = 0; k < keys.length; k++) {
let key = keys[k];
if (row1[key] > row2[key]) return 1;
if (row1[key] < row2[key]) return -1;
if (k == keys.length - 1) return 0;
}
};
return binaryInsert(rows, row, compare, fUnique);
}
/**
* isSortedArray(a, fQuiet)
*
* @param {Array} a
* @param {boolean} [fQuiet]
* @return {boolean}
*/
function isSortedArray(a, fQuiet)
{
let isSorted = true;
for (let i = 1; i < a.length; i++) {
let v1 = a[i-1], v2 = a[i];
if (v1 < v2) break;
if (v1 == v2) continue;
isSorted = false;
if (fQuiet) {
i = a.length;
break;
}
warning("element %d (%s) > element %d (%s)\n", i-1, v1, i, v2);
}
return isSorted;
}
/**
* isSortedObjects(rows, keys, fQuiet)
*
* @param {Array.<object>} rows
* @param {Array.<string>} keys
* @param {boolean} [fQuiet]
* @return {boolean}
*/
function isSortedObjects(rows, keys, fQuiet)
{
let isSorted = true;
for (let i = 1; i < rows.length; i++) {
let row1 = rows[i-1], row2 = rows[i];
for (let k = 0; k < keys.length; k++) {
let key = keys[k];
if (row1[key] < row2[key]) break;
if (row1[key] == row2[key]) continue;
isSorted = false;
if (fQuiet) {
i = rows.length;
break;
}
warning("row %d '%s' (%s) > row %d '%s' (%s)\n", i-1, key, row1[key], i, key, row2[key]);
}
}
return isSorted;
}
/**
* searchObjects(rows, row, next, fSub)
*
* fSub can now be an array of keys (eg, ['identifier']) to restrict the search to a subset of keys.
*
* @param {Array.<object>} rows
* @param {object} row
* @param {number} [next]
* @param {boolean|Array} [fSub] (true to perform substring comparisons; default is equality checks)
* @return {number} (index of position, or -1 if not found)
*/
function searchObjects(rows, row, next=0, fSub=false)
{
let i, keys;
if (Array.isArray(fSub)) {
keys = fSub;
fSub = false;
} else {
keys = Object.keys(row);
}
for (i = next; i < rows.length; i++) {
let k;
for (k = 0; k < keys.length; k++) {
let key = keys[k];
if (fSub && rows[i][key].indexOf(row[key]) < 0 || !fSub && rows[i][key] != row[key]) {
break;
}
}
if (k == keys.length) {
break;
}
}
return (i < rows.length)? i : -1;
}
/**
* searchSortedObjects(rows, row, rowScore, fDisplay)
*
* If rowScore is set, then if there are multiple matches, the row that scores best against
* rowScore will be returned. If you just want the first match, regardless whether there are
* multiple matches or not, specify null (the default). And if you only want unique matches,
* pass {}.
*
* @param {Array.<object>} rows
* @param {object} row
* @param {object} [rowScore]
* @param {boolean} [fDisplay]
* @return {number}
*/
function searchSortedObjects(rows, row, rowScore=null, fDisplay=false)
{
let keys = Object.keys(row);
let compare = function(row1, row2) {
for (let k = 0; k < keys.length; k++) {
let key = keys[k];
let v1 = row1[key], v2 = row2[key];
// if (typeof v1 == "string" && v1.slice(-1) == '.') v1 = v1.slice(0, -1);
// if (typeof v2 == "string" && v2.slice(-1) == '.') v2 = v2.slice(0, -1);
if (v1 > v2) {
// printf("%s: %s > %s: 1\n", key, v1, v1);
return 1;
}
if (v1 < v2) {
// printf("%s: %s < %s: -1\n", key, v1, v2);
return -1;
}
if (k == keys.length - 1) {
// printf("%s: %s == %s: 0\n", key, v1, v2);
return 0;
}
}
};
if (fDisplay) printf("\n\tsearching for row with %s == %s\n", keys[0], row[keys[0]]);
let i = binarySearch(rows, row, compare);
while (i > 0) {
if (compare(rows[i], rows[i-1])) break;
i--;
}
if (rowScore && i >= 0) {
let iBest = i, scoreBest = 0;
let keys = Object.keys(rowScore);
if (!keys.length) {
if (i < rows.length - 1 && !compare(rows[i], rows[i+1])) {
iBest = -1;
}
return iBest;
}
let keyScore = keys[0];
if (fDisplay && keyScore) printf("\tmatched row %d: %s == %s (looking for %s)\n", iBest, keyScore, rows[iBest][keyScore], rowScore[keyScore]);
while (i < rows.length) {
if (compare(rows[i], rows[iBest])) break;
let score = scoreStrings(rows[i][keyScore], rowScore[keyScore]);
if (fDisplay) printf("\tcomparing row %d: %s = %s (%d)\n", i, keyScore, rows[i][keyScore], score);
if (scoreBest < score) {
scoreBest = score;
iBest = i;
}
i++;
}
i = scoreBest? iBest : -1;
if (fDisplay && keyScore) printf("\treturned row %d: %s == %s (%d)\n", i, keyScore, rows[iBest][keyScore], scoreBest);
}
return i;
}
/**
* sortObjects(rows, keys, order, clone)
*
* @param {Array.<object>} rows
* @param {Array.<string>} keys
* @param {number} [order] (default is 1, for ascending order; use -1 for descending order)
* @param {boolean} [clone]
* @return {Array.<object>}
*/
function sortObjects(rows, keys, order=1, clone=false)
{
if (clone) {
rows = rows.slice();
}
rows.sort(function(row1, row2) {
for (let k = 0; k < keys.length; k++) {
let key = keys[k];
let col1 = row1[key];
let col2 = row2[key];
if (key == "usCite-numerical") {
let cite1 = {}, cite2 = {};
key = "usCite";
col1 = row1[key];
col2 = row2[key];
parseCite(col1, cite1);
parseCite(col2, cite2);
col1 = sprintf("%04d U.S. %04d", cite1.volume || 999, cite1.page || 9999);
col2 = sprintf("%04d U.S. %04d", cite2.volume || 999, cite2.page || 9999);
}
if (col1 > col2) return order;
if (col1 < col2) return -order;
if (k == keys.length - 1) return 0;
}
});
return rows;
}
/**
* addCSV(text, obj, keys, pairs)
*
* @param {string} text
* @param {object} obj
* @param {Array.<string>} keys
* @param {Array} pairs
* @return {string}
*/
function addCSV(text, obj, keys, ...pairs)
{
if (!text) {
for (let i = 0; i < keys.length; i++) {
if (text) text += ',';
text += keys[i];
}
for (let i = 0; i < pairs.length; i += 2) {
if (text) text += ',';
text += pairs[i];
}
text += '\n';
}
let line = "";
for (let i = 0; i < keys.length; i++) {
let s = obj[keys[i]] || "";
if (typeof s == "string") s = '"' + he.decode(s).replace(/"/g, '""') + '"';
if (line) line += ',';
line += s;
}
for (let i = 0; i < pairs.length; i += 2) {
let s = pairs[i+1];
if (typeof s == "string") s = '"' + he.decode(s).replace(/"/g, '""') + '"';
if (line) line += ',';
line += s;
}
line += '\n';
if (text.indexOf(line) < 0) {
text += line;
}
return text;
}
/**
* parseCSV(text, encodeAs, maxRows, keyUnique, keySubset, saveUniqueKey, vars)
*
* By default, all CSV fields containing strings are returned as-is, unless encodeAs is "html", which triggers replacement
* with HTML entities where appropriate.
*
* @param {string} text
* @param {string} [encodeAs] (default is none; currently only "html" is supported)
* @param {number} [maxRows] (default is zero, implying no maximum; heading row is not counted toward the limit)
* @param {string} [keyUnique] (name of field, if any, that should be filtered; typically the key associated with the subset fields)
* @param {string} [keySubset] (name of first subset field, if any, containing data for unique subsets)
* @param {boolean} [saveUniqueKey] (default is false, to reduce space requirements)
* @param {object|null} [vars]
* @return {Array.<Object>}
*/
function parseCSV(text, encodeAs="", maxRows=0, keyUnique="", keySubset="", saveUniqueKey=false, vars=null)
{
let rows = [];
let headings, fields;
let lines = text.split(/\r?\n/);
let keyChildren = keySubset + 's';
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (!line) continue;
let row = {};
let fields = parseCSVFields(line, encodeAs, !headings);
if (!headings) {
headings = fields;
/**
* Make sure all headings are non-empty and unique.
*/
for (let h = 0; h < headings.length; h++) {
let heading = headings[h];
if (!heading || row[headings[h]] !== undefined) {
warning("CSV field heading %d (%s) is invalid or duplicate\n", h, heading);
heading = "field" + (h + 1);
}
row[heading] = h;
}
} else {
let fieldUnique = "";
let subset = null, hUnique = -1;
let matchedPrevious = !!rows.length;
for (let h = 0; h < headings.length; h++) {
let field = fields[h];
let heading = headings[h];
if (vars) {
if (!vars[heading]) {
// warning("%s field is an undefined type, defaulting to string\n", heading);
// vars[heading] = {type: "string", dump: true};
vars[heading] = {type: "string"};
}
let t = vars[heading];
if (field != "") {
if (t.dump) {
if (!t.values) t.values = [];
if (t.values.indexOf(field) < 0) t.values.push(field);
}
else {
let v = t.values;
if (v && typeof v == "string") {
v = vars[v].values;
}
if (v && (Array.isArray(v) && v.indexOf(field) < 0 || !Array.isArray(v) && v[field] === undefined) || !v && field == "NULL") {
if (argv['debug']) {
if (fieldUnique && fieldUnique != "NULL") {
warning("record %s field %s has unexpected value '%s'\n", fieldUnique, heading, field);
} else {
warning("CSV row %d field %s has unexpected value '%s'\n", i+1, heading, field);
}
}
}
}