-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrev.lua
2563 lines (2443 loc) · 97.2 KB
/
rev.lua
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
--[[
_______ ______ _______ __ _ ______ _______ _______ ___ _______ __ __ ___ __ __ _______
| || _ | | || | | || | | || _ || | | || | | || | | | | || |
|_ _|| | || | ___|| |_| || _ | | || |_| || | | || | | || | | | | || _____|
| | | |_||_ | |___ | || | | | | || || | | || |_| || | | |_| || |_____
| | | __ || ___|| _ || |_| | | _|| || |___ | _|| || |___ | ||_____ |
| | | | | || |___ | | | || | | |_ | _ || || |_ | || || | _____| |
|___| |___| |_||_______||_| |__||______| |_______||__| |__||_______||_______||_______||_______||_______||_______|
Trend Calculus: Reversal and Trend Statistics Generator
Copyright 2014, 2015, ByteSumo Limited (Andrew J Morgan)
Author: Andrew J Morgan
Notes: No unauthorised use or distribution of this code what so ever.
License: GPLv3
This file is part of TrendCalculus.
TrendCalculus is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TrendCalculus is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with TrendCalculus. If not, see <http://www.gnu.org/licenses/>.
Revisions::
2015-04-16
Created a program that quickly generates reversals from FHLS -s data.
2015-05-13
Added in feature to output trend period measures in a genomic format good for circos
2015-06-07
Embedded the dependent library code into this program to reduce external dependencies. date, csv, pl.lapp
Updated license information.
2015-06-10
Embedded pl.sip as this was needed by pl.lapp. Listed embedded libraries.
Embedded Libraries::
pl.lapp -- part of the Penlight package for Lua.
Copyright (C) 2009 Steve Donovan, David Manura.
https://github.com/stevedonovan/Penlight/blob/master/LICENSE.md
https://github.com/stevedonovan/Penlight
csv-1.1 -- the csv parsing library for lua.
Copyright (c) 2013-2014 Incremental IP Limited
Copyright (c) 2014 Kevin Martin
https://github.com/geoffleyland/lua-csv/blob/master/LICENSE
https://github.com/geoffleyland/lua-csv
date -- Date and Time string parsing; Time addition and subtraction; Time span calculation; Supports ISO 8601 Dates.
Copyright (c) 2013-2014 Thijs Schreijer
https://github.com/Tieske/date/blob/master/LICENSE
http://tieske.github.io/date/
--]]
local whohow = [[
---------------------------------------------------------------------------------
| |
|--\ /-|-.-. .
|__/\/ | \/_ . :.
___/ _ _ _ __ ___/ . .
/ ._|| | | || \/ \ / \ . : .:
\_ \| |_| || | | || [ ] | ..
\___/|____/||_|_|_| \___/ ..
/ . .. .:
.: . .:
TrendCalculus: Reversal and Trend Statistics Generator
Copyright 2014-2015, ByteSumo Limited (Andrew J Morgan)
License: GPLv3
Author: Andrew J Morgan
Version: 1.0.0
Usage:
> cat tst.csv | lua trendcalculus.lua -F "," -h -H -s -n 5 | lua rev.lua -h -H -p 1 -s
> lua trendcalculus.lua -F "," -h -H -s -n 5 -f tst.csv | lua rev.lua
Options
-v --version Show version and help
-F (string default ",") input record delimeter
-OFS (string default ",") output record delimeter
-h --header indicates there is a column header row
-H --outheader indicate if you want an output header record
-p --pass user value, pass num over the data, with -r option
-s --stats enhanced output with trend statistics
-g --geneout output genomic formatted trend outputs for circos (not available yet)
<file> (default stdin) input file to process
note:
(1)
on a mac commandline, to set OFS to tab delimited
you need to use OFS = "ctrl-v<tab>" to get round tab expansion
(2)
Do not set the filename to accept stdin streams
(3)
Data Input Format:
-- this assumes data is created by FHLS using the options: -s -H
(4)
This program when it gets column headers on inputs. A column alias feature internally
helps handle names flexibly. if needed you can edit this source to add new column aliases
if needed to simplify your data processing pipeline.
(5)
the -s option delivers richer stats about the trends. The extra columns delivers mean the following:
"opendate" -- the trend's open date, preceding the current reversal date found
"open" -- the trend's open value, preceeding the current reversal value found
"diff" -- the absolute difference in value, from open to close
"relrtrn" -- the relative return of the trend (close - open) / open
"d_days" -- the difference in days from trend open to close
"RatioToPrev" -- the ratio of this trend's absolute value change, against that of the one before it (of opposite direction)
"RatioToPPrev" -- the ratio of this trend's absolute value change, against that before the previous one
(compares trends of same direction, included as it is commonly thought to be a fib ratio)
References:
https://bitbucket.org/bytesumo/trendcalculus-public
https://github.com/geoffleyland/lua-csv
https://github.com/stevedonovan/Penlight
http://tieske.github.io/date/
---------------------------------------------------------------------------------
]]
--- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX START OF EMBEDDED LIBRARY CODE. pl.lapp, csv, date. XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
package.preload[ "pl.sip" ] = assert( (loadstring or load)(
"--- Simple Input Patterns (SIP).\
-- SIP patterns start with '$', then a\
-- one-letter type, and then an optional variable in curly braces.\
--\
-- sip.match('$v=$q','name=\"dolly\"',res)\
-- ==> res=={'name','dolly'}\
-- sip.match('($q{first},$q{second})','(\"john\",\"smith\")',res)\
-- ==> res=={second='smith',first='john'}\
--\
-- ''Type names''\
--\
-- v identifier\
-- i integer\
-- f floating-point\
-- q quoted string\
-- ([{< match up to closing bracket\
--\
-- See @{08-additional.md.Simple_Input_Patterns|the Guide}\
--\
-- @module pl.sip\
\
local loadstring = rawget(_G,'loadstring') or load\
local unpack = rawget(_G,'unpack') or rawget(table,'unpack')\
\
local append,concat = table.insert,table.concat\
local ipairs,loadstring,type,unpack = ipairs,loadstring,type,unpack\
local io,_G = io,_G\
local print,rawget = print,rawget\
\
local patterns = {\
FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*',\
INTEGER = '[+%-%d]%d*',\
IDEN = '[%a_][%w_]*',\
FILE = '[%a%.\\\\][:%][%w%._%-\\\\]*',\
OPTION = '[%a_][%w_%-]*',\
}\
\
local function assert_arg(idx,val,tp)\
if type(val) ~= tp then\
error(\"argument \"..idx..\" must be \"..tp, 2)\
end\
end\
\
\
--[[\
module ('pl.sip',utils._module)\
]]\
\
local sip = {}\
\
local brackets = {['<'] = '>', ['('] = ')', ['{'] = '}', ['['] = ']' }\
local stdclasses = {a=1,c=0,d=1,l=1,p=0,u=1,w=1,x=1,s=0}\
\
local _patterns = {}\
\
\
local function group(s)\
return '('..s..')'\
end\
\
-- escape all magic characters except $, which has special meaning\
-- Also, un-escape any characters after $, so $( passes through as is.\
local function escape (spec)\
--_G.print('spec',spec)\
local res = spec:gsub('[%-%.%+%[%]%(%)%^%%%?%*]','%%%1'):gsub('%$%%(%S)','$%1')\
--_G.print('res',res)\
return res\
end\
\
local function imcompressible (s)\
return s:gsub('%s+','\\001')\
end\
\
-- [handling of spaces in patterns]\
-- spaces may be 'compressed' (i.e will match zero or more spaces)\
-- unless this occurs within a number or an identifier. So we mark\
-- the four possible imcompressible patterns first and then replace.\
-- The possible alnum patterns are v,f,a,d,x,l and u.\
local function compress_spaces (s)\
s = s:gsub('%$[vifadxlu]%s+%$[vfadxlu]',imcompressible)\
s = s:gsub('[%w_]%s+[%w_]',imcompressible)\
s = s:gsub('[%w_]%s+%$[vfadxlu]',imcompressible)\
s = s:gsub('%$[vfadxlu]%s+[%w_]',imcompressible)\
s = s:gsub('%s+','%%s*')\
s = s:gsub('\\001',' ')\
return s\
end\
\
local pattern_map = {\
v = group(patterns.IDEN),\
i = group(patterns.INTEGER),\
f = group(patterns.FLOAT),\
o = group(patterns.OPTION),\
r = '(%S.*)',\
p = '([%a]?[:]?[\\\\/%.%w_]+)'\
}\
\
function sip.custom_pattern(flag,patt)\
pattern_map[flag] = patt\
end\
\
--- convert a SIP pattern into the equivalent Lua string pattern.\
-- @param spec a SIP pattern\
-- @param options a table; only the <code>at_start</code> field is\
-- currently meaningful and esures that the pattern is anchored\
-- at the start of the string.\
-- @return a Lua string pattern.\
function sip.create_pattern (spec,options)\
assert_arg(1,spec,'string')\
local fieldnames,fieldtypes = {},{}\
\
if type(spec) == 'string' then\
spec = escape(spec)\
else\
local res = {}\
for i,s in ipairs(spec) do\
res[i] = escape(s)\
end\
spec = concat(res,'.-')\
end\
\
local kount = 1\
\
local function addfield (name,type)\
if not name then name = kount end\
if fieldnames then append(fieldnames,name) end\
if fieldtypes then fieldtypes[name] = type end\
kount = kount + 1\
end\
\
local named_vars, pattern\
named_vars = spec:find('{%a+}')\
pattern = '%$%S'\
\
if options and options.at_start then\
spec = '^'..spec\
end\
if spec:sub(-1,-1) == '$' then\
spec = spec:sub(1,-2)..'$r'\
if named_vars then spec = spec..'{rest}' end\
end\
\
\
local names\
\
if named_vars then\
names = {}\
spec = spec:gsub('{(%a+)}',function(name)\
append(names,name)\
return ''\
end)\
end\
spec = compress_spaces(spec)\
\
local k = 1\
local err\
local r = (spec:gsub(pattern,function(s)\
local type,name\
type = s:sub(2,2)\
if names then name = names[k]; k=k+1 end\
-- this kludge is necessary because %q generates two matches, and\
-- we want to ignore the first. Not a problem for named captures.\
if not names and type == 'q' then\
addfield(nil,'Q')\
else\
addfield(name,type)\
end\
local res\
if pattern_map[type] then\
res = pattern_map[type]\
elseif type == 'q' then\
-- some Lua pattern matching voodoo; we want to match '...' as\
-- well as \"...\", and can use the fact that %n will match a\
-- previous capture. Adding the extra field above comes from needing\
-- to accomodate the extra spurious match (which is either ' or \")\
addfield(name,type)\
res = '([\"\\'])(.-)%'..(kount-2)\
else\
local endbracket = brackets[type]\
if endbracket then\
res = '(%b'..type..endbracket..')'\
elseif stdclasses[type] or stdclasses[type:lower()] then\
res = '(%'..type..'+)'\
else\
err = \"unknown format type or character class\"\
end\
end\
return res\
end))\
--print(r,err)\
if err then\
return nil,err\
else\
return r,fieldnames,fieldtypes\
end\
end\
\
\
local function tnumber (s)\
return s == 'd' or s == 'i' or s == 'f'\
end\
\
function sip.create_spec_fun(spec,options)\
local fieldtypes,fieldnames\
local ls = {}\
spec,fieldnames,fieldtypes = sip.create_pattern(spec,options)\
if not spec then return spec,fieldnames end\
local named_vars = type(fieldnames[1]) == 'string'\
for i = 1,#fieldnames do\
append(ls,'mm'..i)\
end\
local fun = ('return (function(s,res)\\n\\tlocal %s = s:match(%q)\\n'):format(concat(ls,','),spec)\
fun = fun..'\\tif not mm1 then return false end\\n'\
local k=1\
for i,f in ipairs(fieldnames) do\
if f ~= '_' then\
local var = 'mm'..i\
if tnumber(fieldtypes[f]) then\
var = 'tonumber('..var..')'\
elseif brackets[fieldtypes[f]] then\
var = var..':sub(2,-2)'\
end\
if named_vars then\
fun = ('%s\\tres.%s = %s\\n'):format(fun,f,var)\
else\
if fieldtypes[f] ~= 'Q' then -- we skip the string-delim capture\
fun = ('%s\\tres[%d] = %s\\n'):format(fun,k,var)\
k = k + 1\
end\
end\
end\
end\
return fun..'\\treturn true\\nend)\\n', named_vars\
end\
\
--- convert a SIP pattern into a matching function.\
-- The returned function takes two arguments, the line and an empty table.\
-- If the line matched the pattern, then this function return true\
-- and the table is filled with field-value pairs.\
-- @param spec a SIP pattern\
-- @param options optional table; {anywhere=true} will stop pattern anchoring at start\
-- @return a function if successful, or nil,<error>\
function sip.compile(spec,options)\
assert_arg(1,spec,'string')\
local fun,names = sip.create_spec_fun(spec,options)\
if not fun then return nil,names end\
if rawget(_G,'_DEBUG') then print(fun) end\
local chunk,err = loadstring(fun,'tmp')\
if err then return nil,err end\
return chunk(),names\
end\
\
local cache = {}\
\
--- match a SIP pattern against a string.\
-- @param spec a SIP pattern\
-- @param line a string\
-- @param res a table to receive values\
-- @param options (optional) option table\
-- @return true or false\
function sip.match (spec,line,res,options)\
assert_arg(1,spec,'string')\
assert_arg(2,line,'string')\
assert_arg(3,res,'table')\
if not cache[spec] then\
cache[spec] = sip.compile(spec,options)\
end\
return cache[spec](line,res)\
end\
\
--- match a SIP pattern against the start of a string.\
-- @param spec a SIP pattern\
-- @param line a string\
-- @param res a table to receive values\
-- @return true or false\
function sip.match_at_start (spec,line,res)\
return sip.match(spec,line,res,{at_start=true})\
end\
\
--- given a pattern and a file object, return an iterator over the results\
-- @param spec a SIP pattern\
-- @param f a file - use standard input if not specified.\
function sip.fields (spec,f)\
assert_arg(1,spec,'string')\
f = f or io.stdin\
local fun,err = sip.compile(spec)\
if not fun then return nil,err end\
local res = {}\
return function()\
while true do\
local line = f:read()\
if not line then return end\
if fun(line,res) then\
local values = res\
res = {}\
return unpack(values)\
end\
end\
end\
end\
\
--- register a match which will be used in the read function.\
-- @string spec a SIP pattern\
-- @func fun a function to be called with the results of the match\
-- @see read\
function sip.pattern (spec,fun)\
assert_arg(1,spec,'string')\
local pat,named = sip.compile(spec)\
append(_patterns,{pat=pat,named=named,callback=fun or false})\
end\
\
--- enter a loop which applies all registered matches to the input file.\
-- @param f a file object; if nil, then io.stdin is assumed.\
function sip.read (f)\
local owned,err\
f = f or io.stdin\
if type(f) == 'string' then\
f,err = io.open(f)\
if not f then return nil,err end\
owned = true\
end\
local res = {}\
for line in f:lines() do\
for _,item in ipairs(_patterns) do\
if item.pat(line,res) then\
if item.callback then\
if item.named then\
item.callback(res)\
else\
item.callback(unpack(res))\
end\
end\
res = {}\
break\
end\
end\
end\
if owned then f:close() end\
end\
\
return sip\
"
, '@'.."/Users/andrewmorgan/torch/install/share/lua/5.1/pl/sip.lua" ) )
package.preload[ "date" ] = assert( (loadstring or load)(
"---------------------------------------------------------------------------------------\
-- Module for date and time calculations\
--\
-- Version 2.1.1\
-- Copyright (C) 2006, by Jas Latrix ([email protected])\
-- Copyright (C) 2013-2014, by Thijs Schreijer\
-- Licensed under MIT, http://opensource.org/licenses/MIT\
\
--[[ CONSTANTS ]]--\
local HOURPERDAY = 24\
local MINPERHOUR = 60\
local MINPERDAY = 1440 -- 24*60\
local SECPERMIN = 60\
local SECPERHOUR = 3600 -- 60*60\
local SECPERDAY = 86400 -- 24*60*60\
local TICKSPERSEC = 1000000\
local TICKSPERDAY = 86400000000\
local TICKSPERHOUR = 3600000000\
local TICKSPERMIN = 60000000\
local DAYNUM_MAX = 365242500 -- Sat Jan 01 1000000 00:00:00\
local DAYNUM_MIN = -365242500 -- Mon Jan 01 1000000 BCE 00:00:00\
local DAYNUM_DEF = 0 -- Mon Jan 01 0001 00:00:00\
local _;\
--[[ LOCAL ARE FASTER ]]--\
local type = type\
local pairs = pairs\
local error = error\
local assert = assert\
local tonumber = tonumber\
local tostring = tostring\
local string = string\
local math = math\
local os = os\
local unpack = unpack or table.unpack\
local pack = table.pack or function(...) return { n = select('#', ...), ... } end\
local setmetatable = setmetatable\
local getmetatable = getmetatable\
--[[ EXTRA FUNCTIONS ]]--\
local fmt = string.format\
local lwr = string.lower\
local upr = string.upper\
local rep = string.rep\
local len = string.len\
local sub = string.sub\
local gsub = string.gsub\
local gmatch = string.gmatch or string.gfind\
local find = string.find\
local ostime = os.time\
local osdate = os.date\
local floor = math.floor\
local ceil = math.ceil\
local abs = math.abs\
-- removes the decimal part of a number\
local function fix(n) n = tonumber(n) return n and ((n > 0 and floor or ceil)(n)) end\
-- returns the modulo n % d;\
local function mod(n,d) return n - d*floor(n/d) end\
-- rounds a number;\
local function round(n, d) d=d^10 return floor((n*d)+.5)/d end\
-- rounds a number to whole;\
local function whole(n)return floor(n+.5)end\
-- is `str` in string list `tbl`, `ml` is the minimun len\
local function inlist(str, tbl, ml, tn)\
local sl = len(str)\
if sl < (ml or 0) then return nil end\
str = lwr(str)\
for k, v in pairs(tbl) do\
if str == lwr(sub(v, 1, sl)) then\
if tn then tn[0] = k end\
return k\
end\
end\
end\
local function fnil() end\
local function fret(x)return x;end\
--[[ DATE FUNCTIONS ]]--\
local DATE_EPOCH -- to be set later\
local sl_weekdays = {\
[0]=\"Sunday\",[1]=\"Monday\",[2]=\"Tuesday\",[3]=\"Wednesday\",[4]=\"Thursday\",[5]=\"Friday\",[6]=\"Saturday\",\
[7]=\"Sun\",[8]=\"Mon\",[9]=\"Tue\",[10]=\"Wed\",[11]=\"Thu\",[12]=\"Fri\",[13]=\"Sat\",\
}\
local sl_meridian = {[-1]=\"AM\", [1]=\"PM\"}\
local sl_months = {\
[00]=\"January\", [01]=\"February\", [02]=\"March\",\
[03]=\"April\", [04]=\"May\", [05]=\"June\",\
[06]=\"July\", [07]=\"August\", [08]=\"September\",\
[09]=\"October\", [10]=\"November\", [11]=\"December\",\
[12]=\"Jan\", [13]=\"Feb\", [14]=\"Mar\",\
[15]=\"Apr\", [16]=\"May\", [17]=\"Jun\",\
[18]=\"Jul\", [19]=\"Aug\", [20]=\"Sep\",\
[21]=\"Oct\", [22]=\"Nov\", [23]=\"Dec\",\
}\
-- added the '.2' to avoid collision, use `fix` to remove\
local sl_timezone = {\
[000]=\"utc\", [0.2]=\"gmt\",\
[300]=\"est\", [240]=\"edt\",\
[360]=\"cst\", [300.2]=\"cdt\",\
[420]=\"mst\", [360.2]=\"mdt\",\
[480]=\"pst\", [420.2]=\"pdt\",\
}\
-- set the day fraction resolution\
local function setticks(t)\
TICKSPERSEC = t;\
TICKSPERDAY = SECPERDAY*TICKSPERSEC\
TICKSPERHOUR= SECPERHOUR*TICKSPERSEC\
TICKSPERMIN = SECPERMIN*TICKSPERSEC\
end\
-- is year y leap year?\
local function isleapyear(y) -- y must be int!\
return (mod(y, 4) == 0 and (mod(y, 100) ~= 0 or mod(y, 400) == 0))\
end\
-- day since year 0\
local function dayfromyear(y) -- y must be int!\
return 365*y + floor(y/4) - floor(y/100) + floor(y/400)\
end\
-- day number from date, month is zero base\
local function makedaynum(y, m, d)\
local mm = mod(mod(m,12) + 10, 12)\
return dayfromyear(y + floor(m/12) - floor(mm/10)) + floor((mm*306 + 5)/10) + d - 307\
--local yy = y + floor(m/12) - floor(mm/10)\
--return dayfromyear(yy) + floor((mm*306 + 5)/10) + (d - 1)\
end\
-- date from day number, month is zero base\
local function breakdaynum(g)\
local g = g + 306\
local y = floor((10000*g + 14780)/3652425)\
local d = g - dayfromyear(y)\
if d < 0 then y = y - 1; d = g - dayfromyear(y) end\
local mi = floor((100*d + 52)/3060)\
return (floor((mi + 2)/12) + y), mod(mi + 2,12), (d - floor((mi*306 + 5)/10) + 1)\
end\
--[[ for floats or int32 Lua Number data type\
local function breakdaynum2(g)\
local g, n = g + 306;\
local n400 = floor(g/DI400Y);n = mod(g,DI400Y);\
local n100 = floor(n/DI100Y);n = mod(n,DI100Y);\
local n004 = floor(n/DI4Y); n = mod(n,DI4Y);\
local n001 = floor(n/365); n = mod(n,365);\
local y = (n400*400) + (n100*100) + (n004*4) + n001 - ((n001 == 4 or n100 == 4) and 1 or 0)\
local d = g - dayfromyear(y)\
local mi = floor((100*d + 52)/3060)\
return (floor((mi + 2)/12) + y), mod(mi + 2,12), (d - floor((mi*306 + 5)/10) + 1) \
end\
]] \
-- day fraction from time\
local function makedayfrc(h,r,s,t)\
return ((h*60 + r)*60 + s)*TICKSPERSEC + t\
end\
-- time from day fraction\
local function breakdayfrc(df)\
return\
mod(floor(df/TICKSPERHOUR),HOURPERDAY),\
mod(floor(df/TICKSPERMIN ),MINPERHOUR),\
mod(floor(df/TICKSPERSEC ),SECPERMIN),\
mod(df,TICKSPERSEC)\
end\
-- weekday sunday = 0, monday = 1 ...\
local function weekday(dn) return mod(dn + 1, 7) end\
-- yearday 0 based ...\
local function yearday(dn)\
return dn - dayfromyear((breakdaynum(dn))-1)\
end\
-- parse v as a month\
local function getmontharg(v)\
local m = tonumber(v);\
return (m and fix(m - 1)) or inlist(tostring(v) or \"\", sl_months, 2)\
end\
-- get daynum of isoweek one of year y\
local function isow1(y)\
local f = makedaynum(y, 0, 4) -- get the date for the 4-Jan of year `y`\
local d = weekday(f)\
d = d == 0 and 7 or d -- get the ISO day number, 1 == Monday, 7 == Sunday\
return f + (1 - d)\
end\
local function isowy(dn)\
local w1;\
local y = (breakdaynum(dn))\
if dn >= makedaynum(y, 11, 29) then\
w1 = isow1(y + 1);\
if dn < w1 then\
w1 = isow1(y);\
else\
y = y + 1;\
end\
else\
w1 = isow1(y);\
if dn < w1 then\
w1 = isow1(y-1)\
y = y - 1\
end\
end\
return floor((dn-w1)/7)+1, y\
end\
local function isoy(dn)\
local y = (breakdaynum(dn))\
return y + (((dn >= makedaynum(y, 11, 29)) and (dn >= isow1(y + 1))) and 1 or (dn < isow1(y) and -1 or 0))\
end\
local function makedaynum_isoywd(y,w,d)\
return isow1(y) + 7*w + d - 8 -- simplified: isow1(y) + ((w-1)*7) + (d-1)\
end\
--[[ THE DATE MODULE ]]--\
local fmtstr = \"%x %X\";\
--#if not DATE_OBJECT_AFX then\
local date = {}\
setmetatable(date, date)\
-- Version: VMMMRRRR; V-Major, M-Minor, R-Revision; e.g. 5.45.321 == 50450321\
date.version = 20010001 -- 2.1.1\
--#end -- not DATE_OBJECT_AFX\
--[[ THE DATE OBJECT ]]--\
local dobj = {}\
dobj.__index = dobj\
dobj.__metatable = dobj\
-- shout invalid arg\
local function date_error_arg() return error(\"invalid argument(s)\",0) end\
-- create new date object\
local function date_new(dn, df)\
return setmetatable({daynum=dn, dayfrc=df}, dobj)\
end\
-- is `v` a date object?\
local function date_isdobj(v)\
return (type(v) == 'table' and getmetatable(v) == dobj) and v\
end\
\
--#if not NO_LOCAL_TIME_SUPPORT then\
-- magic year table\
local date_epoch, yt;\
local function getequivyear(y)\
assert(not yt)\
yt = {}\
local de, dw, dy = date_epoch:copy()\
for i = 0, 3000 do\
de:setyear(de:getyear() + 1, 1, 1)\
dy = de:getyear()\
dw = de:getweekday() * (isleapyear(dy) and -1 or 1)\
if not yt[dw] then yt[dw] = dy end --print(de)\
if yt[1] and yt[2] and yt[3] and yt[4] and yt[5] and yt[6] and yt[7] and yt[-1] and yt[-2] and yt[-3] and yt[-4] and yt[-5] and yt[-6] and yt[-7] then\
getequivyear = function(y) return yt[ (weekday(makedaynum(y, 0, 1)) + 1) * (isleapyear(y) and -1 or 1) ] end\
return getequivyear(y)\
end\
end\
end\
-- TimeValue from daynum and dayfrc\
local function dvtotv(dn, df)\
return fix(dn - DATE_EPOCH) * SECPERDAY + (df/1000)\
end\
-- TimeValue from date and time\
local function totv(y,m,d,h,r,s)\
return (makedaynum(y, m, d) - DATE_EPOCH) * SECPERDAY + ((h*60 + r)*60 + s)\
end\
-- TimeValue from TimeTable\
local function tmtotv(tm)\
return tm and totv(tm.year, tm.month - 1, tm.day, tm.hour, tm.min, tm.sec)\
end\
-- Returns the bias in seconds of utc time daynum and dayfrc\
local function getbiasutc2(self)\
local y,m,d = breakdaynum(self.daynum)\
local h,r,s = breakdayfrc(self.dayfrc)\
local tvu = totv(y,m,d,h,r,s) -- get the utc TimeValue of date and time\
local tml = osdate(\"*t\", tvu) -- get the local TimeTable of tvu\
if (not tml) or (tml.year > (y+1) or tml.year < (y-1)) then -- failed try the magic\
y = getequivyear(y)\
tvu = totv(y,m,d,h,r,s)\
tml = osdate(\"*t\", tvu)\
end\
local tvl = tmtotv(tml)\
if tvu and tvl then\
return tvu - tvl, tvu, tvl\
else\
return error(\"failed to get bias from utc time\")\
end\
end\
-- Returns the bias in seconds of local time daynum and dayfrc\
local function getbiasloc2(daynum, dayfrc)\
local tvu\
-- extract date and time\
local y,m,d = breakdaynum(daynum)\
local h,r,s = breakdayfrc(dayfrc)\
-- get equivalent TimeTable\
local tml = {year=y, month=m+1, day=d, hour=h, min=r, sec=s}\
-- get equivalent TimeValue\
local tvl = tmtotv(tml)\
\
local function chkutc()\
tml.isdst = nil; local tvug = ostime(tml) if tvug and (tvl == tmtotv(osdate(\"*t\", tvug))) then tvu = tvug return end\
tml.isdst = true; local tvud = ostime(tml) if tvud and (tvl == tmtotv(osdate(\"*t\", tvud))) then tvu = tvud return end\
tvu = tvud or tvug\
end\
chkutc()\
if not tvu then\
tml.year = getequivyear(y)\
tvl = tmtotv(tml)\
chkutc()\
end\
return ((tvu and tvl) and (tvu - tvl)) or error(\"failed to get bias from local time\"), tvu, tvl\
end\
--#end -- not NO_LOCAL_TIME_SUPPORT\
\
--#if not DATE_OBJECT_AFX then\
-- the date parser\
local strwalker = {} -- ^Lua regular expression is not as powerful as Perl$\
strwalker.__index = strwalker\
local function newstrwalker(s)return setmetatable({s=s, i=1, e=1, c=len(s)}, strwalker) end\
function strwalker:aimchr() return \"\\n\" .. self.s .. \"\\n\" .. rep(\".\",self.e-1) .. \"^\" end\
function strwalker:finish() return self.i > self.c end\
function strwalker:back() self.i = self.e return self end\
function strwalker:restart() self.i, self.e = 1, 1 return self end\
function strwalker:match(s) return (find(self.s, s, self.i)) end\
function strwalker:__call(s, f)-- print(\"strwalker:__call \"..s..self:aimchr())\
local is, ie; is, ie, self[1], self[2], self[3], self[4], self[5] = find(self.s, s, self.i)\
if is then self.e, self.i = self.i, 1+ie; if f then f(unpack(self)) end return self end\
end\
local function date_parse(str)\
local y,m,d, h,r,s, z, w,u, j, e, k, x,v,c, chkfin, dn,df;\
local sw = newstrwalker(gsub(gsub(str, \"(%b())\", \"\"),\"^(%s*)\",\"\")) -- remove comment, trim leading space\
--local function error_out() print(y,m,d,h,r,s) end\
local function error_dup(q) --[[error_out()]] error(\"duplicate value: \" .. (q or \"\") .. sw:aimchr()) end\
local function error_syn(q) --[[error_out()]] error(\"syntax error: \" .. (q or \"\") .. sw:aimchr()) end\
local function error_inv(q) --[[error_out()]] error(\"invalid date: \" .. (q or \"\") .. sw:aimchr()) end\
local function sety(q) y = y and error_dup() or tonumber(q); end\
local function setm(q) m = (m or w or j) and error_dup(m or w or j) or tonumber(q) end\
local function setd(q) d = d and error_dup() or tonumber(q) end\
local function seth(q) h = h and error_dup() or tonumber(q) end\
local function setr(q) r = r and error_dup() or tonumber(q) end\
local function sets(q) s = s and error_dup() or tonumber(q) end\
local function adds(q) s = s + tonumber(q) end\
local function setj(q) j = (m or w or j) and error_dup() or tonumber(q); end\
local function setz(q) z = (z ~= 0 and z) and error_dup() or q end\
local function setzn(zs,zn) zn = tonumber(zn); setz( ((zn<24) and (zn*60) or (mod(zn,100) + floor(zn/100) * 60))*( zs=='+' and -1 or 1) ) end\
local function setzc(zs,zh,zm) setz( ((tonumber(zh)*60) + tonumber(zm))*( zs=='+' and -1 or 1) ) end\
\
if not (sw(\"^(%d%d%d%d)\",sety) and (sw(\"^(%-?)(%d%d)%1(%d%d)\",function(_,a,b) setm(tonumber(a)); setd(tonumber(b)) end) or sw(\"^(%-?)[Ww](%d%d)%1(%d?)\",function(_,a,b) w, u = tonumber(a), tonumber(b or 1) end) or sw(\"^%-?(%d%d%d)\",setj) or sw(\"^%-?(%d%d)\",function(a) setm(a);setd(1) end))\
and ((sw(\"^%s*[Tt]?(%d%d):?\",seth) and sw(\"^(%d%d):?\",setr) and sw(\"^(%d%d)\",sets) and sw(\"^(%.%d+)\",adds))\
or sw:finish() or (sw\"^%s*$\" or sw\"^%s*[Zz]%s*$\" or sw(\"^%s-([%+%-])(%d%d):?(%d%d)%s*$\",setzc) or sw(\"^%s*([%+%-])(%d%d)%s*$\",setzn))\
) )\
then --print(y,m,d,h,r,s,z,w,u,j)\
sw:restart(); y,m,d,h,r,s,z,w,u,j = nil;\
repeat -- print(sw:aimchr())\
if sw(\"^[tT:]?%s*(%d%d?):\",seth) then --print(\"$Time\")\
_ = sw(\"^%s*(%d%d?)\",setr) and sw(\"^%s*:%s*(%d%d?)\",sets) and sw(\"^(%.%d+)\",adds)\
elseif sw(\"^(%d+)[/\\\\%s,-]?%s*\") then --print(\"$Digits\")\
x, c = tonumber(sw[1]), len(sw[1])\
if (x >= 70) or (m and d and (not y)) or (c > 3) then\
sety( x + ((x >= 100 or c>3)and 0 or 1900) )\
else\
if m then setd(x) else m = x end\
end\
elseif sw(\"^(%a+)[/\\\\%s,-]?%s*\") then --print(\"$Words\")\
x = sw[1]\
if inlist(x, sl_months, 2, sw) then\
if m and (not d) and (not y) then d, m = m, false end\
setm(mod(sw[0],12)+1)\
elseif inlist(x, sl_timezone, 2, sw) then\
c = fix(sw[0]) -- ignore gmt and utc\
if c ~= 0 then setz(c, x) end\
elseif inlist(x, sl_weekdays, 2, sw) then\
k = sw[0]\
else\
sw:back()\
-- am pm bce ad ce bc\
if sw(\"^([bB])%s*(%.?)%s*[Cc]%s*(%2)%s*[Ee]%s*(%2)%s*\") or sw(\"^([bB])%s*(%.?)%s*[Cc]%s*(%2)%s*\") then\
e = e and error_dup() or -1\
elseif sw(\"^([aA])%s*(%.?)%s*[Dd]%s*(%2)%s*\") or sw(\"^([cC])%s*(%.?)%s*[Ee]%s*(%2)%s*\") then\
e = e and error_dup() or 1\
elseif sw(\"^([PApa])%s*(%.?)%s*[Mm]?%s*(%2)%s*\") then\
x = lwr(sw[1]) -- there should be hour and it must be correct\
if (not h) or (h > 12) or (h < 0) then return error_inv() end\
if x == 'a' and h == 12 then h = 0 end -- am\
if x == 'p' and h ~= 12 then h = h + 12 end -- pm\
else error_syn() end\
end\
elseif not(sw(\"^([+-])(%d%d?):(%d%d)\",setzc) or sw(\"^([+-])(%d+)\",setzn) or sw(\"^[Zz]%s*$\")) then -- sw{\"([+-])\",{\"(%d%d?):(%d%d)\",\"(%d+)\"}}\
error_syn(\"?\")\
end\
sw(\"^%s*\") until sw:finish()\
--else print(\"$Iso(Date|Time|Zone)\")\
end\
-- if date is given, it must be complete year, month & day\
if (not y and not h) or ((m and not d) or (d and not m)) or ((m and w) or (m and j) or (j and w)) then return error_inv(\"!\") end\
-- fix month\
if m then m = m - 1 end\
-- fix year if we are on BCE\
if e and e < 0 and y > 0 then y = 1 - y end\
-- create date object\
dn = (y and ((w and makedaynum_isoywd(y,w,u)) or (j and makedaynum(y, 0, j)) or makedaynum(y, m, d))) or DAYNUM_DEF\
df = makedayfrc(h or 0, r or 0, s or 0, 0) + ((z or 0)*TICKSPERMIN)\
--print(\"Zone\",h,r,s,z,m,d,y,df)\
return date_new(dn, df) -- no need to :normalize();\
end\
local function date_fromtable(v)\
local y, m, d = fix(v.year), getmontharg(v.month), fix(v.day)\
local h, r, s, t = tonumber(v.hour), tonumber(v.min), tonumber(v.sec), tonumber(v.ticks)\
-- atleast there is time or complete date\
if (y or m or d) and (not(y and m and d)) then return error(\"incomplete table\") end\
return (y or h or r or s or t) and date_new(y and makedaynum(y, m, d) or DAYNUM_DEF, makedayfrc(h or 0, r or 0, s or 0, t or 0))\
end\
local tmap = {\
['number'] = function(v) return date_epoch:copy():addseconds(v) end,\
['string'] = function(v) return date_parse(v) end,\
['boolean']= function(v) return date_fromtable(osdate(v and \"!*t\" or \"*t\")) end,\
['table'] = function(v) local ref = getmetatable(v) == dobj; return ref and v or date_fromtable(v), ref end\
}\
local function date_getdobj(v)\
local o, r = (tmap[type(v)] or fnil)(v);\
return (o and o:normalize() or error\"invalid date time value\"), r -- if r is true then o is a reference to a date obj\
end\
--#end -- not DATE_OBJECT_AFX\
local function date_from(...)\
local arg = pack(...)\
local y, m, d = fix(arg[1]), getmontharg(arg[2]), fix(arg[3])\
local h, r, s, t = tonumber(arg[4] or 0), tonumber(arg[5] or 0), tonumber(arg[6] or 0), tonumber(arg[7] or 0)\
if y and m and d and h and r and s and t then\
return date_new(makedaynum(y, m, d), makedayfrc(h, r, s, t)):normalize()\
else\
return date_error_arg()\
end\
end\
\
--[[ THE DATE OBJECT METHODS ]]--\
function dobj:normalize()\
local dn, df = fix(self.daynum), self.dayfrc\
self.daynum, self.dayfrc = dn + floor(df/TICKSPERDAY), mod(df, TICKSPERDAY)\
return (dn >= DAYNUM_MIN and dn <= DAYNUM_MAX) and self or error(\"date beyond imposed limits:\"..self)\
end\
\
function dobj:getdate() local y, m, d = breakdaynum(self.daynum) return y, m+1, d end\
function dobj:gettime() return breakdayfrc(self.dayfrc) end\
\
function dobj:getclockhour() local h = self:gethours() return h>12 and mod(h,12) or (h==0 and 12 or h) end\
\
function dobj:getyearday() return yearday(self.daynum) + 1 end\
function dobj:getweekday() return weekday(self.daynum) + 1 end -- in lua weekday is sunday = 1, monday = 2 ...\
\
function dobj:getyear() local r,_,_ = breakdaynum(self.daynum) return r end\
function dobj:getmonth() local _,r,_ = breakdaynum(self.daynum) return r+1 end-- in lua month is 1 base\
function dobj:getday() local _,_,r = breakdaynum(self.daynum) return r end\
function dobj:gethours() return mod(floor(self.dayfrc/TICKSPERHOUR),HOURPERDAY) end\
function dobj:getminutes() return mod(floor(self.dayfrc/TICKSPERMIN), MINPERHOUR) end\
function dobj:getseconds() return mod(floor(self.dayfrc/TICKSPERSEC ),SECPERMIN) end\
function dobj:getfracsec() return mod(floor(self.dayfrc/TICKSPERSEC ),SECPERMIN)+(mod(self.dayfrc,TICKSPERSEC)/TICKSPERSEC) end\
function dobj:getticks(u) local x = mod(self.dayfrc,TICKSPERSEC) return u and ((x*u)/TICKSPERSEC) or x end\
\
function dobj:getweeknumber(wdb)\
local wd, yd = weekday(self.daynum), yearday(self.daynum)\
if wdb then\
wdb = tonumber(wdb)\
if wdb then\
wd = mod(wd-(wdb-1),7)-- shift the week day base\
else\
return date_error_arg()\
end\
end\
return (yd < wd and 0) or (floor(yd/7) + ((mod(yd, 7)>=wd) and 1 or 0))\
end\
\
function dobj:getisoweekday() return mod(weekday(self.daynum)-1,7)+1 end -- sunday = 7, monday = 1 ...\
function dobj:getisoweeknumber() return (isowy(self.daynum)) end\
function dobj:getisoyear() return isoy(self.daynum) end\
function dobj:getisodate()\
local w, y = isowy(self.daynum)\
return y, w, self:getisoweekday()\
end\
function dobj:setisoyear(y, w, d)\
local cy, cw, cd = self:getisodate()\
if y then cy = fix(tonumber(y))end\
if w then cw = fix(tonumber(w))end\
if d then cd = fix(tonumber(d))end\
if cy and cw and cd then\
self.daynum = makedaynum_isoywd(cy, cw, cd)\
return self:normalize()\
else\
return date_error_arg()\
end\
end\
\
function dobj:setisoweekday(d) return self:setisoyear(nil, nil, d) end\
function dobj:setisoweeknumber(w,d) return self:setisoyear(nil, w, d) end\
\
function dobj:setyear(y, m, d)\
local cy, cm, cd = breakdaynum(self.daynum)\
if y then cy = fix(tonumber(y))end\
if m then cm = getmontharg(m) end\
if d then cd = fix(tonumber(d))end\
if cy and cm and cd then\
self.daynum = makedaynum(cy, cm, cd)\
return self:normalize()\
else\
return date_error_arg()\
end\
end\
\
function dobj:setmonth(m, d)return self:setyear(nil, m, d) end\
function dobj:setday(d) return self:setyear(nil, nil, d) end\
\
function dobj:sethours(h, m, s, t)\
local ch,cm,cs,ck = breakdayfrc(self.dayfrc)\
ch, cm, cs, ck = tonumber(h or ch), tonumber(m or cm), tonumber(s or cs), tonumber(t or ck)\
if ch and cm and cs and ck then\
self.dayfrc = makedayfrc(ch, cm, cs, ck)\
return self:normalize()\
else\
return date_error_arg()\
end\
end\
\
function dobj:setminutes(m,s,t) return self:sethours(nil, m, s, t) end\
function dobj:setseconds(s, t) return self:sethours(nil, nil, s, t) end\