/
util.py
1658 lines (1415 loc) · 53.8 KB
/
util.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
#!/usr/bin/env python
# Filename: util.py
'''
util
@author: Andrew Philpot
@version 0.79
collection of misc utils
Usage: python util.py
Options:
\t-h, --help:\tprint help to STDOUT and quit
\t-v, --verbose:\tverbose output
'''
import sys
import inspect
import types
import getopt
import fileinput
import tempfile
import datetime
import time
import StringIO
import re
import htmlentitydefs
import os
import socket
from itertools import izip_longest
import math
import hashlib
import codecs
from subprocess import check_output, CalledProcessError
import argparse
import cgi
from contextlib import contextmanager
import multiprocessing as mp
import subprocess
import colorama
from colorama import Fore, Back, Style
import traceback
import requests
VERSION = '0.79'
__version__ = VERSION
REVISION = '$Revision: 25780 $'.replace('$','')
# defaults
VERBOSE = True
# util section echo (= trace)
# adapted from http://wordaligned.org/articles/echo
def format_arg_value(arg_val):
""" Return a string representing a (name, value) pair.
>>> format_arg_value(('x', (1, 2, 3)))
'x=(1, 2, 3)'
"""
arg, val = arg_val
return "%s=%r" % (arg, val)
def echo(fn, write=sys.stdout.write):
""" Echo calls to a function.
Returns a decorated version of the input function which "echoes" calls
made to it by writing out the function's name and the arguments it was
called with.
"""
import functools
# Unpack function's arg count, arg names, arg defaults
code = fn.func_code
argcount = code.co_argcount
argnames = code.co_varnames[:argcount]
fn_defaults = fn.func_defaults or list()
argdefs = dict(zip(argnames[-len(fn_defaults):], fn_defaults))
name = fn.__name__
@functools.wraps(fn)
def wrapped(*v, **k):
# Collect function arguments by chaining together positional,
# defaulted, extra positional and keyword arguments.
positional = map(format_arg_value, zip(argnames, v))
defaulted = [format_arg_value((a, argdefs[a]))
for a in argnames[len(v):] if a not in k]
nameless = map(repr, v[argcount:])
keyword = map(format_arg_value, k.items())
args = positional + defaulted + nameless + keyword
write(emittable("=> %s(%s)\n" % (name, ", ".join(args))))
try:
result = fn(*v, **k)
write(emittable("<= %s : %s\n" % (name, result)))
except Exception as e:
write(emittable("<# %s exited exceptionally (%s.%s) via %r\n" % (name, os.path.basename(traceback.extract_stack()[-2][0]), traceback.extract_stack()[-2][1], e)))
raise e
return result
return wrapped
def eecho(fn, write=sys.stderr.write):
return echo(fn, write=sys.stderr.write)
# 18 April 2014
# adapted from https://wiki.python.org/moin/PythonDecoratorLibrary
# import warnings
import functools
def deprecated(func):
'''This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.'''
@functools.wraps(func)
def new_func(*args, **kwargs):
# warnings.warn_explicit(
# "Call to deprecated function {}.".format(func.__name__),
# category=DeprecationWarning,
# filename=func.func_code.co_filename,
# lineno=func.func_code.co_firstlineno + 1
# )
print >> sys.stderr, ("Call to deprecated function %s from %s.%s." %
(func.__name__,
func.func_code.co_filename,
func.func_code.co_firstlineno + 1))
return func(*args, **kwargs)
return new_func
# ## Usage examples ##
# @deprecated
# def my_func():
# pass
# @other_decorators_must_be_upper
# @deprecated
# def my_func():
# pass
# #!/usr/bin/env python
# """
# Deprecated decorator.
# Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
# License: MIT
# """
# import warnings
# import functools
# def deprecated(replacement=None):
# """A decorator which can be used to mark functions as deprecated.
# replacement is a callable that will be called with the same args
# as the decorated function.
# >>> @deprecated()
# ... def foo(x):
# ... return x
# ...
# >>> ret = foo(1)
# DeprecationWarning: foo is deprecated
# >>> ret
# 1
# >>>
# >>>
# >>> def newfun(x):
# ... return 0
# ...
# >>> @deprecated(newfun)
# ... def foo(x):
# ... return x
# ...
# >>> ret = foo(1)
# DeprecationWarning: foo is deprecated; use newfun instead
# >>> ret
# 0
# >>>
# """
# def outer(fun):
# msg = "psutil.%s is deprecated" % fun.__name__
# if replacement is not None:
# msg += "; use %s instead" % replacement
# if fun.__doc__ is None:
# fun.__doc__ = msg
# @functools.wraps(fun)
# def inner(*args, **kwargs):
# warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
# return fun(*args, **kwargs)
# return inner
# return outer
def stub(func):
'''This is a decorator which can be used to mark functions
as stubbed out.'''
@functools.wraps(func)
def new_func(*args, **kwargs):
# warnings.warn_explicit(
# "Call to deprecated function {}.".format(func.__name__),
# category=DeprecationWarning,
# filename=func.func_code.co_filename,
# lineno=func.func_code.co_firstlineno + 1
# )
print >> sys.stderr, ("Call to stubbed-out function %s from %s.%s." %
(func.__name__,
func.func_code.co_filename,
func.func_code.co_firstlineno + 1))
return func(*args, **kwargs)
return new_func
def gripe(msg, *args):
i = inspect.getouterframes(inspect.currentframe(),1)[1]
blurb = msg % tuple(args)
print >> sys.stderr, "---- %s:%s in %s -- %s" % (os.path.basename(i[1]), i[2], i[3], blurb)
del i
def blab(msg, *args):
i = inspect.getouterframes(inspect.currentframe(),1)[1]
blurb = msg % tuple(args)
print >> sys.stderr, "-- %s:%s in %s -- %s" % (os.path.basename(i[1]), i[2], i[3], blurb)
del i
def gossip(msg, *args):
i = inspect.getouterframes(inspect.currentframe(),1)[1]
blurb = msg % tuple(args)
print >> sys.stdout, "-- %s:%s in %s -- %s" % (os.path.basename(i[1]), i[2], i[3], blurb)
del i
class Talkative(object):
def vgripe(self, msg, *args):
try:
if self.verbose:
# gripe(msg, *args)
i = inspect.getouterframes(inspect.currentframe(),1)[1]
blurb = msg % tuple(args)
print >> sys.stderr, ":::: %s:%s in %s :: %s" % (os.path.basename(i[1]), i[2], i[3], blurb)
del i
except:
pass
def vblab(self, msg, *args):
try:
if self.verbose:
# blab(msg, *args)
i = inspect.getouterframes(inspect.currentframe(),1)[1]
blurb = msg % tuple(args)
print >> sys.stderr, ":: %s:%s in %s :: %s" % (os.path.basename(i[1]), i[2], i[3], blurb)
del i
except:
pass
# from http://wiki.python.org/moin/PythonDecoratorLibrary#Cached_Properties
#
# (c) 2011 Christopher Arndt, MIT License
#
class cached_property(object):
'''Decorator for read-only properties evaluated only once within TTL period.
It can be used to created a cached property like this::
import random
# the class containing the property must be a new-style class
class MyClass(object):
# create property whose value is cached for ten minutes
@cached_property(ttl=600)
def randint(self):
# will only be evaluated every 10 min. at maximum.
return random.randint(0, 100)
The value is cached in the '_cache' attribute of the object instance that
has the property getter method wrapped by this decorator. The '_cache'
attribute value is a dictionary which has a key for every property of the
object which is wrapped by this decorator. Each entry in the cache is
created only when the property is accessed for the first time and is a
two-element tuple with the last computed property value and the last time
it was updated in seconds since the epoch.
The default time-to-live (TTL) is 300 seconds (5 minutes). Set the TTL to
zero for the cached value to never expire.
To expire a cached property value manually just do::
del instance._cache[<property name>]
'''
def __init__(self, ttl=300):
self.ttl = ttl
def __call__(self, fget, doc=None):
self.fget = fget
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
self.__module__ = fget.__module__
return self
def __get__(self, inst, owner):
now = time.time()
try:
value, last_update = inst._cache[self.__name__]
if self.ttl > 0 and now - last_update > self.ttl:
raise AttributeError
except (KeyError, AttributeError):
value = self.fget(inst)
try:
cache = inst._cache
except AttributeError:
cache = inst._cache = {}
cache[self.__name__] = (value, now)
return value
# util section splitpath
# from http://nicks-liquid-soapbox.blogspot.com/2011/03/splitting-path-to-list-in-python.html
def splitpath(path, maxdepth=20):
( head, tail ) = os.path.split(path)
return splitpath(head, maxdepth - 1) + [ tail ] \
if maxdepth and head and head != path \
else [ head or tail ]
def ancestry(path, depth=3):
return os.path.join(*splitpath(path)[-depth:])
#philpot
def pathnameName(pth):
return os.path.splitext(os.path.split(pth)[1])[0]
#philpot
def pathnameType(pth):
return os.path.splitext(pth)[1].lstrip('.')
# 19 March 2013
def lowestMatchingPath(path, leafDir):
#info(path)
#print """/usr/bin/python""" in path
#print """/usr/bin/python -m cProfile -s cumulative""" in path
# path = path[0:17] + path[42:]
#print path
# if -m cProfile -s cumulative
# /usr/lib64/python2.7/cProfile.py
comps = splitpath(os.path.realpath(path))
pos = position(leafDir, comps, fromEnd=True)
if not pos:
raise ValueError("No such directory %s in path %s" % (leafDir, path))
return os.path.join(*comps[0:pos+1])
# 19 March 2013
def parentDir(start,count=1):
for i in xrange(count):
start = os.path.join(start, os.pardir)
return os.path.abspath(start)
def slurp(streamDesignator):
'''streamDesignator could be string=filename, sys.stdin, - (= sys.stdin), or an opened file'''
stream = streamDesignator
if isinstance(streamDesignator,str):
stream = open(streamDesignator)
contents = []
for line in stream:
contents.append(line)
return "".join(contents)
import os, errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST:
pass
else:
raise
## essentially the same
def ensureDirectoriesExist(path):
d = os.path.dirname(path)
try:
os.makedirs(d)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# adapted from http://stackoverflow.com/questions/431684/how-do-i-cd-in-python
class CurrentDirectoryContext:
def __init__(self, newPath):
self.newPath = newPath
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
# # Now you can enter the directory like this:
# with CurrentDirectoryContext("~/Library"):
# # we are in ~/Library
# subprocess.call("ls")
def diskUsage(path, duCmd='du'):
"""Untested on bad input"""
try:
result = check_output([duCmd, "-s", "-b", os.path.realpath(path)])
bytes = result.split('\t')[0]
return int(bytes)
except CalledProcessError as e:
return None
def getFolderSize(folder):
total_size = os.path.getsize(folder)
for item in os.listdir(folder):
itempath = os.path.join(folder, item)
if os.path.isfile(itempath):
total_size += os.path.getsize(itempath)
elif os.path.isdir(itempath):
total_size += getFolderSize(itempath)
return total_size
def getFolderCount(folder):
total_count = 0
for item in os.listdir(folder):
itempath = os.path.join(folder, item)
if os.path.isfile(itempath):
# one for file
total_count += 1
elif os.path.isdir(itempath):
# one for the dir
total_count += 1
# plus those in subdirs
total_count += getFolderCount(itempath)
return total_count
def touch(fname, times=None):
with open(fname, 'a'):
os.utime(fname, times)
# util section ID
# adapted from http://effbot.org/zone/python-hash.htm
def c_mul(a, b):
return eval(hex((long(a) * b) & 0xFFFFFFFFL)[:-1])
def pseudohash(sequence):
value = 0x345678
for item in sequence:
value = c_mul(1000003, value) ^ hash(item)
value = value ^ len(sequence)
if value == -1:
value = -2
return value
def iterChunks(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
# lisplike getf for list/tuple
def getf(seq, item):
missing = object()
for (key,val) in iterChunks(seq, 2, fillvalue=missing):
if item == key:
if val == missing:
raise ValueError("malformed property list %s" % (seq,))
return val
return None
# adapted from http://effbot.org/zone/re-sub.html#unescape-html
##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.
def decodeEntities(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
# 1 September 2013
def escapeEntities(uc):
return cgi.escape(uc).encode('ascii', 'xmlcharrefreplace')
# ported from Ute.pm
def safeDecodeEntities(text):
"""Simply delete any control chars in 0x00-0x1F, 0x7F-0xFF"""
text = decodeEntities(text)
# simply delete any control characters
return re.sub(r"""[\x00-\x1F\x7F-\xFF]""", "", text)
def safeAsciiString(text):
# try mightily to represent the contents of string
# using &#nnnn; if necessary
# 'unicodeescape' codec can't decode bytes in position 311-313: truncated \UXXXXXXXX escape
# e.g., in /nfs/studio-data/wat/data/escort/20130101/sandiego.backpage.com/FemaleEscorts/60-forget-the-rest-beautiful-from-top-to-bottom-im-the-best-60-23/8229874
# But this didn't fix it(!)
# # http://stackoverflow.com/questions/7602171/unicode-error-unicodeescape-codec-cant-decode-bytes-string-with-u
# # escape \U
# print "before, len is %s" % len(text)
# text = re.sub(r'\U',r'\\U',text)
# print "after, len is %s" % len(text)
# UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 1035: \ at end of string
text = text.strip("""\\""")
if isinstance(text,str):
u = unicode(text,'unicode_escape')
elif isinstance(text,unicode):
u = text
else:
raise ValueError
# print ">> unicode %s" % u
a = u.encode('ascii','xmlcharrefreplace')
# print ">> xcrp %s" % a
# 1251 stuff 29 June 2012
t = dumb1251decode(a)
# finally, delete any remaining control characters
# should not be necessary(?)
raw = "[\x00-\x1F\x7F-\xFF]"
# print raw,len(raw)
return re.sub(raw, "", t)
def dumbDecodeEntities(text):
"""Encode as numeric entities any control chars in 0x00-0x1F, 0x7F-0xFF"""
def fixup(m):
text = m.group(0)
# print "fixup %s" % text
return "&#%s;" % ord(text[0:1])
return re.sub("""[\x00-\x1F\x7F-\xFF]""", fixup, text)
def dumbEncodeControlChars(text):
"""Encode as numeric entities any control chars in 0x00-0x1F, 0x7F-0xFF"""
def fixup(m):
text = m.group(0)
# print "fixup %s" % text
return "&#%s;" % ord(text[0:1])
return re.sub("""[\x00-\x1F\x7F-\xFF]""", fixup, text)
# 30 January 2013
# gets data as unicode, turns it into a string where all bad characters
# including control characters: x00 - x1F
# including non Ascii latin-1: x7F - XFF
# including unicode #x100 - infinity ;-)
# are represented as decimal HTML entities
import gzip
def slurpAsciiEntitified(file):
try:
with codecs.open(file, encoding='utf-8', mode='r') as stream:
# lines: a list of unicode objects
lines = [line for line in stream]
# blob: a unicode object
blob = u"".join(lines)
# print type(blob)
# text: a unicode object
text = " ".join(blob.splitlines())
# print type(text)
# escaped: a string
escaped = safeAsciiString(dumbDecodeEntities(text))
return escaped
except UnicodeDecodeError as e:
# 14 February 2013
# Assume failure due to file being gzipped(!)
# e.g., /nfs/studio-data/wat/data/escort/20130101/longbeach.backpage.com/FemaleEscorts/luscious-latina-bombshell-22/26059623
print >> sys.stderr, "retry reading %s as gzipped" % (file)
try:
with gzip.open(file) as gunzipfile:
# lines: a list of objects, convert on the fly to unicode utf-8
lines = [line.decode('utf-8') for line in gunzipfile]
# blob: a unicode object
blob = u"".join(lines)
# print type(blob)
# text: a unicode object
text = " ".join(blob.splitlines())
# print type(text)
# escaped: a string
escaped = safeAsciiString(dumbDecodeEntities(text))
return escaped
except IOError as e:
return None
win1251replacements = {
# win 1251 appears with hex encoded entity in 0x80-0x9F range
"€": "€", # EURO SIGN
"": "�", # REPLACEMENT CHAR (philpot)
"‚": "‚", # SINGLE LOW-9 QUOTATION MARK
"ƒ": "ƒ", # LATIN SMALL LETTER F WITH HOOK
"„": "„", # DOUBLE LOW-9 QUOTATION MARK
"…": "…", # HORIZONTAL ELLIPSIS
"†": "†", # DAGGER
"‡": "‡", # DOUBLE DAGGER
"ˆ": "ˆ", # MODIFIER LETTER CIRCUMFLEX ACCENT
"‰": "‰", # PER MILLE SIGN
"Š": "Š", # LATIN CAPITAL LETTER S WITH CARON
"‹": "‹", # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
"Œ": "Œ", # LATIN CAPITAL LIGATURE OE
"": "�", # REPLACEMENT CHAR (philpot)
"Ž": "Ž", # LATIN CAPITAL LETTER Z WITH CARON
"": "�", # REPLACEMENT CHAR (philpot)
"": "�", # REPLACEMENT CHAR (philpot)
"‘": "‘", # LEFT SINGLE QUOTATION MARK
"’": "’", # RIGHT SINGLE QUOTATION MARK
"“": "“", # LEFT DOUBLE QUOTATION MARK
"”": "”", # RIGHT DOUBLE QUOTATION MARK
"•": "•", # BULLET
"–": "–", # EN DASH
"—": "—", # EM DASH
"˜": "˜", # SMALL TILDE
"™": "™", # TRADE MARK SIGN
"š": "š", # LATIN SMALL LETTER S WITH CARON
"›": "›", # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
"œ": "œ", # LATIN SMALL LIGATURE OE
"": "�", # REPLACEMENT CHAR (philpot)
"ž": "ž", # LATIN SMALL LETTER Z WITH CARON
"Ÿ": "Ÿ", # LATIN CAPITAL LETTER Y WITH DIAERESIS
# win 1251 appears with decimal-encoded entity in range
"€": "€", # EURO SIGN
"": "�", # REPLACEMENT CHAR (philpot)
"‚": "‚", # SINGLE LOW-9 QUOTATION MARK
"ƒ": "ƒ", # LATIN SMALL LETTER F WITH HOOK
"„": "„", # DOUBLE LOW-9 QUOTATION MARK
"…": "…", # HORIZONTAL ELLIPSIS
"†": "†", # DAGGER
"‡": "‡", # DOUBLE DAGGER
"ˆ": "ˆ", # MODIFIER LETTER CIRCUMFLEX ACCENT
"‰": "‰", # PER MILLE SIGN
"Š": "Š", # LATIN CAPITAL LETTER S WITH CARON
"‹": "‹", # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
"Œ": "Œ", # LATIN CAPITAL LIGATURE OE
"": "�", # REPLACEMENT CHAR (philpot)
"Ž": "Ž", # LATIN CAPITAL LETTER Z WITH CARON
"": "�", # REPLACEMENT CHAR (philpot)
"": "�", # REPLACEMENT CHAR (philpot)
"‘": "‘", # LEFT SINGLE QUOTATION MARK
"’": "’", # RIGHT SINGLE QUOTATION MARK
"“": "“", # LEFT DOUBLE QUOTATION MARK
"”": "”", # RIGHT DOUBLE QUOTATION MARK
"•": "•", # BULLET
"–": "–", # EN DASH
"—": "—", # EM DASH
"˜": "˜", # SMALL TILDE
"™": "™", # TRADE MARK SIGN
"š": "š", # LATIN SMALL LETTER S WITH CARON
"›": "›", # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
"œ": "œ", # LATIN SMALL LIGATURE OE
"": "�", # REPLACEMENT CHAR (philpot)
"ž": "ž", # LATIN SMALL LETTER Z WITH CARON
"Ÿ": "Ÿ" # LATIN CAPITAL LETTER Y WITH DIAERESIS
}
win1251regex = re.compile('''(&#(?:x8|x9|12|13|14|15)[0-9a-f];)''', re.IGNORECASE)
# Also see mapping table to emulate silly windows emulation
def win1251repl(matchobj):
"""I'm not sure I like this, I think we canonically want decimal entities, at least"""
oldent = matchobj.group(0)
# print "considering replacing %s" % oldent
newent = win1251replacements.get(oldent,oldent)
return newent
def dumb1251decode(text):
return re.sub(win1251regex,win1251repl,text)
# 17 December 2013
def isGzipFile(path):
# SANITY CHECK that a file is actually gzip, not just named .gz/.tgz
fileType = None
try:
# if this succeeds, it is a gzip file
s = gzip.GzipFile(path, 'r')
s.read(2)
fileType = "gzip"
except IOError as e:
# not a gzip file
pass
finally:
# be sure and try to close it
try:
s.close()
except:
pass
return (fileType == "gzip")
# 1 September 2013
def asutf8(x):
if isinstance(x, (int, long, float)):
x = str(x)
return x.encode('utf-8')
#adapted from https://secure.wikimedia.org/wikipedia/en/wiki/Base_36
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Convert positive integer to a base36 string."""
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
# Special case for zero
if number == 0:
return alphabet[0]
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = - number
while number != 0:
number, i = divmod(number, len(alphabet))
base36 = alphabet[i] + base36
return sign + base36
def base36decode(number):
return int(number, 36)
#print base36encode(1412823931503067241)
#print base36decode('AQF8AA0006EH')
def vanillaRepr(o):
cr = hasattr(o, "signature") and callable(getattr(o, "signature")) and o.signature()
cr = "'%s' " % (cr) if cr else ''
return "{|%s %s@ %s|}" % (fullyQualifiedName(o), cr, base36encode(id(o)))
def vanillaStr(o):
cr = hasattr(o, "signature") and callable(getattr(o, "signature")) and o.signature()
cr = "%s " % (cr) if cr else ''
return emittable("<%s %s@ %s>" % (fullyQualifiedName(o), cr, base36encode(id(o))))
def abbrevString(s, max=10):
if len(s) > max:
return s[:max-3] + "..."
else:
return s
# util section control
def forever(x):
while 1:
yield x
# util section output
class NotEmittable(Exception):
pass
onError=True
def emittable(atom, onError=True):
e = atom
if hasattr(e, "encode"):
try:
e = atom.encode('utf-8')
except (AttributeError, TypeError):
gripe("Failed to UTF-8 encode [%s], passing thru unchanged", atom)
except UnicodeEncodeError:
e = "###unencodable###"
except UnicodeDecodeError:
e = "###undecodable###"
if onError:
raise NotEmittable(atom)
except:
e = "###GeneralError###"
else:
e = str(e)
return e
def utf8print(content):
try:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
print content
except:
pass
# util section general introspection
def fullyQualifiedName(o):
m = o.__module__
c = o.__class__.__name__
l = []
if m != '__main__':
l.append(m)
l.append(c)
return ".".join(l)
# adapted from
# """Visit http://diveintopython.org/"""
# __author__ = "Mark Pilgrim (mark@diveintopython.org)"
def safeGetAttr(o,e):
try:
return getattr(o,e)
except AttributeError:
return None
def attrChain(obj, *attrs):
"""if attrs is ["a1", "a2", ..., "an"], then this returns obj.a1.a2.a3...an.
If any .ak for k<n returns a scalar, stop and return None"""
r = obj
complete = False
started = False
for attr in attrs:
try:
r = getattr(r, attr)
started = True
except (ValueError, AttributeError) as e:
return None
complete = True
if started and complete:
return r
else:
raise SyntaxError("Must have some attrs")
def info(object, spacing=12, collapse=1, hidden=False, dest=sys.stdout):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
print >> dest, "INFO for %r" % (object)
methodList = [e for e in dir(object) if callable(safeGetAttr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print >> dest, "\n".join([" %s %s" % (method.ljust(spacing),
processFunc(str(safeGetAttr(object, method).__doc__)))
for method in methodList
if hidden or not method.startswith("__")])
attrList = [e for e in dir(object) if not callable(safeGetAttr(object, e))]
print >> dest, "\n".join([" %s %s" % (attr.ljust(spacing),
processFunc(str(safeGetAttr(object, attr))))
for attr in attrList
if hidden or not attr.startswith("__")])
print >> dest, "END INFO for %r" % (object)
# if name == "main": print help.doc
# util section data-directed programming
def lookupClass(name):
try:
g = globals().get(name)
except TypeError:
# For example if name is something unhashable
return None
return g if inspect.isclass(g) else None
def findClass(thing):
# it's a class
if inspect.isclass(thing):
return thing
# treat as class name (works if it is a string...)
cl = lookupClass(thing)
if cl:
return cl
# return object's stored class
cl = thing.__class__
return cl
def lookupFunction(name):
"Don't try this at home, globals() aren't"
try:
print globals()
g = globals().get(name)
except TypeError:
# For example if name is something unhashable
return None
return g if inspect.isfunction(g) else None
prototypes = {}
def prototype(classOrName, *args, **kwdargs):
cl = findClass(classOrName)
if cl:
proto = prototypes.get(cl)
if not proto:
proto = cl(*args, **kwdargs)
prototypes[cl] = proto
return proto
return None
def objectify(designator, *args, **kwdargs):
return prototype(designator, *args, **kwdargs) or designator.__class__ or designator
def master(dispatch_arg, arg1, arg2, **kwdargs):
return objectify(dispatch_arg).slave(arg1,arg2,**kwdargs)
# example
# Each of these classes exists only to allow data directed programming
#class Banana(object):
# def slave(self, arg1, arg2, **kwdargs):
# print "I am a banana slave"
#
#class Orange(object):
# def slave(self, arg1, arg2, **kwdargs):
# print "I am an orange slave"
# util section : lists
def canonList(thing):
if isinstance(thing, types.ListType):
return thing
else:
return [thing]
# util section: string
def unprefix(prefix, s, strict=False):
if s.startswith(prefix):
return s[len(prefix):]
else:
if strict:
raise ValueError("string '%s' has no prefix '%s'" % (s, prefix))
else:
return s
def unsuffix(suffix, s, strict=False):
if s.endswith(suffix):
return s[:-len(suffix)]
else:
if strict:
raise ValueError("String '%s' has no suffix '%s'" % (s, suffix))
else:
return s
# util section : format
def fmt(fmtString, *args):
return fmtString.format(*args)
# util section temp i/o
outputFiles = {}
def getOutputFile(prefix=None, delete=False, dir=".", mode='w+b'):
scriptName = sys.argv and sys.argv[0]
# assumes that processing has used fileinput.input to open files of interest, either stdin or file(s) passed in on command line
prefix = prefix if prefix else fileinput.filename()
prefix = prefix if (prefix and prefix != '<stdin>') else (scriptName or "out")
outputFile = outputFiles.get(prefix) or outputFiles.setdefault(prefix, tempfile.NamedTemporaryFile(mode=mode, prefix=prefix+"-", delete=delete, dir=dir))
return outputFile
# end utils
def backupFile(pathname):
"""Quick and dirty rename file to timestamped version"""
t=time.localtime()
timestamp = time.strftime("%Y%m%d%H%M%S", t)
os.rename(pathname, pathname + "_" + str(timestamp))
# util section fns
def guess_boolean(thing):
if thing in ("1", 1, "Y", "y", "YES", "Yes", "yes", "T", "t", "TRUE", "True", "true"):
return True
elif thing in ("0", 0, "N", "n", "NO", "No", "no", "F", "f", "FALSE", "False", "false",
"NONE", "None", "none", ""):
return False
else:
raise TypeError('thing must denote a boolean')
# end fns
def rebase(num, base=16):
rem = 1
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
result = []
while num != 0:
rem = num % base
num = num/base
result.append(digits[rem])