-
Notifications
You must be signed in to change notification settings - Fork 1
/
sqlite3.m
6376 lines (6080 loc) · 269 KB
/
sqlite3.m
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
function [response_struct,cli_output]=sqlite3(db_or_opts,SQL_statement,input_struct)
%Matlab and Octave interface to the SQLite engine
%
% With SQLite you can access an SQL database, without the need of a server. This function is a
% wrapper for a command line interface and a mex interface. The mex files were compiled for most
% operating systems for Matlab. For Octave an internal function will download the source files and
% compile it, since the resulting mex files are less portable than Matlab mex files.
% Since this is a wrapper for different implementations, it is possible that more complex commands
% have inconsistent effects depending on whether the mex implementation was used or the CLI.
%
% The CLI is removed from this version, but may be back in a future update. If and when it is back,
% the CLI may have inconsistent effects across different operating systems. The test suite will
% only test basic functionality for the CLI.
%
% These are the supported data types: double, single, char, logical, and all integer data types
% (int/uint 8/16/32/64). All single variables are converted to double, and integer data types are
% converted to int64. Logical is converted to integer as well.
%
% Syntax:
% sqlite3(filename,SQL_statement)
% sqlite3(optionstruct,SQL_statement)
% sqlite3(___,input_struct)
% response_struct = sqlite3(___)
% [response_struct,cli_output] = sqlite3(___)
%
% Input/output arguments:
% response_struct:
% This is an Nx1 struct array, with each field name corresponding to the column name in the
% selected table. Other commands might result in different types of output. A very limited number
% of commands and syntax options has been tested.
% For CLI interactions, an attempt will be made to parse the returned output to a struct and to
% convert to an appropriate data type. For fields where this fails, the fields will be char
% arrays. The "PRAGMA table_info('table name')" command is used to parse the data types of
% output_struct for CLI calls.
% cli_output_string:
% This is a char vector containing the raw output returned by the system function.
% This variable defaults to an empty char array if not available.
% NB: the current version of this function does not support a CLI interaction, so this variable
% will always be an empty char. It is only here to avoid syntax errors for users updating this
% function.
% filename:
% The file name of the database file to be edited. Using a full or relative path is optional.
% optionstruct:
% A struct with the parameters. Any missing field will be filled from the defaults listed below.
% Using incomplete parameter names or incorrect capitalization is allowed, as long as there is a
% unique match.
% NB: with this syntax the filename must be included as a parameter.
% SQL_statement:
% A char vector containing a valid SQL statement. Please note that the validity of the SQL
% statement is mostly determined by the mex implementation used. There may be differences between
% implementations.
% input_struct:
% If the SQL statement contains placeholders, the values are filled from this parameter. This
% input argument must be a struct and the number of fields should match the number of
% placeholders.
% The number of unnamed parameters ('?') must be equal to the number of fields left after
% matching named (:NAME, @NAME, $NAME) or indexed (?NNN) parameters.
%
% Name,Value parameters:
% filename:
% Since the optionstruct replaces the filename, it has to be entered as an optional parameter.
% Not specifying this will result in an error.
% [default=error;]
% use_CLI:
% Use a system-installed command line interface. This will result in an error if no CLI is
% available. For this version of the function the CLI has been removed, so this will error if
% you set this flag to true. The CLI will probably be back in a future update.
% On prior versions on Windows an exe file was downloaded, while Linux assumed a system
% install. The complete statement was written to a file in the tempdir. There may be
% additional limitations compared to mex implementations. [default=false;]
% print_to_con:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% A logical that controls whether warnings and other output will be printed to the command
% window. Errors can't be turned off. [default=true;]
% Specifying print_to_fid, print_to_obj, or print_to_fcn will change the default to false,
% unless parsing of any of the other exception redirection options results in an error.
% print_to_fid:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% The file identifier where console output will be printed. Errors and warnings will be
% printed including the call stack. You can provide the fid for the command window (fid=1) to
% print warnings as text. Errors will be printed to the specified file before being actually
% thrown. [default=[];]
% If print_to_fid, print_to_obj, and print_to_fcn are all empty, this will have the effect of
% suppressing every output except errors.
% Array inputs are allowed.
% print_to_obj:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% The handle to an object with a String property, e.g. an edit field in a GUI where console
% output will be printed. Messages with newline characters (ignoring trailing newlines) will
% be returned as a cell array. This includes warnings and errors, which will be printed
% without the call stack. Errors will be written to the object before the error is actually
% thrown. [default=[];]
% If print_to_fid, print_to_obj, and print_to_fcn are all empty, this will have the effect of
% suppressing every output except errors.
% Array inputs are allowed.
% print_to_fcn:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% A struct with a function handle, anonymous function or inline function in the 'h' field and
% optionally additional data in the 'data' field. The function should accept three inputs: a
% char array (either 'warning' or 'error'), a struct with the message, id, and stack, and the
% optional additional data. The function(s) will be run before the error is actually thrown.
% [default=[];]
% If print_to_fid, print_to_obj, and print_to_fcn are all empty, this will have the effect of
% suppressing every output except errors.
% Array inputs are allowed.
% print_to_params:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% This struct contains the optional parameters for the error_ and warning_ functions.
% Each field can also be specified as ['print_to_option_' parameter_name]. This can be used to
% avoid nested struct definitions.
% ShowTraceInMessage:
% [default=false] Show the function trace in the message section. Unlike the normal results
% of rethrow/warning, this will not result in clickable links.
% WipeTraceForBuiltin:
% [default=false] Wipe the trace so the rethrow/warning only shows the error/warning message
% itself. Note that the wiped trace contains the calling line of code (along with the
% function name and line number), while the generated trace does not.
%
% The basis for the interface is the SQLite3 project itself. The sqlite3.c and sqlite3.h files
% can be downloaded from an archived zip file here:
% http://web.archive.org/web/202108id_/https://www.sqlite.org/2021/sqlite-amalgamation-3360000.zip
% The originals for sqlite3_interface.c, structlist.c, and structlist.h can be found on GitHub
% (https://github.com/rmartinjak/mex-sqlite3). These 3 files were edited to make them conform to
% the stricter standards of older compilers and to remove a message ('mexPrintf("binding params %d
% of %zu\n", i, mxGetM(params));'). The files were further edited to deal with column names that
% are not valid Matlab field names and to make sure the database file is closed whenever an error
% occurs.
% Additionally a converter file was written to deal with UTF-16 char encoding.
%
% Most error messages should be self-explanatory (or come from SQLite itself). However, there are
% two exceptions.
% Error code 20 (SQLITE_MISMATCH) is returned if the type checks fail. This means the input is not
% a supported data type (i.e. double, single, char, or int/uint 8/16/32/64).
% Error code 24 (SQLITE_FORMAT) is not used in SQLite itself, but is used by the wrapper.
%
%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%
%| |%
%| Version: 3.1.0 |%
%| Date: 2023-06-14 |%
%| Author: H.J. Wisselink |%
%| Licence: CC by-nc-sa 4.0 ( creativecommons.org/licenses/by-nc-sa/4.0 ) |%
%| Email = 'h_j_wisselink*alumnus_utwente_nl'; |%
%| Real_email = regexprep(Email,{'*','_'},{'@','.'}) |%
%| |%
%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%
%
% Tested on several versions of Matlab (ML 6.5 and onward) and Octave (4.4.1 and onward), and on
% multiple operating systems (Windows/Ubuntu/MacOS). You can see the full test matrix below.
% Compatibility considerations:
% - This is expected to work on most releases. Forward compatibility of Matlab mex files is
% (generally) excellent, but backward compatibility is often an issue. If you use an
% OS/realease-combination for which the current binaries don't work, you're welcome to send me a
% compiled mex file by email, so I can add it to a future update.
%
% /=========================================================================================\
% || | Windows | Linux | MacOS ||
% ||---------------------------------------------------------------------------------------||
% || Matlab R2023a | W10: Pass | Ubuntu 22.04: Pass | Monterey: Pass ||
% || Matlab R2022b | W10: Pass | Ubuntu 22.04: Pass | Monterey: Pass ||
% || Matlab R2022a | W10: Pass | | ||
% || Matlab R2021b | W10: Pass | Ubuntu 22.04: Pass | Monterey: Pass ||
% || Matlab R2021a | W10: Pass | | ||
% || Matlab R2020b | W10: Pass | Ubuntu 22.04: Pass | Monterey: Pass ||
% || Matlab R2020a | W10: Pass | | ||
% || Matlab R2019b | W10: Pass | Ubuntu 22.04: Pass | Monterey: Pass ||
% || Matlab R2019a | W10: Pass | | ||
% || Matlab R2018a | W10: Pass | Ubuntu 22.04: Pass | ||
% || Matlab R2017b | W10: Pass | Ubuntu 22.04: Pass | Monterey: Pass ||
% || Matlab R2016b | W10: Pass | Ubuntu 22.04: Pass | Monterey: Pass ||
% || Matlab R2015a | W10: Pass | Ubuntu 22.04: Pass | ||
% || Matlab R2013b | W10: Pass | | ||
% || Matlab R2012a | | Ubuntu 22.04: Pass | ||
% || Matlab R2007b | W10: Pass | | ||
% || Matlab 7.1 (R14SP3) | XP: Pass | | ||
% || Matlab 6.5 (R13) | W10: Pass | | ||
% || Octave 8.2.0 | W10: Pass | | ||
% || Octave 7.2.0 | W10: Pass | | ||
% || Octave 6.2.0 | W10: Pass | Raspbian 11: Pass | Catalina: Pass ||
% || Octave 5.2.0 | W10: Pass | | ||
% || Octave 4.4.1 | W10: Pass | | Catalina: Pass ||
% \=========================================================================================/
% Verify number of input arguments.
if nargout>=2
cli_output = ''; % Set default.
end
if nargin<2 || nargin>3
error('HJW:sqlite3:nargin','Incorrect number of input argument.')
end
if nargout>2
error('HJW:sqlite3:nargout','Incorrect number of output argument.')
end
% Linearize a struct array input so later rows are processed as well.
args = {db_or_opts,SQL_statement};if nargin>=3,args{end+1} = reshape(input_struct,1,[]);end
[success,opts,ME] = sqlite3_parse_inputs(args{:});
if ~success
error_(opts.print_to,ME)
else
print_to = opts.print_to;
if nargin==3
[invalid,opts.input_struct] = CheckDatatype(opts.input_struct);
if invalid
error_(print_to,'Unsupported datatype.')
end
args = {opts.filename,opts.SQL_statement,opts.input_struct};
else
args = {opts.filename,opts.SQL_statement};
end
end
% Determine the function call type.
persistent fun_handle
if isempty(fun_handle) || opts.DEBUG_delete_mex
% Store the handle to the correct mex file in a persistent variable.
% Octave requires a compile specific to at least the release and architecture, so it will be
% compiled from the source files. If any files need to be downloaded, this will require
% internet access.
fun_handle = get_sqlite3_mex(print_to,opts.DEBUG_delete_mex);
end
% Actually call the mex implementation.
n_arg_out = nargout;
for tries=1:2
try ME = []; %#ok<NASGU>
c = cell(1,2*double(logical(n_arg_out)));
[c{:}] = feval(fun_handle,args{:});
if n_arg_out>0,response_struct = c{1};SQLiteFieldnames = c{2};end
break
catch ME;if isempty(ME),ME = lasterror;end %#ok<LERR>
if strcmp(ME.identifier,'MATLAB:assigningResultsIntoInitializedEmptyLHS')
% If the only ouput argument is 'ans', c being 1x0 causes an error. Retry with nargout
% set to 1. Any other exception should trigger an error.
n_arg_out = 1;
continue
end
error_(print_to,ME)
end
end
% A normal clear would wipe the persistent.
if n_arg_out==0 ,return,end
if ~isa(response_struct,'struct'),return,end
% The mex interface seems to allow invalid field names. This generates valid field names and copies
% the data from the raw output to the actual output struct.
% This should probably be done inside the mex implementation, but I already had the code in Matlab.
% If you want to translate the code to C, feel free to send the code.
raw_output = response_struct;N = numel(response_struct);response_struct = struct;
for n=1:numel(SQLiteFieldnames)
% First parse the field names as stored in the database.
if ~CharIsUTF8,SQLiteFieldnames{n} = unicode_to_char(UTF8_to_unicode(SQLiteFieldnames{n}));end
SQLiteFieldnames{n} = CreateValidFieldName(...
SQLiteFieldnames{n} ,...
SQLiteFieldnames(1:(n-1)) );
% Now rename the field.
[response_struct(1:N).(SQLiteFieldnames{n})] = deal(raw_output.(sprintf('field_%d',n)));
end
% On runtimes where chars are encoded as UTF-16, text is returned as uint8. That means any text
% should be re-encoded. While it is technically possible to do this inside the mex implementation,
% the code to do so seems to have a bug. Any help in fixing this/these bug/bugs is welcome.
if ~CharIsUTF8
fields = fieldnames(response_struct);
for n=1:numel(fields)
for m=1:numel(response_struct)
x = response_struct(m).(fields{n});
if ~isa(x,'uint8'),continue,end
% Attempt to convert to UTF-16. If the content is not valid UTF-8, this will not
% trigger an error, but return the content as uint8. This should not happen.
[U,tf] = UTF8_to_unicode(x);
if tf,response_struct(m).(fields{n}) = unicode_to_char(U);end
end
end
end
end
function [invalid,input_struct]=CheckDatatype(input_struct)
% Check if the input variables are all of an allowed datatype.
invalid = false;
if numel(input_struct)>1
% Unwind, which allows inconsistent types per field (as SQLite does).
for n=1:numel(input_struct)
[invalid,input_struct(n)] = CheckDatatype(input_struct(n));
if invalid,return,end
end
return
end
fields = fieldnames(input_struct);
for n=1:numel(fields)
data = input_struct.(fields{n});
switch class(data)
case {'logical','int8','uint8'}
% Convert logical, int8, and uint8 to int64.
input_struct.(fields{n}) = int64(data);
case {'double','single','char','int16','int32','int64','uint16','uint32','uint64'}
% Do nothing, this is valid.
otherwise
% Unsupported type; throw error.
invalid = true;return
end
end
end
function out=bsxfun_plus(in1,in2)
%Implicit expansion for plus(), but without any input validation.
persistent type
if isempty(type)
type = ...
double(hasFeature('ImplicitExpansion')) + ...
double(hasFeature('bsxfun'));
end
if type==2
% Implicit expansion is available.
out = in1+in2;
elseif type==1
% Implicit expansion is only available with bsxfun.
out = bsxfun(@plus,in1,in2);
else
% No implicit expansion, expand explicitly.
sz1 = size(in1);
sz2 = size(in2);
if min([sz1 sz2])==0
% Construct an empty array of the correct size.
sz1(sz1==0) = inf;sz2(sz2==0) = inf;
sz = max(sz1,sz2);
sz(isinf(sz)) = 0;
% Create an array and cast it to the correct type.
out = feval(str2func(class(in1)),zeros(sz));
return
end
in1 = repmat(in1,max(1,sz2./sz1));
in2 = repmat(in2,max(1,sz1./sz2));
out = in1+in2;
end
end
function c=char2cellstr(str,LineEnding)
% Split char or uint32 vector to cell (1 cell element per line). Default splits are for CRLF/CR/LF.
% The input data type is preserved.
%
% Since the largest valid Unicode codepoint is 0x10FFFF (i.e. 21 bits), all values will fit in an
% int32 as well. This is used internally to deal with different newline conventions.
%
% The second input is a cellstr containing patterns that will be considered as newline encodings.
% This will not be checked for any overlap and will be processed sequentially.
returnChar = isa(str,'char');
str = int32(str); % Convert to signed, this should not crop any valid Unicode codepoints.
if nargin<2
% Replace CRLF, CR, and LF with -10 (in that order). That makes sure that all valid encodings
% of newlines are replaced with the same value. This should even handle most cases of files
% that mix the different styles, even though such mixing should never occur in a properly
% encoded file. This considers LFCR as two line endings.
if any(str==13)
str = PatternReplace(str,int32([13 10]),int32(-10));
str(str==13) = -10;
end
str(str==10) = -10;
else
for n=1:numel(LineEnding)
str = PatternReplace(str,int32(LineEnding{n}),int32(-10));
end
end
% Split over newlines.
newlineidx = [0 find(str==-10) numel(str)+1];
c=cell(numel(newlineidx)-1,1);
for n=1:numel(c)
s1 = (newlineidx(n )+1);
s2 = (newlineidx(n+1)-1);
c{n} = str(s1:s2);
end
% Return to the original data type.
if returnChar
for n=1:numel(c),c{n} = char(c{n});end
else
for n=1:numel(c),c{n} = uint32(c{n});end
end
end
function tf=CharIsUTF8
% This provides a single place to determine if the runtime uses UTF-8 or UTF-16 to encode chars.
% The advantage is that there is only 1 function that needs to change if and when Octave switches
% to UTF-16. This is unlikely, but not impossible.
persistent persistent_tf
if isempty(persistent_tf)
if ifversion('<',0,'Octave','>',0)
% Test if Octave has switched to UTF-16 by looking if the Euro symbol is losslessly encoded
% with char.
% Because we will immediately reset it, setting the state for all warnings to off is fine.
w = struct('w',warning('off','all'));[w.msg,w.ID] = lastwarn;
persistent_tf = ~isequal(8364,double(char(8364)));
warning(w.w);lastwarn(w.msg,w.ID); % Reset warning state.
else
persistent_tf = false;
end
end
tf = persistent_tf;
end
function date_correct=check_date(outfilename,opts,SaveAttempt)
%Check if the date of the downloaded file matches the requested date.
%
% There are two strategies. Strategy 1 is guaranteed to be correct, but isn't always possible.
% Strategy 2 could give an incorrect answer, but is possible in more situations. In the case of
% non-web page files (like e.g. an image), both will fail. This will trigger a missing date error,
% for which you need to input a missing date response (m_date_r).
%
% Strategy 1:
% Rely on the html for the header to provide the date of the currently viewed capture.
% Strategy 2:
% Try a much less clean version: don't rely on the top bar, but look for links that indicate a link
% to the same date in the Wayback Machine. The most common occurring date will be compared with
% date_part.
if ~exist(outfilename,'file')
date_correct = false;return
% If the file doesn't exist (not even as a 0 byte file), evidently something went wrong, so
% retrying or alerting the user is warranted.
end
[m_date_r,date_bounds,print_to] = deal(opts.m_date_r,opts.date_bounds,opts.print_to);
% Loading an unsaved page may result in a capture of the live page (but no save in the WBM). If
% this happens the time in the file will be very close to the current time if this is the case. If
% the save was actually triggered this is valid, but if this is the result of a load attempt, it is
% unlikely this is correct, in which case it is best to trigger the response to an incorrect date:
% attempt an explicit save. Save the time here so any time taken up by file reading and processing
% doesn't bias the estimation of whether or not this is too recent.
if ~SaveAttempt
currentTime = WBM_getUTC_local;
end
% Strategy 1:
% Rely on the html for the header to provide the date of the currently viewed capture.
StringToMatch = '<input type="hidden" name="date" value="';
data = readfile(outfilename);
% A call to ismember would be faster, but it can result in a memory error in ML6.5. The
% undocumented ismembc function only allows numeric, logical, or char inputs (and Octave lacks it),
% so we can't use that on our cellstr either. That is why we need the while loop here.
pos = 0;
while pos<=numel(data) && (pos==0 || ~strcmp(stringtrim(data{pos}),'<td class="u" colspan="2">'))
% This is equivalent to pos=find(ismember(data,'<td class="u" colspan="2">'));
pos = pos+1;
end
if numel(data)>=(pos+1)
line = data{pos+1};
idx = strfind(line,StringToMatch);
idx = idx+length(StringToMatch)-1;
date_as_double = str2double(line(idx+(1:14)));
date_correct = date_bounds.double(1)<=date_as_double && date_as_double<=date_bounds.double(2);
return
end
% Strategy 2:
% Try a much less clean version: don't rely on the top bar, but look for links that indicate a link
% to the same date in the Wayback Machine. The most common occurring date will be compared with
% date_part.
% The file was already loaded with data=readfile(outfilename);
data = data(:)';data = cell2mat(data);
% The data variable is now a single long string.
idx = strfind(data,'/web/');
if numel(idx)==0
if m_date_r==0 % Ignore.
date_correct = true;
return
elseif m_date_r==1 % Warning.
warning_(print_to,'HJW:WBM:MissingDateWarning',...
'No date found in file, unable to check date, assuming it is correct.')
date_correct = true;
return
elseif m_date_r==2 % Error.
error_(print_to,'HJW:WBM:MissingDateError',...
['Could not find date. This can mean there is an ',...
'error in the save. Try saving manually.'])
end
end
datelist = zeros(size(idx));
data = [data 'abcdefghijklmnopqrstuvwxyz']; % Avoid error in the loop below.
if exist('isstrprop','builtin')
for n=1:length(idx)
for m=1:14
if ~isstrprop(data(idx(n)+4+m),'digit')
break
end
end
datelist(n) = str2double(data(idx(n)+4+(1:m)));
end
else
for n=1:length(idx)
for m=1:14
if ~any(double(data(idx(n)+4+m))==(48:57))
break
end
end
datelist(n) = str2double(data(idx(n)+4+(1:m)));
end
end
[a,ignore_output,c] = unique(datelist);%#ok<ASGLU> ~
% In some future release, histc might not be supported anymore.
try
[ignore_output,c2] = max(histc(c,1:max(c)));%#ok<HISTC,ASGLU>
catch
[ignore_output,c2] = max(accumarray(c,1)); %#ok<ASGLU>
end
date_as_double=a(c2);
date_correct = date_bounds.double(1)<=date_as_double && date_as_double<=date_bounds.double(2);
if ~SaveAttempt
% Check if the time in the file is too close to the current time to be an actual loaded
% capture. Setting this too high will result in too many save triggers, but setting it too low
% will lead to captures being missed on slower systems/networks. 15 seconds seems a reasonable
% middle ground.
% One extreme situation to be aware of: it is possible for a save to be triggered, the request
% arrives successfully and the page is saved, but the response from the server is wrong or
% missing, triggering an HTTP error. This may then lead to a load attempt. Now we have the
% situation where there is a save of only several seconds old, but the the SaveAttempt flag is
% false. The time chosen here must be short enough to account for this situation.
% Barring such extreme circumstances, page ages below a minute are suspect.
if date_as_double<1e4 % Something is wrong.
% Trigger missing date response. This shouldn't happen, so offer a graceful exit.
if m_date_r==0 % Ignore.
date_correct = true;
return
elseif m_date_r==1 % Warning.
warning_(print_to,'HJW:WBM:MissingDateWarning',...
'No date found in file, unable to check date, assuming it is correct.')
date_correct = true;
return
elseif m_date_r==2 % Error.
error_(print_to,'HJW:WBM:MissingDateError',...
['Could not find date. This can mean there is an error in the save.',...
char(10),'Try saving manually.']) %#ok<CHARTEN>
end
end
% Convert the date found to a format that the ML6.5 datenum supports.
line = sprintf('%014d',date_as_double);
line = {...
line(1:4 ),line( 5:6 ),line( 7:8 ),... %date
line(9:10),line(11:12),line(13:14)}; %time
line = str2double(line);
timediff = (currentTime-datenum(line))*24*60*60; %#ok<DATNM>
if timediff<10 % This is in seconds.
date_correct = false;
elseif timediff<60% This is in seconds.
warning_(print_to,'HJW:WBM:LivePageStored',...
['The live page might have been saved instead of a capture.',char(10),...
'Check on the WBM if a capture exists.']) %#ok<CHARTEN>
end
end
end
function outfilename=check_filename(filename,outfilename)
% It can sometimes happen that the outfilename provided by urlwrite is incorrect. Therefore, we
% need to check if either the outfilename file exists, or the same file, but inside the current
% directory. It is unclear when this would happen, but it might be that this only happens when the
% filename provided only contains a name, and not a full or relative path.
outfilename2 = [pwd filesep filename];
if ~strcmp(outfilename,outfilename2) && ~exist(outfilename,'file') && exist(outfilename2,'file')
outfilename = outfilename2;
end
end
function [tf,ME]=CheckMexCompilerExistence
% Returns true if a mex compiler is expected to be installed.
% The method used for R2008a and later is fairly slow, so the flag is stored in a file. Run
% ClearMexCompilerExistenceFlag() to reset this test.
%
% This function may result in false positives (e.g. by detecting an installed compiler that doesn't
% work, or if a compiler is required for a specific language).
% False negatives should be rare.
%
% Based on: http://web.archive.org/web/2/http://www.mathworks.com/matlabcentral/answers/99389
% (this link will redirect to the URL with the full title)
%
% The actual test will be performed in a separate function. That way the same persistent can be
% used for different functions containing this check as a subfunction.
persistent tf_ ME_
if isempty(tf_)
% In some release-runtime combinations addpath has a permanent effect, in others it doesn't. By
% putting this code in this block, we are trying to keep these queries to a minimum.
[p,ME] = CreatePathFolder__CheckMexCompilerExistence_persistent;
if ~isempty(ME),tf = false;return,end
fn = fullfile(p,'ClearMexCompilerExistenceFlag.m');
txt = {...
'function ClearMexCompilerExistenceFlag',...
'fn = create_fn;',...
'if exist(fn,''file''),delete(fn),end',...
'end',...
'function fn = create_fn',...
'v = version;v = v(regexp(v,''[a-zA-Z0-9()\.]''));',...
'if ~exist(''OCTAVE_VERSION'', ''builtin'')',...
' runtime = ''MATLAB'';',...
' type = computer;',...
'else',...
' runtime = ''OCTAVE'';',...
' arch = computer;arch = arch(1:(min(strfind(arch,''-''))-1));',...
' if ispc',...
' if strcmp(arch,''x86_64'') ,type = ''win_64'';',...
' elseif strcmp(arch,''i686''),type = ''win_i686'';',...
' elseif strcmp(arch,''x86'') ,type = ''win_x86'';',...
' else ,type = [''win_'' arch];',...
' end',...
' elseif isunix && ~ismac % Essentially this is islinux',...
' if strcmp(arch,''i686'') ,type = ''lnx_i686'';',...
' elseif strcmp(arch,''x86_64''),type = ''lnx_64'';',...
' else ,type = [''lnx_'' arch];',...
' end',...
' elseif ismac',...
' if strcmp(arch,''x86_64''),type = ''mac_64'';',...
' else ,type = [''mac_'' arch];',...
' end',...
' end',...
'end',...
'type = strrep(strrep(type,''.'',''''),''-'','''');',...
'flag = [''flag_'' runtime ''_'' v ''_'' type ''.txt''];',...
'fn = fullfile(fileparts(mfilename(''fullpath'')),flag);',...
'end',...
''};
fid = fopen(fn,'wt');fprintf(fid,'%s\n',txt{:});fclose(fid);
[tf_,ME_] = CheckMexCompilerExistence_persistent(p);
end
tf = tf_;ME = ME_;
end
function [tf,ME]=CheckMexCompilerExistence_persistent(p)
% Returns true if a mex compiler is expected to be installed.
% The method used for R2008a and later is fairly slow, so the flag is stored in a file. Run
% ClearMexCompilerExistenceFlag() to reset this test.
%
% This function may result in false positives (e.g. by detecting an installed compiler that doesn't
% work, or if a compiler is required for a specific language). False negatives should be rare.
%
% Based on: http://web.archive.org/web/2/http://www.mathworks.com/matlabcentral/answers/99389
% (this link will redirect to the URL with the full title)
persistent tf_ ME_
if isempty(tf_)
ME_ = create_ME;
fn = create_fn(p);
if exist(fn,'file')
str = fileread(fn);
tf_ = strcmp(str,'compiler found');
else
% Use evalc to suppress anything printed to the command window.
[txt,tf_] = evalc(func2str(@get_tf)); %#ok<ASGLU>
fid = fopen(fn,'w');
if tf_,fprintf(fid,'compiler found');
else , fprintf(fid,'compiler not found');end
fclose(fid);
end
end
tf = tf_;ME = ME_;
end
function fn=create_fn(p)
v = version;v = v(regexp(v,'[a-zA-Z0-9()\.]'));
if ~exist('OCTAVE_VERSION', 'builtin')
runtime = 'MATLAB';
type = computer;
else
runtime = 'OCTAVE';
arch = computer;arch = arch(1:(min(strfind(arch,'-'))-1));
if ispc
if strcmp(arch,'x86_64') ,type = 'win_64';
elseif strcmp(arch,'i686'),type = 'win_i686';
elseif strcmp(arch,'x86') ,type = 'win_x86';
else ,type = ['win_' arch];
end
elseif isunix && ~ismac % Essentially this is islinux.
if strcmp(arch,'i686') ,type = 'lnx_i686';
elseif strcmp(arch,'x86_64'),type = 'lnx_64';
else ,type = ['lnx_' arch];
end
elseif ismac
if strcmp(arch,'x86_64'),type = 'mac_64';
else ,type = ['mac_' arch];
end
end
end
type = strrep(strrep(type,'.',''),'-','');
flag = ['flag_' runtime '_' v '_' type '.txt'];
fn = fullfile(p,flag);
end
function ME_=create_ME
msg = {...
'No selected compiler was found.',...
'Please make sure a supported compiler is installed and set up.',...
'Run mex(''-setup'') for version-specific documentation.',...
'',...
'Run ClearMexCompilerExistenceFlag() to reset this test.'};
msg = sprintf('\n%s',msg{:});msg = msg(2:end);
ME_ = struct(...
'identifier','HJW:CheckMexCompilerExistence:NoCompiler',...
'message',msg);
end
function tf=get_tf
[isOctave,v_num] = ver_info;
if isOctave
% Octave normally comes with a compiler out of the box, but for some methods of installation an
% additional package may be required.
tf = ~isempty(try_file_compile);
elseif v_num>=706 % ifversion('>=','R2008a')
% Just try to compile a MWE. Getting the configuration is very slow. On Windows this is a bad
% idea, as it starts an interactive prompt. Because this function is called with evalc, that
% means this function will hang.
if ispc, TryNormalCheck = true;
else,[cc,TryNormalCheck] = try_file_compile;
end
if TryNormalCheck
% Something strange happened, so try the normal check anyway.
try cc = mex.getCompilerConfigurations;catch,cc=[];end
end
tf = ~isempty(cc);
else
if ispc,ext = '.bat';else,ext = '.sh';end
tf = exist(fullfile(prefdir,['mexopts' ext]),'file');
end
end
function [isOctave,v_num]=ver_info
% This is a compact and feature-poor equivalent of ifversion.
% To save space this can be used as an alternative.
% Example: R2018a is 9.4, so v_num will be 904.
isOctave = exist('OCTAVE_VERSION', 'builtin');
v_num = version;
ii = strfind(v_num,'.');if numel(ii)~=1,v_num(ii(2):end) = '';ii = ii(1);end
v_num = [str2double(v_num(1:(ii-1))) str2double(v_num((ii+1):end))];
v_num = v_num(1)+v_num(2)/100;v_num = round(100*v_num);
end
function [cc,TryNormalCheck]=try_file_compile
TryNormalCheck = false;
try
[p,n] = fileparts(tempname);e='.c';
n = n(regexp(n,'[a-zA-Z0-9_]')); % Keep only valid characters.
n = ['test_fun__' n(1:min(15,end))];
fid = fopen(fullfile(p,[n e]),'w');
fprintf(fid,'%s\n',...
'#include "mex.h"',...
'void mexFunction(int nlhs, mxArray *plhs[],',...
' int nrhs, const mxArray *prhs[]) {',...
' plhs[0]=mxCreateString("compiler works");',...
' return;',...
'}');
fclose(fid);
catch
% If there is a write error in the temp dir, something is wrong.
% Just try the normal check.
cc = [];TryNormalCheck = true;return
end
try
current = cd(p);
catch
% If the cd fails, something is wrong here. Just try the normal check.
cc = [];TryNormalCheck = true;return
end
try
mex([n e]);
cc = feval(str2func(n));
clear(n); % Clear to remove file lock.
cd(current);
catch
% Either the mex or the feval failed. That means we can safely assume no working compiler is
% present. The normal check should not be required.
cd(current);
cc = [];TryNormalCheck = false;return
end
end
function str=convert_from_codepage(str,inverted)
% Convert from the Windows-1252 codepage.
persistent or ta
if isempty(or)
% This list is complete for all characters (up to 0xFFFF) that can be encoded with ANSI.
CPwin2UTF8 = [338 140;339 156;352 138;353 154;376 159;381 142;382 158;402 131;710 136;732 152;
8211 150;8212 151;8216 145;8217 146;8218 130;8220 147;8221 148;8222 132;8224 134;8225 135;
8226 149;8230 133;8240 137;8249 139;8250 155;8364 128;8482 153];
or = CPwin2UTF8(:,2);ta = CPwin2UTF8(:,1);
end
if nargin>1 && inverted
origin = ta;target = or;
else
origin = or;target = ta;
end
str = uint32(str);
for m=1:numel(origin)
str = PatternReplace(str,origin(m),target(m));
end
end
function [p,ME]=CreatePathFolder__CheckMexCompilerExistence_persistent
% Try creating a folder in either the tempdir or a persistent folder and try adding it to the path
% (if it is not already in there). If the folder is not writable, the current folder will be used.
try
ME = [];
p = fullfile(GetWritableFolder,'FileExchange','CheckMexCompilerExistence');
if isempty(strfind([path ';'],[p ';'])) %#ok<STREMP>
% This means f is not on the path.
if ~exist(p,'dir'),makedir(p);end
addpath(p,'-end');
end
catch
ME = struct('identifier','HJW:CheckMexCompilerExistence:PathFolderFail',...
'message','Creating a folder on the path to store the compiled function and flag failed.');
end
end
function p=CreatePathFolder__sqlite3(print_to)
% Try creating a folder in either the tempdir or a persistent folder and try adding it to the path
% (if it is not already in there). If the folder is not writable, the current folder will be used.
try
p = fullfile(GetWritableFolder,'FileExchange','sqlite3');
if isempty(strfind([path ';'],[p ';'])) %#ok<STREMP>
% This means f is not on the path.
if ~exist(p,'dir'),makedir(p);end
addpath(p,'-end');
end
catch
error_(print_to,'HJW:sqlite3:PathFolderFail',...
'Creating a folder on the path to store compiled mex files failed.')
end
end
function fn=CreateValidFieldName(fn,PreviousFieldNames)
% Create valid field names based on a char input and the already assigned field names.
% This function is modelled after matlab.lang.makeValidName.
% Only edit the base name if it doesn't match the regular expression.
[ind1,ind2] = regexp(fn,'[A-Za-z][A-Za-z0-9_]*');
if ~( numel(ind1)==1 && ind1==1 && ind2==numel(fn) )
fn = CreateValidFieldName_helper(fn);
end
% Check if a counter is needed.
if nargin==2
fn_ = fn;counter = 0;
while ismember(fn,PreviousFieldNames)
counter = counter+1;fn = sprintf('%s_%d',fn_,counter);
end
end
end
function fn=CreateValidFieldName_helper(fn)
persistent RE dyn_expr
if isempty(RE)
ws = char([9 10 11 12 13 32]);
RE = ['[' ws ']+([^' ws '])'];
% Dynamically check if the dynamic expression replacement is available. This is possible since
% R2006a (v7.2), and has not been implemented yet in Octave 7.
dyn_expr = strcmp('fooBar',regexprep('foo bar',RE,'${upper($1)}'));
end
if dyn_expr
fn = regexprep(fn,RE,'${upper($1)}'); % Convert characters after whitespace to upper case.
else
[s,e] = regexp(fn,RE);
if ~isempty(s)
fn(e) = upper(fn(e));
L = zeros(size(fn));L(s)=1;L(e)=-1;L=logical(cumsum(L));
fn(L) = '';
end
end
fn = regexprep(fn,'\s',''); % Remove all remaining whitespace.
x = find(double(fn)==0);if ~isempty(x),fn(x(1):end)='';end % Gobble null characters.
fn = regexprep(fn,'[^0-9a-zA-Z_]','_'); % Replace remaining invalid characters.
if isempty(fn)||any(fn(1)=='_0123456789')
fn = ['x' fn];
end
% If the name exceeds 63 characters, crop the trailing characters.
fn((namelengthmax+1):end) = '';
end
function error_(options,varargin)
%Print an error to the command window, a file and/or the String property of an object.
% The error will first be written to the file and object before being actually thrown.
%
% Apart from controlling the way an error is written, you can also run a specific function. The
% 'fcn' field of the options must be a struct (scalar or array) with two fields: 'h' with a
% function handle, and 'data' with arbitrary data passed as third input. These functions will be
% run with 'error' as first input. The second input is a struct with identifier, message, and stack
% as fields. This function will be run with feval (meaning the function handles can be replaced
% with inline functions or anonymous functions).
%
% The intention is to allow replacement of every error(___) call with error_(options,___).
%
% NB: the function trace that is written to a file or object may differ from the trace displayed by
% calling the builtin error/warning functions (especially when evaluating code sections). The
% calling code will not be included in the constructed trace.
%
% There are two ways to specify the input options. The shorthand struct described below can be used
% for fast repeated calls, while the input described below allows an input that is easier to read.
% Shorthand struct:
% options.boolean.IsValidated: if true, validation is skipped
% options.params: optional parameters for error_ and warning_, as explained below
% options.boolean.con: only relevant for warning_, ignored
% options.fid: file identifier for fprintf (array input will be indexed)
% options.boolean.fid: if true print error to file
% options.obj: handle to object with String property (array input will be indexed)
% options.boolean.obj: if true print error to object (options.obj)
% options.fcn struct (array input will be indexed)
% options.fcn.h: handle of function to be run
% options.fcn.data: data passed as third input to function to be run (optional)
% options.boolean.fnc: if true the function(s) will be run
%
% Full input description:
% print_to_con:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% A logical that controls whether warnings and other output will be printed to the command
% window. Errors can't be turned off. [default=true;]
% Specifying print_to_fid, print_to_obj, or print_to_fcn will change the default to false,
% unless parsing of any of the other exception redirection options results in an error.
% print_to_fid:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% The file identifier where console output will be printed. Errors and warnings will be
% printed including the call stack. You can provide the fid for the command window (fid=1) to
% print warnings as text. Errors will be printed to the specified file before being actually
% thrown. [default=[];]
% If print_to_fid, print_to_obj, and print_to_fcn are all empty, this will have the effect of
% suppressing every output except errors.
% Array inputs are allowed.
% print_to_obj:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% The handle to an object with a String property, e.g. an edit field in a GUI where console
% output will be printed. Messages with newline characters (ignoring trailing newlines) will
% be returned as a cell array. This includes warnings and errors, which will be printed
% without the call stack. Errors will be written to the object before the error is actually
% thrown. [default=[];]
% If print_to_fid, print_to_obj, and print_to_fcn are all empty, this will have the effect of
% suppressing every output except errors.
% Array inputs are allowed.
% print_to_fcn:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% A struct with a function handle, anonymous function or inline function in the 'h' field and
% optionally additional data in the 'data' field. The function should accept three inputs: a
% char array (either 'warning' or 'error'), a struct with the message, id, and stack, and the
% optional additional data. The function(s) will be run before the error is actually thrown.
% [default=[];]
% If print_to_fid, print_to_obj, and print_to_fcn are all empty, this will have the effect of
% suppressing every output except errors.
% Array inputs are allowed.
% print_to_params:
% NB: An attempt is made to use this parameter for warnings or errors during input parsing.
% This struct contains the optional parameters for the error_ and warning_ functions.
% Each field can also be specified as ['print_to_option_' parameter_name]. This can be used to
% avoid nested struct definitions.
% ShowTraceInMessage:
% [default=false] Show the function trace in the message section. Unlike the normal results
% of rethrow/warning, this will not result in clickable links.
% WipeTraceForBuiltin:
% [default=false] Wipe the trace so the rethrow/warning only shows the error/warning message
% itself. Note that the wiped trace contains the calling line of code (along with the
% function name and line number), while the generated trace does not.
%
% Syntax:
% error_(options,msg)
% error_(options,msg,A1,...,An)
% error_(options,id,msg)
% error_(options,id,msg,A1,...,An)
% error_(options,ME) %equivalent to rethrow(ME)
%
% Examples options struct:
% % Write to a log file:
% opts = struct;opts.fid = fopen('log.txt','wt');
% % Display to a status window and bypass the command window:
% opts = struct;opts.boolean.con = false;opts.obj = uicontrol_object_handle;
% % Write to 2 log files:
% opts = struct;opts.fid = [fopen('log2.txt','wt') fopen('log.txt','wt')];
persistent this_fun
if isempty(this_fun),this_fun = func2str(@error_);end
% Parse options struct, allowing an empty input to revert to default.
if isempty(options),options = struct;end
options = parse_warning_error_redirect_options( options );
[id,msg,stack,trace,no_op] = parse_warning_error_redirect_inputs( varargin{:});
if no_op,return,end
forced_trace = trace;
if options.params.ShowTraceInMessage
msg = sprintf('%s\n%s',msg,trace);
end
ME = struct('identifier',id,'message',msg,'stack',stack);
if options.params.WipeTraceForBuiltin
ME.stack = stack('name','','file','','line',[]);
end
% Print to object.
if options.boolean.obj
msg_ = msg;while msg_(end)==10,msg_(end) = '';end % Crop trailing newline.
if any(msg_==10) % Parse to cellstr and prepend 'Error: '.
msg_ = char2cellstr(['Error: ' msg_]);
else % Only prepend 'Error: '.
msg_ = ['Error: ' msg_];
end
for OBJ=reshape(options.obj,1,[])
try set(OBJ,'String',msg_);catch,end
end
end
% Print to file.
if options.boolean.fid
T = datestr(now,31); %#ok<DATST,TNOW1> Print the time of the error to the log as well.
for FID=reshape(options.fid,1,[])
try fprintf(FID,'[%s] Error: %s\n%s',T,msg,trace);catch,end
end
end
% Run function.
if options.boolean.fcn
if ismember(this_fun,{stack.name})