This repository has been archived by the owner on Aug 10, 2020. It is now read-only.
/
Utils.py
1614 lines (1316 loc) · 46.1 KB
/
Utils.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
# -*- coding: iso-8859-1 -*-
##
## Fry-IT Zope Base utility scripts
## Peter Bengtsson, peter@fry-it.com, (c) 2005
##
# python
import os
import string
import sys
import re
import inspect
import random
from time import strftime
from random import shuffle
from math import floor
import httplib, urllib
from urlparse import urlparse, urlunparse
from types import FloatType, IntType
from urllib import urlencode
import itertools
import unicodedata
from datetime import date
from htmlentitydefs import entitydefs
entitydefs_inverted = {}
for k,v in entitydefs.items():
entitydefs_inverted[v] = k
from addhrefs import addhrefs
from unaccent import unaccented_map
# zope
try:
from DocumentTemplate import sequence
from Products.PythonScripts.standard import html_quote, newline_to_br, \
structured_text, url_quote, url_quote_plus, thousands_commas
from DateTime import DateTime
from Acquisition import aq_base
except ImportError:
pass
#from DocumentTemplate import sequence
#from Products.PythonScripts.standard import html_quote, newline_to_br, \
# structured_text, url_quote, url_quote_plus, thousands_commas
#-----------------------------------------------------------------------------
#
# ZODB
#
## https://bugs.launchpad.net/zope2/+bug/142399
def safe_hasattr(obj, name, _marker=object()):
"""Make sure we don't mask exceptions like hasattr().
We don't want exceptions other than AttributeError to be masked,
since that too often masks other programming errors.
Three-argument getattr() doesn't mask those, so we use that to
implement our own hasattr() replacement.
"""
return getattr(obj, name, _marker) is not _marker
def base_hasattr(obj, name):
"""Like safe_hasattr, but also disables acquisition."""
return safe_hasattr(aq_base(obj), name)
#-----------------------------------------------------------------------------
#
# Debuggning
#
def debug(s, tabs=0, steps=(1,), include_module_name=False):
inspect_dbg = []
if isinstance(steps, int):
steps = range(1, steps+1)
for i in steps:
try:
caller_module = inspect.stack()[i][1]
caller_method = inspect.stack()[i][3]
caller_method_line = inspect.stack()[i][2]
except IndexError:
break
if include_module_name:
if caller_module.endswith('/__init__.py'):
caller_module = '/'.join(caller_module.split('/')[-2:])
else:
caller_module = caller_module.split('/')[-1]
inspect_dbg.append("(%s)%s:%s"%(caller_module, caller_method, caller_method_line))
else:
inspect_dbg.append("%s:%s"%(caller_method, caller_method_line))
inspect_appendix = ", ".join(inspect_dbg)
if inspect_appendix:
out = "\t"*tabs + "%s (%s)"%(s, inspect_appendix)
else:
out = "\t"*tabs + "%s"%s
print out
#-----------------------------------------------------------------------------
#
# Unicode
#
def unaccent_string(ustring, encoding="ascii"):
if not isinstance(ustring, unicode):
ustring = ustring.decode(encoding)
return ustring.translate(unaccented_map()).encode(encoding, "ignore")
def unicodify(i, encoding='latin-1'):
if type(i) == unicode:
return i
else:
return unicode(str(i), encoding)
def safe_unicodify(s, encodings=('utf8','latin1')):
if isinstance(s, str):
if not isinstance(encodings, (tuple, list)):
encodings = [encodings]
for encoding in encodings:
try:
return unicode(s, encoding)
except UnicodeDecodeError:
pass
raise UnicodeDecodeError, \
"Unable to unicodify %r with these encodings %s" % (s, encodings)
return s
def internationalizeID(y, encoding='latin-1'):
""" this is an improvement to the previous internationalizeID() function
which is left above.
Taken from the comment by Aaron Bentley on
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871
"""
if isinstance(y, str):
y = unicode(y, encoding)
return unicodedata.normalize('NFKD', y).encode('ascii','ignore')
from types import StringType, UnicodeType, InstanceType
nasty_exception_str = Exception.__str__.im_func
def ustr(v):
"""Convert any object to a plain string or unicode string,
minimising the chance of raising a UnicodeError. This
even works with uncooperative objects like Exceptions
"""
string_types = (StringType,UnicodeType)
if type(v) in string_types:
return v
else:
fn = getattr(v,'__str__',None)
if fn is not None:
# An object that wants to present its own string representation,
# but we dont know what type of string. We cant use any built-in
# function like str() or unicode() to retrieve it because
# they all constrain the type which potentially raises an exception.
# To avoid exceptions we have to call __str__ direct.
if getattr(fn,'im_func',None)==nasty_exception_str:
# Exception objects have been optimised into C, and their
# __str__ function fails when given a unicode object.
# Unfortunately this scenario is all too common when
# migrating to unicode, because of code which does:
# raise ValueError(something_I_wasnt_expecting_to_be_unicode)
return _exception_str(v)
else:
# Trust the object to do this right
v = fn()
if type(v) in string_types:
return v
else:
raise ValueError('__str__ returned wrong type')
# Drop through for non-instance types, and instances that
# do not define a special __str__
return str(v)
def _exception_str(exc):
if hasattr(exc, 'args'):
if not exc.args:
return ''
elif len(exc.args) == 1:
return ustr(exc.args[0])
else:
return str(exc.args)
return str(exc)
#-----------------------------------------------------------------------------
#
# Internet, sockets, networking
#
def anyPost(url, cgi_params={}):
params = urllib.urlencode(cgi_params)
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
url_parsed = urlparse(url)
conn = httplib.HTTPConnection(url_parsed[1])
conn.request("POST", url_parsed[2], params, headers)
response = conn.getresponse()
res = response.status, response.reason, response.read()
conn.close()
return res
#-----------------------------------------------------------------------------
#
# URL handling
#
def parametrize_url(url, unicode_encoding='utf8', doseq=False, **params):
""" don't just add the **params because the url
itself might contain CGI variables embedded inside
the string. """
url_parsed = list(urlparse(url))
for k, v in params.items():
if isinstance(v, unicode):
params[k] = v.encode(unicode_encoding)
encoded = urlencode(params, doseq=doseq)
qs = url_parsed[4]
if encoded:
if qs:
qs += '&'+encoded
else:
qs = encoded
netloc = url_parsed[1]
if netloc.find('?')>-1:
url_parsed[1] = url_parsed[1][:netloc.find('?')]
if qs:
qs = netloc[netloc.find('?')+1:]+'&'+qs
else:
qs = netloc[netloc.find('?')+1:]
url_parsed[4] = qs
if url_parsed[2] == '':
url_parsed[2] = '/'
url = urlunparse(url_parsed)
return url
def AddParam2URL(url, params={}):
""" return url and append params but be aware of existing params """
return parametrize_url(url, **params)
p='?'
if p in url:
p = '&'
url = url + p
for key, value in params.items():
url = url + '%s=%s&'%(key, url_quote(value))
return url[:-1]
#-----------------------------------------------------------------------------
#
# Zope inspired
#
def cookIdAndTitle(s):
""" if s='image1~Image One.gif' then return ['image1.gif','Image One']
Testwork:
s='image1~Image One.gif' => ['image1.gif','Image One']
s='image1.gif' => ['image1.gif','']
s='image1~.gif' => ['image1.gif','']
s='image1~Image One.gif.gif'=> ['image1.gif','Image One.gif']
"""
if s.find('~') == -1:
return [s, '']
splitted = s.split('~',1)
id = splitted[0]
rest = s.replace(id+'~','')
if rest.rfind('.') == -1:
return [id, rest]
else:
pos_last_dot = rest.rfind('.')
ext = rest[pos_last_dot:]
id = id.strip() + ext.strip()
title = rest[0:pos_last_dot].strip()
return [id, title]
hide_key={'HTTP_AUTHORIZATION':1,
'HTTP_CGI_AUTHORIZATION': 1,
}.has_key
def REQUEST2String(REQUEST):
result="form\n"
row = "\t%s: %s\n"
for k,v in _filterPasswordFields(REQUEST.form.items()):
result=result + row % (escape(k), escape(repr(v)))
result += "cookies\n"
for k,v in _filterPasswordFields(REQUEST.cookies.items()):
result=result + row % (escape(k), escape(repr(v)))
result += "lazy items\n"
for k,v in _filterPasswordFields(REQUEST._lazies.items()):
result=result + row % (escape(k), escape(repr(v)))
result += "other\n"
for k,v in _filterPasswordFields(REQUEST.other.items()):
if k in ('PARENTS','RESPONSE'): continue
result=result + row % (escape(k), escape(repr(v)))
for n in "0123456789":
key = "URL%s"%n
try: result=result + row % (key, escape(REQUEST[key]))
except KeyError: pass
for n in "0123456789":
key = "BASE%s"%n
try: result=result + row % (key, escape(REQUEST[key]))
except KeyError: pass
result=result+"environ\n"
for k,v in REQUEST.environ.items():
if not hide_key(k):
result=result + row % (escape(k), escape(repr(v)))
return result
#-----------------------------------------------------------------------------
#
# Quoting
#
def tex_quote(s):
for k, v in {'&':r'\&', '$':r'\$', '_':r'\_', r'%':r'\%',
'|':r'\textbackslash', '#':r'\#', '^':r'\^{}',
'~':r'\~{}',
'<':'\textless ', # notice the extra space
'>':'\textgreater ', # notice the extra space
}.items():
s = s.replace(k, v)
return s
def tag_quote(text):
""" similiar to html_quote but only fix < and > """
return text.replace('<','<').replace('>','>')
destroyed_hex_entities = re.compile('&#(\d+);')
def safe_html_quote(text):
""" like html_quote but allow things like Ӓ """
text = html_quote(text)
text = destroyed_hex_entities.sub(r'&#\1;', text)
return text
_badchars_regex = re.compile('|'.join(entitydefs.values()))
_been_fixed_regex = re.compile('&\w+;|&#[0-9]+;')
def html_entity_fixer(text, skipchars=[], extra_careful=1):
if not text:
# then don't even begin to try to do anything
return text
if isinstance(text, unicode):
return text.encode('ascii', 'xmlcharrefreplace')
# if extra_careful we don't attempt to do anything to
# the string if it might have been converted already.
if extra_careful and _been_fixed_regex.findall(text):
return text
if isinstance(skipchars, basestring):
skipchars = [skipchars]
keyholder= {}
for x in _badchars_regex.findall(text):
if x not in skipchars:
keyholder[x] = 1
text = text.replace('&','&')
text = text.replace('\x80', '€')
for each in keyholder.keys():
if each == '&':
continue
better = entitydefs_inverted[each]
if not better.startswith('&#'):
better = '&%s;'%entitydefs_inverted[each]
text = text.replace(each, better)
return text
#-----------------------------------------------------------------------------
#
# Randomness
#
def nicepass(alpha=6,numeric=2):
"""
returns a human-readble password (say rol86din instead of
a difficult to remember K8Yn9muL )
"""
vowels = ['a','e','i','o','u']
consonants = [a for a in string.ascii_lowercase if a not in vowels]
digits = string.digits
####utility functions
def a_part(slen):
ret = ''
for i in range(slen):
if i%2 ==0:
randid = random.randint(0,20) #number of consonants
ret += consonants[randid]
else:
randid = random.randint(0,4) #number of vowels
ret += vowels[randid]
return ret
def n_part(slen):
ret = ''
for i in range(slen):
randid = random.randint(0,9) #number of digits
ret += digits[randid]
return ret
####
fpl = alpha/2
if alpha % 2 :
fpl = int(alpha/2) + 1
lpl = alpha - fpl
start = a_part(fpl)
mid = n_part(numeric)
end = a_part(lpl)
return "%s%s%s" % (start,mid,end)
def getRandomString(length=10, loweronly=1, numbersonly=0,
more_numbers=0, avoidchars=[], lettersonly=0):
""" return a very random string """
if numbersonly:
l = list('0123456789')
else:
if lettersonly:
lowercase = 'abcdefghijklmnopqrstuvwxyz'
else:
lowercase = 'abcdefghijklmnopqrstuvwxyz'+'0123456789'
if more_numbers and abs(more_numbers)==more_numbers:
for i in range(more_numbers):
lowercase += '0123456789'
if loweronly:
l = list(lowercase)
else:
l = list(lowercase + lowercase.upper())
if avoidchars:
if type(avoidchars)==type('s'):
avoidchars = list(avoidchars)
for e in avoidchars:
while e in l:
l.remove(e)
shuffle(l)
s = string.join(l,'')
if len(s) < length:
s = s + getRandomString(loweronly=1)
s = s[:length]
if loweronly:
return s.lower()
else:
return s
#-----------------------------------------------------------------------------
#
# Sequences, lists
#
def anyTrue(pred, seq):
""" http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/212959 """
return True in itertools.imap(pred,seq)
def anyFalse(pred, seq):
""" http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/212959 """
return False in itertools.imap(pred,seq)
def insensitiveRemove(item, list):
rm_these = []
for each in list:
if ss(each) == ss(item):
rm_these.append(each)
for each in rm_these:
list.remove(each)
def insensitiveIN(item, list):
if same_type(item, 's'):
item = ss(item)
for each in list:
if same_type(each, 's'):
if item == ss(each):
return 1
return 0
def listintersection(list1, list2):
checked = []
for e in list1:
if e in list2:
checked.append(e)
return checked
def mergeEnglishList(seq, lastword='or'):
""" make ['abc','def','efg'] into 'abc, def or efg' """
if len(seq) == 0:
return ''
elif len(seq) == 1:
return seq[0]
else:
s = ''
for i in range(len(seq)):
if i == len(seq)-2:
t = ' %s '%lastword
elif i == len(seq)-1:
t = ''
else:
t = ', '
s += "%s%s"%(seq[i], t)
return s
def uniqify(seq, idfun=None): # Alex Martelli ******* order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
##if marker in seen: continue
if seen.has_key(marker): continue
seen[marker] = 1
result.append(item)
return result
def uniqify(seq, idfun=None): # Alex Martelli ******* order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
##if marker in seen: continue
if seen.has_key(marker): continue
seen[marker] = 1
result.append(item)
return result
def iuniqify(seq):
""" return a list of strings unique case insensitively.
If the input is ['foo','bar','Foo']
return ['foo','bar']
"""
def idfunction(x):
if isinstance(x, basestring):
return x.lower()
else:
return x
return uniqify(seq, idfunction)
def moveUpListelement(element, xlist):
""" move an element in a _mutable_ list up one position
if possible. If the element is a list, then the function
is self recursivly called for each subelement.
"""
assert type(xlist)==type([]), "List to change not of list type "\
"(%r)"%type(xlist)
if type(element)==type([]):
for subelement in element:
moveUpListelement(subelement, xlist)
if element==xlist[0]:
pass
elif element in xlist:
i=xlist.index(element)
xlist[i], xlist[i-1] = xlist[i-1], xlist[i]
#-----------------------------------------------------------------------------
#
# HTML handling
#
starttag_regex = re.compile('<.*?>', re.MULTILINE|re.DOTALL)
singletontag_regex = re.compile('<.*?/>', re.MULTILINE|re.DOTALL)
endtag_regex = re.compile('</.*?>', re.MULTILINE|re.DOTALL)
multiple_linebreaks = re.compile('\n\s+\n|\n\n')
def dehtmlify(html):
""" Try to convert an HTML chunk to text """
li_tags = re.compile('<li>\s*',re.I)
html = li_tags.sub(' * ', html)
html = multiple_linebreaks.sub('\n', html)
html = starttag_regex.sub('',html)
html = singletontag_regex.sub('', html)
html = endtag_regex.sub('\n', html)
return html.strip()
#-----------------------------------------------------------------------------
#
# String enhancing
#
def ordinalth(n, html=0):
t = 'th st nd rd th th th th th th'.split()
if n % 100 in (11, 12, 13): #special case
if html:
return '%d'%n+'<sup>th</sup>'
else:
return '%dth' % n
if html:
return str(n) + '<sup>%s</sup>'% t[n % 10]
else:
return str(n) + t[n % 10]
def LineIndent(text, indent, maxwidth=None):
""" indent each new line with 'indent' """
if maxwidth:
parts = []
for part in text.split('\n'):
words = part.split(' ')
lines = []
tmpline = ''
for word in words:
if len(tmpline+' '+word) > maxwidth:
lines.append(tmpline.strip())
tmpline = word
else:
tmpline += ' ' + word
lines.append(tmpline.strip())
start = "\n%s"%indent
parts.append(indent + start.join(lines))
return "\n".join(parts)
else:
text = indent+text
text = text.replace('\n','\n%s'%indent)
return text
def safeId(id, nospaces=0, extra_allows=[]):
""" Just make sure it contains no dodgy characters """
lowercase = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
specials = '_-.' + ''.join(extra_allows)
allowed = lowercase + lowercase.upper() + digits + specials
if not nospaces:
allowed = ' ' + allowed
n_id=[]
allowed_list = list(allowed)
for letter in list(id):
if letter in allowed_list:
n_id.append(letter)
return ''.join(n_id)
def banner(text, ch='=', length=78):
"""Return a banner line centering the given text.
"text" is the text to show in the banner. None can be given to have
no text.
"ch" (optional, default '=') is the banner line character (can
also be a short string to repeat).
"length" (optional, default 78) is the length of banner to make.
Examples:
>>> banner("Peggy Sue")
'================================= Peggy Sue =================================='
>>> banner("Peggy Sue", ch='-', length=50)
'------------------- Peggy Sue --------------------'
>>> banner("Pretty pretty pretty pretty Peggy Sue", length=40)
'Pretty pretty pretty pretty Peggy Sue'
"""
if text is None:
return ch * length
elif len(text) + 2 + len(ch)*2 > length:
# Not enough space for even one line char (plus space) around text.
return text
else:
remain = length - (len(text) + 2)
prefix_len = remain / 2
suffix_len = remain - prefix_len
if len(ch) == 1:
prefix = ch * prefix_len
suffix = ch * suffix_len
else:
prefix = ch * (prefix_len/len(ch)) + ch[:prefix_len%len(ch)]
suffix = ch * (suffix_len/len(ch)) + ch[:suffix_len%len(ch)]
return prefix + ' ' + text + ' ' + suffix
def normalizeMobileNumber(number, default_cc='44'):
""" prepare a mobile number """
number = number.strip()
if number.startswith('00%s'%default_cc):
number = "+"+number[2:]
elif number.startswith('0'):
number = '+%s'%default_cc+number[1:]
number = number.replace(' ','').replace('-','')
return number
def ss(s):
""" simple string """
return s.strip().lower()
def encodeEmailString(email, title=None, nolink=0):
""" just write the email like
<span class="aeh">peter_AT_peterbe_._com</span>
and a 'onLoad' Javascript will convert it to look nice.
The way we show the email address must match the Javascript
that converts it on the fly. """
methods = ['_dot_',' dot ', '_._']
shuffle(methods)
# replace . after @
if '@' in list(email):
afterbit = email.split('@')[1]
newbit = afterbit.replace('.', methods[0])
email = email.replace(afterbit, newbit)
methods = ['_', '~']
shuffle(methods)
atsigns = ['at','AT']
shuffle(atsigns)
# replace @ with *AT*
email = email.replace('@','%s%s%s'%(methods[0], atsigns[0], methods[0]))
if title is None or title == email:
title = email
spantag = '<span class="aeh">%s</span>'
spantag_link = '<span class="aeh"><a href="mailto:%s">%s</a></span>'
if nolink:
return spantag%email
else:
return spantag_link%(email, title)
def encodeEmailString2(email, title=None, nolink=0):
""" A second version of the old encodeEmailString() function.
This one returns a XHTML valid tag not wrapped in a <span> tag"""
methods = [urllib.quote(x) for x in ['_dot_',' dot ', '_._']]
shuffle(methods)
# replace . after @
if '@' in list(email):
afterbit = email.split('@')[1]
newbit = afterbit.replace('.', methods[0])
email = email.replace(afterbit, newbit)
methods = ['_', '~']
shuffle(methods)
atsigns = ['at','AT','ATT']
shuffle(atsigns)
r = random.randint(1,3)
if r==1:
email = email.replace('@','@(removethis)')
elif r==2:
email = email.replace('@','(removethis)@')
# replace @ with *AT*
email = email.replace('@','%s%s%s'%(methods[0], atsigns[0], methods[0]))
if title is None or title == email:
title = email
spantag = '<span class="aeh">%s</span>'
spantag_link = '<a class="aeh" href="mailto:%s">%s</a>'
if nolink:
return spantag % email
else:
return spantag_link % (email, title)
#-----------------------------------------------------------------------------
#
# Booleanism
#
def niceboolean(value):
if type(value) is bool:
return value
falseness = ('','no','off','false','none','0', 'f')
return str(value).lower().strip() not in falseness
def isOrdinalth(s):
""" return true if like 1st, 4th, 11th, 23rd """
ordn = re.compile(r"""\dst$
|\dnd$
|\drd$
|\dth$
|\d\dst$
|\d\dnd$
|\d\drd$
|\d\dth$""",
re.I|re.VERBOSE)
return not not ordn.findall(s)
def typelessEqual(a, b):
""" Checks equality of two values regardless of type """
if a is None or b is None:
# like Postgres deals with NULL
return False
try: # floatable?
a = float(a)
b = float(b)
return a == b
except ValueError:
try:
a = int(a)
b = int(b)
return a == b
except ValueError:
a = str(a)
b = str(b)
return a == b
def same_type(one, two):
""" use this because 'type' as variable can be used elsewhere """
return type(one)==type(two)
def safebool(value):
try:
return not not int(value)
except ValueError:
return 0
#-----------------------------------------------------------------------------
#
# Showers, converters, nicifiers
#
# taken from IssueTrackerProduct and modified
def ShowText(text, display_format='',
emaillinkfunction=None,
urllinkfunction=None,
allowhtml=False, # only applies to plaintext and structured_text
paragraphtag=True, # only applies with plaintext
):
"""
Display text, using harmless HTML
"""
if not text: # blank or None
return ""
if display_format == 'structuredtext':
#st=_replace_special_chars(text)
st=text
if not allowhtml:
for k,v in {'<':'<', '>':'>'}.items():
st = st.replace(k, v)
st = st.replace('[','|[|')
st = html_entity_fixer(st, skipchars=('"',))
st = structured_text(st)
if allowhtml:
for k,v in {'<':'<', '>':'>'}.items():
st = st.replace(v, k)
for k,v in {'&lt;':'<', '&gt;':'>',
'|[|':'['}.items():
st = st.replace(k,v)
st = addhrefs(st, emaillinkfunction=emaillinkfunction, urllinkfunction=urllinkfunction)
st = st.rstrip()
return st
elif display_format == 'html':
return text
else:
if paragraphtag:
t = '<p>%s</p>'%safe_html_quote(text)
else:
t = safe_html_quote(text)
t = t.replace('&lt;','<').replace('&gt;','>')
t = addhrefs(t)
t = newline_to_br(t)
return t
def ShowFilesize(bytes, whole_numbers=False):
""" Return nice representation of size """
if bytes < 1024:
return "1 Kb"
elif bytes > 1024**3:
if whole_numbers:
mb_bytes = '%0.02f'%(bytes / 1024.0**3)
else:
mb_bytes = '%.f'%(bytes / 1024.0**3)
return "%s Gb"%mb_bytes
elif bytes > 1024**2:
if whole_numbers:
mb_bytes = '%0.02f'%(bytes / 1024.0**2)
else:
mb_bytes = '%.f'%(bytes / 1024.0**2)
return "%s Mb"%mb_bytes
else:
return "%s Kb"%int(bytes / 1024)
def formatFloat(f, decimal_places=2):
""" return a float with thousand commas
and two decimal places if any. """
try:
assert type(f) is FloatType or type(f) is IntType, \
"parameter f is not float or int"
except AssertionError:
f = float(f)
if str(int(f))!=str(f): # try if f==1.1 but not if f==1
f= round(f, decimal_places)
_fmt = "%."+str(decimal_places)+"f"
f = _fmt%f
f = thousands_commas(f)
return f
def _QasList(q):
""" q is a string that might contain 'and' and/or 'or'.
Remove that and make it a list. """
L = []
for e in re.compile("'.*'|\".*\"").findall(q):
L.append(e[1:-1])
q = q.replace(e,'')
r=re.compile(r"\band\b|\bor\b", re.I)
return r.sub("", q).split() + L
def _warpLine(found, line, template):
# print found
return line
def highlightQ(q, text, template='<span class="highlight">%s</span>',
splitlines=False):
""" return a result text where certain words are highligheted.
This code is taken from the IssueTrackerProduct and modified """