-
-
Notifications
You must be signed in to change notification settings - Fork 215
/
extensions.py
1499 lines (1088 loc) · 29.3 KB
/
extensions.py
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
# encoding: utf-8
# nocoding: interpy "string interpolation #{like ruby}"
# encoding=utf8
import io
import math
import sys
import inspect
import re # for 'is_file'
import os
# import __builtin__
import numpy as np
from random import randint
from random import random as _random
import shutil
# from extension_functions import * MERGED BACK!
py2 = sys.version < '3'
py3 = sys.version >= '3'
true = True
false = False
pi = math.pi
E = math.e
def Max(a, b):
if a > b:
return a
return b
def Min(a, b):
if a > b:
return b
return a
def rand(n=1): return _random() * n
def random(n=1): return _random() * n
def random_array(l): return np.random.rand(l) # (0,1) x,y don't work ->
def random_matrix(x, y): return np.random.rand(x, y) # (0,1) !
def pick(xs):
return xs[randint(len(xs))]
def reverse(x):
y = x.reverse()
return y or x
def h(x):
help(x)
def log(msg):
print(msg)
def fold(self, x, fun):
if not callable(fun):
fun, x = x, fun
return reduce(fun, self, x)
def last(xs):
return xs[-1]
def Pow(x, y):
return x**y
def is_string(s):
return isinstance(s, str) or isinstance(s, xstr) or isinstance(s, unicode)
# or issubclass(s,str) or issubclass(s,unicode)
def flatten(l):
if isinstance(l, list) or isinstance(l, tuple):
for k in l:
if isinstance(k, list):
l.remove(k)
l.append(*k)
else:
return [l]
# verbose("NOT flattenable: %s"%s)
return l
def square(x):
if isinstance(x, list): return map(square, x)
return x * x
def puts(x):
print(x)
return x
def increase(x):
import nodes
# if isinstance(x, dict)
if isinstance(x, nodes.Variable):
x.value = x.value + 1
return x.value
return x + 1
def grep(xs, x):
# filter(lambda y: re.match(x,y),xs)
# return filter(pattern, xs)
if isinstance(x, list):
return filter(lambda y: x[0] in str(y), xs)
return filter(lambda y: x in str(y), xs)
def ls(mypath="."):
from extensions import xlist
return xlist(os.listdir(mypath))
def length(self):
return len(self)
def say(x):
print(x)
os.system("say '%s'" % x)
def bash(x):
os.system(x)
def beep():
print("\aBEEP ")
def beep(bug=True):
print("\aBEEP ")
import context
if not context.testing:
import os
os.system("say 'beep'")
return 'beeped'
def match_path(p):
if not isinstance(p, str): return False
m = re.search(r'^(/[\w\'.]+)', p)
if not m: return []
return m
def regex_match(a, b):
NONE = "None"
match = regex_matches(a, b)
if match:
try:
return a[match.start():match.end()].strip()
except:
return b[match.start():match.end()].strip()
return NONE
# RegexType= _sre.SRE_Pattern#type(r'')
MatchObjectType = type(re.search('', ''))
def typeof(x):
print("type(x)")
return type(x)
def regex_matches(a, b):
if isinstance(a, re._pattern_type):
return a.search(b) #
if isinstance(b, re._pattern_type):
return b.search(a)
if is_string(a) and len(a) > 0:
if a[0] == "/": return re.compile(a).search(b)
if is_string(b) and len(b) > 0:
if b[0] == "/": return re.compile(b).search(a)
try:
b = re.compile(b)
except:
print("FAILED: re.compile(%s)" % b)
b = re.compile(str(b))
print(a)
print(b)
return b.search(str(a)) # vs
# return b.match(a) # vs search
# return a.__matches__(b) # other cases
# return a.contains(b)
def is_file(p, must_exist=True):
if not isinstance(p, str): return False
if re.search(r'^\d*\.\d+', p): return False
if re.match(r'^\d*\.\d+', str(p)): return False
m = re.search(r'^(\/[\w\'\.]+)', p)
m = m or re.search(r'^([\w\/\.]*\.\w+)', p)
if not m: return False
return must_exist and m and os.path.isfile(m.string) or m
def is_dir(x, must_exist=True):
# (the.string+" ").match(r'^(\')?([^\/\\0]+(\')?)+ ')
m = match_path(x)
return must_exist and m and (py3 and os.path.isdir(m[0])) or (py2 and os.path.isdirectory(m[0]))
# def print(x # debug!):
# print x
# print "\n"
# x
def exists(x):
return os.path.isfile(x)
def is_dir(x):
return os.path.isfile(x) and os.path.isdir(x)
def is_file(x):#Is it a file, or a directory?
return os.path.isfile(x) and not os.path.isdir(x)
def is_a(self, clazz):
if self is clazz: return True
try:
ok = isinstance(self, clazz)
if ok: return True
except Exception as e:
print(e)
className = str(clazz).lower()
if className == str(self).lower(): return True # KINDA
if self.is_(clazz): return True
return False
# print("extension functions loaded")
# from fractions import Fraction
# x = Fraction(22, 7) # Ruby: 22 / 7r 22r / 7
if py3:
class file(io.IOBase):
pass # WTF python3 !?!?!?!?!??
class xrange: # WTF python3 !?!?!?!?!??
pass
class xstr(str):
pass # later
class unicode(xstr): # , bytes): # xchar[] TypeError: multiple bases have instance lay-out conflict
# Python 3 renamed the unicode type to str, the old str type has been replaced by bytes.
pass
# else: https://stackoverflow.com/questions/22098099/reason-why-xrange-is-not-inheritable-in-python
# class range(xrange):
# pass
else: # Python 2 needs:
class bytes(str):
pass
class char(str):
pass
# char = char
class byte(str):
pass
# byte= byte
file = file # nice trick: native py2 class or local py3 class
unicode = unicode
xrange = xrange
if py2:
import cPickle as pickle
else:
import dill as pickle
# try: # py2
# import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
# except:
# pass
def type_name(x):
return type(x).__name__
def xx(y):
if type_name(y).startswith('x'): return y
# if isinstance(y, xstr): return y
# if isinstance(y, xlist): return y
if isinstance(y, xrange): return xlist(y)
if isinstance(y, bool): return y # xbool(y)
if isinstance(y, list): return xlist(y)
if isinstance(y, str): return xstr(y)
if isinstance(y, unicode): return xstr(y)
if isinstance(y, dict): return xdict(y)
if isinstance(y, float): return xfloat(y)
if isinstance(y, int): return xint(y)
if isinstance(y, file): return xfile(y)
if isinstance(y, char): return xchar(y)
if isinstance(y, byte): return xchar(y)
if py3 and isinstance(y, range): return xlist(y)
print("No extension for type %s" % type(y))
return y
extensionMap = {}
def extension(clazz):
try:
for base in clazz.__bases__:
extensionMap[base] = clazz
except:
pass
return clazz
# class Extension:
# def __init__(self, base,b=None,c=None):
# self.base=base
#
# def __call__(self,clazz):
# self.base()
# import angle
# angle.extensionMap[self.base]=clazz
# print(angle.extensionMap)
class Class:
pass
# not def(self):
# False
# class Method(__builtin__.function):
# pass
# file() is no supported in python3
# use open() instead
@extension
class xfile(file):
# import fileutils
# str(def)(self):
# path
path = ""
def name(self):
return self.path
def filename(self):
return self.path
def mv(self, to):
os.rename(self.path, to)
def move(self, to):
os.rename(self.path, to)
def copy(self, to):
shutil.copyfile(self.path, to)
def cp(self, to):
shutil.copyfile(self.path, to)
def contain(self, x):
return self.path.index(x)
def contains(self, x):
return self.path.index(x)
@staticmethod
def delete():
raise Exception("SecurityError: cannot delete files")
# FileUtils.remove_dir(to_path, True)
# @classmethod
# def open(cls):return open(cls)
# @classmethod
# def read(cls):return open(cls)
# @classmethod
# def ls(cls):
# return os.listdir(cls)
@staticmethod
def open(x): return open(x)
@staticmethod
def read(x): return open(x)
@staticmethod
def ls(mypath="."):
return xlist(os.listdir(mypath))
@extension
class File(xfile):
pass
@extension
class Directory(file): #
# str(def)(self):
# path
@classmethod
def cd(path):
os.chdir(path)
def files(self):
os.listdir(str(self)) # ?
@classmethod
def ls(path="."):
os.listdir(path)
@classmethod
def files(path):
os.listdir(path)
def contains(self, x):
return self.files().has(x)
# Dir.cd
# Dir.glob "*.JPG"
#
# import fileutils
#
# def remove_leaves(dir=".", matching= ".svn"):
# Dir.chdir(dir) do
# entries=Dir.entries(Dir.pwd).reject (lambda e: e=="." or e==":" )
# if entries.size == 1 and entries.first == matching:
# print "Removing #{Dir.pwd}"
# FileUtils.rm_rf(Dir.pwd)
# else:
# entries.each do |e|
# if File.directory? e:
# remove_leaves(e)
#
# def delete(self):
# raise SecurityError "cannot delete directories"
# FileUtils.remove_dir(to_path, True)
class Dir(Directory):
pass
class xdir(Directory):
pass
# class Number < Numeric
#
# def not None(self):
# return True
#
# def None.test(self):
# "None.test OK"
#
# def None.+ x(self):
# x
# def None.to_s:
# ""
# #"None"
#
@extension
class xdict(dict):
def clone(self):
import copy
return copy.copy(self)
# return copy.deepcopy(self)
# filter == x.select{|z|z>1}
# CAREFUL! MESSES with rails etc!!
# alias_method :orig_index, :[]
# Careful hash.map returns an Array, not a map as expected
# Therefore we need a new method:
# {a:1,b:2}.map_values{|x|x*3} => {a:3,b:6}
# if not normed here too!!: DANGER: NOT surjective
# def []= x,y # NORM only through getter:
# super[x.to_sym]=y
#
# def __index__(self,x):
# if not x: return
# if isinstance(x, symtable.Symbol): return orig_index(x) or orig_index(str(x))
# if isinstance(x,str): return orig_index(x)
# # yay! todo: eqls {a:b}=={:a=>b}=={"a"=>b} !!
# return orig_index(x)
def contains(self, key):
return self.keys().contains(key)
class Class:
def wrap(self):
return str(self) # TODO!?
# WOW YAY WORKS!!!
# ONLY VIA EXPLICIT CONSTRUCTOR!
# NOOOO!! BAAAD! isinstance(my_xlist,list) FALSE !!
from functools import partial # for method_missing
@extension
class xlist(list):
def unique(xs):
return xlist(set(xs))
#
# def list(xs):
# for x in xs:
# print(x)
# return xs
def uniq(xs):
return xlist(set(xs))
def unique(xs):
return xlist(set(xs))
def add(self, x):
self.insert(len(self), x)
def method_missing(xs, name, *args, **kwargs): # [2.1,4.8].int=[2,5]
if len(xs) == 0: return None
try:
method = getattr(xs.first(), name)
except:
# if str(name) in globals():
method = globals()[str(name)] # .method(m)
if not callable(method):
properties = xlist(map(lambda x: getattr(x, name), xs))
return xlist(zip(xs, properties))
# return properties
return xlist(map(lambda x: method(args, kwargs), xs)) # method bound to x
def pick(xs):
return xs[randint(len(xs))]
def __getattr__(self, name):
if str(name) in globals():
method = globals()[str(name)] # .method(m)
try:
return method(self)
except:
xlist(map(method, self))
return self.method_missing(name)
# return partial(self.method_missing, name)
def select(xs, func): # VS MAP!!
# return [x for x in xs if func(x)]
return filter(func, xs)
def map(xs, func):
return xlist(map(func, xs))
def last(xs):
return xs[-1]
def first(xs):
return xs[0]
def fold(self, x, fun):
if not callable(fun):
fun, x = x, fun
return self.reduce(fun, self, x)
def row(xs, n):
return xs[int(n) - 1]
def column(xs, n):
if isinstance(xs[0], str):
return xlist(map(lambda row: xstr(row).word(n + 1), xs))
if isinstance(xs[0], list):
return xlist(map(lambda row: row[n], xs))
raise Exception("column of %s undefined" % type(xs[0]))
# c=self[n]
def length(self):
return len(self)
def clone(self):
import copy
return copy.copy(self)
# return copy.deepcopy(self)
def flatten(self):
from itertools import chain
return list(chain.from_iterable(self))
def __gt__(self, other):
if not isinstance(other, list): other = [other]
return list.__gt__(self, other)
def __lt__(self, other):
if not isinstance(other, list): other = [other]
return list.__lt__(self, other)
# TypeError: unorderable types: int() < list() fucking python 3
# def __cmp__(self, other):
# if not isinstance(other, list): other = [other]
# return list.__cmp__(self, other)
def __sub__(self, other): # xlist-[1]-[2] minus
if not hasattr(other, '__iter__'): other = [other]
return xlist(i for i in self if i not in other)
def __rsub__(self, other): # [1]-xlist-[2] ok!
return xlist(i for i in other if i not in self)
def c(self):
return xlist(map(str.c, self).join(", ")) # leave [] which is not compatible with C
def wrap(self):
# map(wrap).join(", ") # leave [] which is not compatible with C
return "rb_ary_new3(#{size}/*size*', #{wraps})" # values
def wraps(self):
return xlist(map(lambda x: x.wrap, self).join(", ")) # leave [] which is not compatible with C
def values(self):
return xlist(map(lambda x: x.value, self).join(", ")) # leave [] which is not compatible with C
def contains_a(self, type):
for a in self:
if isinstance(a, type): return True
return False
def drop(self, x):
return self.reject(x)
def to_s(self):
return self.join(", ")
# ifdef $auto_map:
# def method_missing(method, *args, block):
# if args.count==0: return self.map (lambda x: x.send(method ))
# if args.count>0: return self.map (lambda x: x.send(method, args) )
# super method, *args, block
# def matches(item):
# contains item
#
# remove: confusing!!
def matches(self, regex):
for i in self.flatten():
m = regex.match(i.gsub(r'([^\w])', "\\\\\\1")) # escape_token(i))
if m:
return m
return False
def And(self, x):
if not isinstance(x, list): self + [x]
return self + x
def plus(self, x):
if not isinstance(x, list): self + [x]
return self + x
# EVIL!!
# not def(self):
# None? not or
# def = x unexpected '=':
# is x
#
# def grep(x):
# select{|y|y.to_s.match(x)}
#
def names(self):
return xlist(map(str, self))
def rest(self, index=1):
return self[index:]
def fix_int(self, i):
if str(i) == "middle": i = self.count() / 2
if isinstance(i, Numeric): return i - 1
i = xstr(i).parse_integer()
return i - 1
def character(self, nr):
return self.item(nr)
def item(self, nr): # -1 AppleScript style ! BUT list[0] !
return self[xlist(self).fix_int(nr)]
def word(self, nr): # -1 AppleScript style ! BUT list[0] !):
return self[xlist(self).fix_int(nr)]
def invert(self): # ! Self modifying !
self.reverse()
return self
def get(self, x):
return self[self.index(x)]
# def row(self, n):
# return self.at(n)
def has(self, x):
return self.index(x)
def contains(self, x):
ok = self.index(x)
if ok:
return self.at(self.index(x))
else:
return False
# def to_s:
# "["+join(", ")+"]"
#
# class TrueClass:
# not def(self):
# False
class FalseClass:
# not def(self):
# True
def wrap(self):
return self
def c(self):
return self
@extension
class xstr(str):
# @staticmethod
# def invert(self):
# r=reversed(self) #iterator!
# return "".join(r)
def invert(self):
r = reversed(self) # iterator!
self = "".join(r)
return self
def inverse(self):
r = reversed(self) # iterator!
return "".join(r)
def reverse(self):
r = reversed(self) # iterator!
return "".join(r)
def to_i(self):
return int(self)
# to_i=property(to_i1,to_i1)
def quoted(self):
return "%s" % self
# def c(self):
# return self.quoted()
# def id(self):
# return "id(%s)" % self
#
# def wrap(self):
# return "s(%s)" % self
# def value(self):
# return self # variable
# quoted
# def name(self):
# return self
def number(self):
return int(self)
def is_in(self, ary):
return ary.has(self)
def cut_to(self, pattern):
return self.sub(0, self.indexOf(pattern))
def matches(self, regex):
if isinstance(regex, list):
for x in regex:
if re.match(x):
return x
else:
return re.match(regex)
return False
def strip_newline(self):
return self.strip() # .sub(r';$', '')
def join(self, x):
return self + x
# def < x:
# i=x.is_a?Numeric
# if i:
# return int(self)<x
#
# super.< x
#
def starts_with(self, x):
# puts "WARNING: start_with? missspelled as starts_with?"
if isinstance(x, list):
for y in x:
if self.startswith(y): return y
return self.startswith(x)
# def show(self, x=None):
# print(x or self)
# return x or self
def contains(self, *things):
for t in flatten(things):
if self.index(t): return True
return False
def fix_int(self, i):
if str(i) == "middle": i = self.count / 2
if isinstance(i, int): return i - 1
i = xstr(i).parse_integer()
return i - 1
def sentence(self, i):
i = self.fix_int(i)
return self.split(r'[\.\?\!\;]')[i]
def paragraph(self, i):
i = self.fix_int(i)
return self.split("\n")[i]
def word(self, i):
i = self.fix_int(i)
replaced = self.replace("\t", " ").replace(" ", " ").replace("\t", " ").replace(" ", " ") # WTF
words = replaced.split(" ")
if i >= len(words): return self # be gentle
return words[i]
def item(self, i):
return self.word(i)
def char(self, i):
return self.character(i)
def character(self, i):
i = self.fix_int(i)
return self[i - 1:i]
def flip(self):
return self.split(" ").reverse.join(" ")
def plus(self, x):
return self + x
def _and(self, x):
return self + x
def add(self, x):
return self + x
def offset(self, x):
return self.index(x)
def __sub__(self, x):
return self.gsub(x, "")
# self[0:self.index(x)-1]+self[self.index(x)+x.length:-1]
def synsets(self, param):
pass
def is_noun(self): # expensive!):
# Sequel::InvalidOperation Invalid argument used for IS operator
return self.synsets('noun') or self.gsub(r's$', "").synsets('noun') # except False
def is_verb(self):
return self.synsets('verb') or self.gsub(r's$', "").synsets('verb')
def is_a(className):
className = className.lower()
if className == "quote": return True
return className == "string"
def is_adverb(self):
return self.synsets('adverb')
def is_adjective(self):
return self.synsets('adjective')
def examples(self):
return xlist(self.synsets.flatten.map('hyponyms').flatten().map('words').flatten.uniq.map('to_s'))
# def not_(self):
# return None or not
def lowercase(self):
return self.lower()
# def replace(self,param, param1):
# pass
def replaceAll(self, pattern, string):
return re.sub(pattern, string, self)
def shift(self, n=1):
n.times(self=self.replaceAll(r'^.', ""))
# self[n:-1]
def replace_numerals(self):
x = self
x = x.replace(r'([a-z])-([a-z])', "\\1+\\2") # WHOOOT???
x = x.replace("last", "-1") # index trick
# x = x.replace("last", "0") # index trick
x = x.replace("first", "1") # index trick
x = x.replace("tenth", "10")
x = x.replace("ninth", "9")
x = x.replace("eighth", "8")
x = x.replace("seventh", "7")
x = x.replace("sixth", "6")
x = x.replace("fifth", "5")
x = x.replace("fourth", "4")
x = x.replace("third", "3")
x = x.replace("second", "2")
x = x.replace("first", "1")
x = x.replace("zero", "0")
x = x.replace("4th", "4")
x = x.replace("3rd", "3")
x = x.replace("2nd", "2")
x = x.replace("1st", "1")
x = x.replace("(\d+)th", "\\1")
x = x.replace("(\d+)rd", "\\1")
x = x.replace("(\d+)nd", "\\1")
x = x.replace("(\d+)st", "\\1")
x = x.replace("a couple of", "2")
x = x.replace("a dozen", "12")
x = x.replace("ten", "10")