PythonUtil.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  1. import types
  2. import string
  3. import re
  4. import math
  5. import operator
  6. import inspect
  7. import os
  8. import sys
  9. import random
  10. import time
  11. import new
  12. if __debug__:
  13. import traceback
  14. from direct.directutil import Verify
  15. ScalarTypes = (types.FloatType, types.IntType, types.LongType)
  16. def enumerate(L):
  17. """Returns (0, L[0]), (1, L[1]), etc., allowing this syntax:
  18. for i, item in enumerate(L):
  19. ...
  20. enumerate is a built-in feature in Python 2.3, which implements it
  21. using an iterator. For now, we can use this quick & dirty
  22. implementation that returns a list of tuples that is completely
  23. constructed every time enumerate() is called.
  24. """
  25. return zip(xrange(len(L)), L)
  26. import __builtin__
  27. if not hasattr(__builtin__, 'enumerate'):
  28. __builtin__.enumerate = enumerate
  29. def unique(L1, L2):
  30. """Return a list containing all items in 'L1' that are not in 'L2'"""
  31. L2 = dict([(k, None) for k in L2])
  32. return [item for item in L1 if item not in L2]
  33. def indent(stream, numIndents, str):
  34. """
  35. Write str to stream with numIndents in front of it
  36. """
  37. # To match emacs, instead of a tab character we will use 4 spaces
  38. stream.write(' ' * numIndents + str)
  39. def nonRepeatingRandomList(vals, max):
  40. random.seed(time.time())
  41. #first generate a set of random values
  42. valueList=range(max)
  43. finalVals=[]
  44. for i in range(vals):
  45. index=int(random.random()*len(valueList))
  46. finalVals.append(valueList[index])
  47. valueList.remove(valueList[index])
  48. return finalVals
  49. def writeFsmTree(instance, indent = 0):
  50. if hasattr(instance, 'parentFSM'):
  51. writeFsmTree(instance.parentFSM, indent-2)
  52. elif hasattr(instance, 'fsm'):
  53. name = ''
  54. if hasattr(instance.fsm, 'state'):
  55. name = instance.fsm.state.name
  56. print "%s: %s"%(instance.fsm.name, name)
  57. #if __debug__: #RAU accdg to Darren its's ok that StackTrace is not protected by __debug__
  58. # DCR if somebody ends up using StackTrace in production, either
  59. # A) it will be OK because it hardly ever gets called, or
  60. # B) it will be easy to track it down (grep for StackTrace)
  61. class StackTrace:
  62. def __init__(self, label="", start=0, limit=None):
  63. """
  64. label is a string (or anything that be be a string)
  65. that is printed as part of the trace back.
  66. This is just to make it easier to tell what the
  67. stack trace is referring to.
  68. start is an integer number of stack frames back
  69. from the most recent. (This is automatically
  70. bumped up by one to skip the __init__ call
  71. to the StackTrace).
  72. limit is an integer number of stack frames
  73. to record (or None for unlimited).
  74. """
  75. self.label = label
  76. if limit is not None:
  77. self.trace = traceback.extract_stack(sys._getframe(1+start),
  78. limit=limit)
  79. else:
  80. self.trace = traceback.extract_stack(sys._getframe(1+start))
  81. def __str__(self):
  82. r = "Debug stack trace of %s (back %s frames):\n"%(
  83. self.label, len(self.trace),)
  84. for i in traceback.format_list(self.trace):
  85. r+=i
  86. return r
  87. #-----------------------------------------------------------------------------
  88. def traceFunctionCall(frame):
  89. """
  90. return a string that shows the call frame with calling arguments.
  91. e.g.
  92. foo(x=234, y=135)
  93. """
  94. f = frame
  95. co = f.f_code
  96. dict = f.f_locals
  97. n = co.co_argcount
  98. if co.co_flags & 4: n = n+1
  99. if co.co_flags & 8: n = n+1
  100. r=''
  101. if dict.has_key('self'):
  102. r = '%s.'%(dict['self'].__class__.__name__,)
  103. r+="%s("%(f.f_code.co_name,)
  104. comma=0 # formatting, whether we should type a comma.
  105. for i in range(n):
  106. name = co.co_varnames[i]
  107. if name=='self':
  108. continue
  109. if comma:
  110. r+=', '
  111. else:
  112. # ok, we skipped the first one, the rest get commas:
  113. comma=1
  114. r+=name
  115. r+='='
  116. if dict.has_key(name):
  117. v=str(dict[name])
  118. if len(v)>2000:
  119. # r+="<too big for debug>"
  120. r += (str(dict[name])[:2000] + "...")
  121. else:
  122. r+=str(dict[name])
  123. else: r+="*** undefined ***"
  124. return r+')'
  125. def traceParentCall():
  126. return traceFunctionCall(sys._getframe(2))
  127. def printThisCall():
  128. print traceFunctionCall(sys._getframe(1))
  129. return 1 # to allow "assert printThisCall()"
  130. if __debug__:
  131. def lineage(obj, verbose=0, indent=0):
  132. """
  133. return instance or class name in as a multiline string.
  134. Usage: print lineage(foo)
  135. (Based on getClassLineage())
  136. """
  137. r=""
  138. if type(obj) == types.ListType:
  139. r+=(" "*indent)+"python list\n"
  140. elif type(obj) == types.DictionaryType:
  141. r+=(" "*indent)+"python dictionary\n"
  142. elif type(obj) == types.ModuleType:
  143. r+=(" "*indent)+str(obj)+"\n"
  144. elif type(obj) == types.InstanceType:
  145. r+=lineage(obj.__class__, verbose, indent)
  146. elif type(obj) == types.ClassType:
  147. r+=(" "*indent)
  148. if verbose:
  149. r+=obj.__module__+"."
  150. r+=obj.__name__+"\n"
  151. for c in obj.__bases__:
  152. r+=lineage(c, verbose, indent+2)
  153. return r
  154. def tron():
  155. sys.settrace(trace)
  156. def trace(frame, event, arg):
  157. if event == 'line':
  158. pass
  159. elif event == 'call':
  160. print traceFunctionCall(sys._getframe(1))
  161. elif event == 'return':
  162. print "returning"
  163. elif event == 'exception':
  164. print "exception"
  165. return trace
  166. def troff():
  167. sys.settrace(None)
  168. #-----------------------------------------------------------------------------
  169. def getClassLineage(obj):
  170. """
  171. print object inheritance list
  172. """
  173. if type(obj) == types.DictionaryType:
  174. # Just a dictionary, return dictionary
  175. return [obj]
  176. elif (type(obj) == types.InstanceType):
  177. # Instance, make a list with the instance and its class interitance
  178. return [obj] + getClassLineage(obj.__class__)
  179. elif ((type(obj) == types.ClassType) or
  180. (type(obj) == types.TypeType)):
  181. # Class or type, see what it derives from
  182. lineage = [obj]
  183. for c in obj.__bases__:
  184. lineage = lineage + getClassLineage(c)
  185. return lineage
  186. # New FFI objects are types that are not defined.
  187. # but they still act like classes
  188. elif hasattr(obj, '__class__'):
  189. # Instance, make a list with the instance and its class interitance
  190. return [obj] + getClassLineage(obj.__class__)
  191. else:
  192. # Not what I'm looking for
  193. return []
  194. def pdir(obj, str = None, width = None,
  195. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  196. # Remove redundant class entries
  197. uniqueLineage = []
  198. for l in getClassLineage(obj):
  199. if type(l) == types.ClassType:
  200. if l in uniqueLineage:
  201. break
  202. uniqueLineage.append(l)
  203. # Pretty print out directory info
  204. uniqueLineage.reverse()
  205. for obj in uniqueLineage:
  206. _pdir(obj, str, width, fTruncate, lineWidth, wantPrivate)
  207. print
  208. def _pdir(obj, str = None, width = None,
  209. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  210. """
  211. Print out a formatted list of members and methods of an instance or class
  212. """
  213. def printHeader(name):
  214. name = ' ' + name + ' '
  215. length = len(name)
  216. if length < 70:
  217. padBefore = int((70 - length)/2.0)
  218. padAfter = max(0, 70 - length - padBefore)
  219. header = '*' * padBefore + name + '*' * padAfter
  220. print header
  221. print
  222. def printInstanceHeader(i, printHeader = printHeader):
  223. printHeader(i.__class__.__name__ + ' INSTANCE INFO')
  224. def printClassHeader(c, printHeader = printHeader):
  225. printHeader(c.__name__ + ' CLASS INFO')
  226. def printDictionaryHeader(d, printHeader = printHeader):
  227. printHeader('DICTIONARY INFO')
  228. # Print Header
  229. if type(obj) == types.InstanceType:
  230. printInstanceHeader(obj)
  231. elif type(obj) == types.ClassType:
  232. printClassHeader(obj)
  233. elif type (obj) == types.DictionaryType:
  234. printDictionaryHeader(obj)
  235. # Get dict
  236. if type(obj) == types.DictionaryType:
  237. dict = obj
  238. # FFI objects are builtin types, they have no __dict__
  239. elif not hasattr(obj, '__dict__'):
  240. dict = {}
  241. else:
  242. dict = obj.__dict__
  243. # Adjust width
  244. if width:
  245. maxWidth = width
  246. else:
  247. maxWidth = 10
  248. keyWidth = 0
  249. aproposKeys = []
  250. privateKeys = []
  251. remainingKeys = []
  252. for key in dict.keys():
  253. if not width:
  254. keyWidth = len(key)
  255. if str:
  256. if re.search(str, key, re.I):
  257. aproposKeys.append(key)
  258. if (not width) and (keyWidth > maxWidth):
  259. maxWidth = keyWidth
  260. else:
  261. if key[:1] == '_':
  262. if wantPrivate:
  263. privateKeys.append(key)
  264. if (not width) and (keyWidth > maxWidth):
  265. maxWidth = keyWidth
  266. else:
  267. remainingKeys.append(key)
  268. if (not width) and (keyWidth > maxWidth):
  269. maxWidth = keyWidth
  270. # Sort appropriate keys
  271. if str:
  272. aproposKeys.sort()
  273. else:
  274. privateKeys.sort()
  275. remainingKeys.sort()
  276. # Print out results
  277. if wantPrivate:
  278. keys = aproposKeys + privateKeys + remainingKeys
  279. else:
  280. keys = aproposKeys + remainingKeys
  281. format = '%-' + `maxWidth` + 's'
  282. for key in keys:
  283. value = dict[key]
  284. if callable(value):
  285. strvalue = `Signature(value)`
  286. else:
  287. strvalue = `value`
  288. if fTruncate:
  289. # Cut off line (keeping at least 1 char)
  290. strvalue = strvalue[:max(1, lineWidth - maxWidth)]
  291. print (format % key)[:maxWidth] + '\t' + strvalue
  292. # Magic numbers: These are the bit masks in func_code.co_flags that
  293. # reveal whether or not the function has a *arg or **kw argument.
  294. _POS_LIST = 4
  295. _KEY_DICT = 8
  296. def _is_variadic(function):
  297. return function.func_code.co_flags & _POS_LIST
  298. def _has_keywordargs(function):
  299. return function.func_code.co_flags & _KEY_DICT
  300. def _varnames(function):
  301. return function.func_code.co_varnames
  302. def _getcode(f):
  303. """
  304. _getcode(f)
  305. This function returns the name and function object of a callable
  306. object.
  307. """
  308. def method_get(f):
  309. return f.__name__, f.im_func
  310. def function_get(f):
  311. return f.__name__, f
  312. def instance_get(f):
  313. if hasattr(f, '__call__'):
  314. method = f.__call__
  315. if (type(method) == types.MethodType):
  316. func = method.im_func
  317. else:
  318. func = method
  319. return ("%s%s" % (f.__class__.__name__, '__call__'), func)
  320. else:
  321. s = ("Instance %s of class %s does not have a __call__ method" %
  322. (f, f.__class__.__name__))
  323. raise TypeError, s
  324. def class_get(f):
  325. if hasattr(f, '__init__'):
  326. return f.__name__, f.__init__.im_func
  327. else:
  328. return f.__name__, lambda: None
  329. codedict = { types.UnboundMethodType: method_get,
  330. types.MethodType: method_get,
  331. types.FunctionType: function_get,
  332. types.InstanceType: instance_get,
  333. types.ClassType: class_get,
  334. }
  335. try:
  336. return codedict[type(f)](f)
  337. except KeyError:
  338. if callable(f): # eg, built-in functions and methods
  339. # raise ValueError, "type %s not supported yet." % type(f)
  340. return f.__name__, None
  341. else:
  342. raise TypeError, ("object %s of type %s is not callable." %
  343. (f, type(f)))
  344. class Signature:
  345. def __init__(self, func):
  346. self.type = type(func)
  347. self.name, self.func = _getcode(func)
  348. def ordinary_args(self):
  349. n = self.func.func_code.co_argcount
  350. return _varnames(self.func)[0:n]
  351. def special_args(self):
  352. n = self.func.func_code.co_argcount
  353. x = {}
  354. #
  355. if _is_variadic(self.func):
  356. x['positional'] = _varnames(self.func)[n]
  357. if _has_keywordargs(self.func):
  358. x['keyword'] = _varnames(self.func)[n+1]
  359. elif _has_keywordargs(self.func):
  360. x['keyword'] = _varnames(self.func)[n]
  361. else:
  362. pass
  363. return x
  364. def full_arglist(self):
  365. base = list(self.ordinary_args())
  366. x = self.special_args()
  367. if x.has_key('positional'):
  368. base.append(x['positional'])
  369. if x.has_key('keyword'):
  370. base.append(x['keyword'])
  371. return base
  372. def defaults(self):
  373. defargs = self.func.func_defaults
  374. args = self.ordinary_args()
  375. mapping = {}
  376. if defargs is not None:
  377. for i in range(-1, -(len(defargs)+1), -1):
  378. mapping[args[i]] = defargs[i]
  379. else:
  380. pass
  381. return mapping
  382. def __repr__(self):
  383. if self.func:
  384. defaults = self.defaults()
  385. specials = self.special_args()
  386. l = []
  387. for arg in self.ordinary_args():
  388. if defaults.has_key(arg):
  389. l.append(arg + '=' + str(defaults[arg]))
  390. else:
  391. l.append(arg)
  392. if specials.has_key('positional'):
  393. l.append('*' + specials['positional'])
  394. if specials.has_key('keyword'):
  395. l.append('**' + specials['keyword'])
  396. return "%s(%s)" % (self.name, string.join(l, ', '))
  397. else:
  398. return "%s(?)" % self.name
  399. def doc(obj):
  400. if (isinstance(obj, types.MethodType)) or \
  401. (isinstance(obj, types.FunctionType)):
  402. print obj.__doc__
  403. def adjust(command = None, dim = 1, parent = None, **kw):
  404. """
  405. adjust(command = None, parent = None, **kw)
  406. Popup and entry scale to adjust a parameter
  407. Accepts any Slider keyword argument. Typical arguments include:
  408. command: The one argument command to execute
  409. min: The min value of the slider
  410. max: The max value of the slider
  411. resolution: The resolution of the slider
  412. text: The label on the slider
  413. These values can be accessed and/or changed after the fact
  414. >>> vg = adjust()
  415. >>> vg['min']
  416. 0.0
  417. >>> vg['min'] = 10.0
  418. >>> vg['min']
  419. 10.0
  420. """
  421. # Make sure we enable Tk
  422. from direct.tkwidgets import Valuator
  423. # Set command if specified
  424. if command:
  425. kw['command'] = lambda x: apply(command, x)
  426. if parent is None:
  427. kw['title'] = command.__name__
  428. kw['dim'] = dim
  429. # Create toplevel if needed
  430. if not parent:
  431. vg = apply(Valuator.ValuatorGroupPanel, (parent,), kw)
  432. else:
  433. vg = apply(Valuator.ValuatorGroup, (parent,), kw)
  434. vg.pack(expand = 1, fill = 'x')
  435. return vg
  436. def difference(a, b):
  437. """
  438. difference(list, list):
  439. """
  440. if not a: return b
  441. if not b: return a
  442. d = []
  443. for i in a:
  444. if (i not in b) and (i not in d):
  445. d.append(i)
  446. for i in b:
  447. if (i not in a) and (i not in d):
  448. d.append(i)
  449. return d
  450. def intersection(a, b):
  451. """
  452. intersection(list, list):
  453. """
  454. if not a: return []
  455. if not b: return []
  456. d = []
  457. for i in a:
  458. if (i in b) and (i not in d):
  459. d.append(i)
  460. for i in b:
  461. if (i in a) and (i not in d):
  462. d.append(i)
  463. return d
  464. def union(a, b):
  465. """
  466. union(list, list):
  467. """
  468. # Copy a
  469. c = a[:]
  470. for i in b:
  471. if (i not in c):
  472. c.append(i)
  473. return c
  474. def sameElements(a, b):
  475. if len(a) != len(b):
  476. return 0
  477. for elem in a:
  478. if elem not in b:
  479. return 0
  480. for elem in b:
  481. if elem not in a:
  482. return 0
  483. return 1
  484. def makeList(x):
  485. """returns x, converted to a list"""
  486. if type(x) is types.ListType:
  487. return x
  488. elif type(x) is types.TupleType:
  489. return list(x)
  490. else:
  491. return [x,]
  492. def makeTuple(x):
  493. """returns x, converted to a tuple"""
  494. if type(x) is types.ListType:
  495. return tuple(x)
  496. elif type(x) is types.TupleType:
  497. return x
  498. else:
  499. return (x,)
  500. def list2dict(L, value=None):
  501. """creates dict using elements of list, all assigned to same value"""
  502. return dict([(k, value) for k in L])
  503. def invertDict(D, lossy=False):
  504. """creates a dictionary by 'inverting' D; keys are placed in the new
  505. dictionary under their corresponding value in the old dictionary.
  506. It is an error if D contains any duplicate values.
  507. >>> old = {'key1':1, 'key2':2}
  508. >>> invertDict(old)
  509. {1: 'key1', 2: 'key2'}
  510. """
  511. n = {}
  512. for key, value in D.items():
  513. if not lossy and value in n:
  514. raise 'duplicate key in invertDict: %s' % value
  515. n[value] = key
  516. return n
  517. def invertDictLossless(D):
  518. """similar to invertDict, but values of new dict are lists of keys from
  519. old dict. No information is lost.
  520. >>> old = {'key1':1, 'key2':2, 'keyA':2}
  521. >>> invertDictLossless(old)
  522. {1: ['key1'], 2: ['key2', 'keyA']}
  523. """
  524. n = {}
  525. for key, value in D.items():
  526. n.setdefault(value, [])
  527. n[value].append(key)
  528. return n
  529. def uniqueElements(L):
  530. """are all elements of list unique?"""
  531. return len(L) == len(list2dict(L))
  532. def disjoint(L1, L2):
  533. """returns non-zero if L1 and L2 have no common elements"""
  534. used = dict([(k, None) for k in L1])
  535. for k in L2:
  536. if k in used:
  537. return 0
  538. return 1
  539. def contains(whole, sub):
  540. """
  541. Return 1 if whole contains sub, 0 otherwise
  542. """
  543. if (whole == sub):
  544. return 1
  545. for elem in sub:
  546. # The first item you find not in whole, return 0
  547. if elem not in whole:
  548. return 0
  549. # If you got here, whole must contain sub
  550. return 1
  551. def replace(list, old, new, all=0):
  552. """
  553. replace 'old' with 'new' in 'list'
  554. if all == 0, replace first occurrence
  555. otherwise replace all occurrences
  556. returns the number of items replaced
  557. """
  558. if old not in list:
  559. return 0
  560. if not all:
  561. i = list.index(old)
  562. list[i] = new
  563. return 1
  564. else:
  565. numReplaced = 0
  566. for i in xrange(len(list)):
  567. if list[i] == old:
  568. numReplaced += 1
  569. list[i] = new
  570. return numReplaced
  571. def reduceAngle(deg):
  572. """
  573. Reduces an angle (in degrees) to a value in [-180..180)
  574. """
  575. return (((deg + 180.) % 360.) - 180.)
  576. def fitSrcAngle2Dest(src, dest):
  577. """
  578. given a src and destination angle, returns an equivalent src angle
  579. that is within [-180..180) of dest
  580. examples:
  581. fitSrcAngle2Dest(30, 60) == 30
  582. fitSrcAngle2Dest(60, 30) == 60
  583. fitSrcAngle2Dest(0, 180) == 0
  584. fitSrcAngle2Dest(-1, 180) == 359
  585. fitSrcAngle2Dest(-180, 180) == 180
  586. """
  587. return dest + reduceAngle(src - dest)
  588. def fitDestAngle2Src(src, dest):
  589. """
  590. given a src and destination angle, returns an equivalent dest angle
  591. that is within [-180..180) of src
  592. examples:
  593. fitDestAngle2Src(30, 60) == 60
  594. fitDestAngle2Src(60, 30) == 30
  595. fitDestAngle2Src(0, 180) == -180
  596. fitDestAngle2Src(1, 180) == 180
  597. """
  598. return src + (reduceAngle(dest - src))
  599. def closestDestAngle2(src, dest):
  600. # The function above didn't seem to do what I wanted. So I hacked
  601. # this one together. I can't really say I understand it. It's more
  602. # from impirical observation... GRW
  603. diff = src - dest
  604. if diff > 180:
  605. # if the difference is greater that 180 it's shorter to go the other way
  606. return dest - 360
  607. elif diff < -180:
  608. # or perhaps the OTHER other way...
  609. return dest + 360
  610. else:
  611. # otherwise just go to the original destination
  612. return dest
  613. def closestDestAngle(src, dest):
  614. # The function above didn't seem to do what I wanted. So I hacked
  615. # this one together. I can't really say I understand it. It's more
  616. # from impirical observation... GRW
  617. diff = src - dest
  618. if diff > 180:
  619. # if the difference is greater that 180 it's shorter to go the other way
  620. return src - (diff - 360)
  621. elif diff < -180:
  622. # or perhaps the OTHER other way...
  623. return src - (360 + diff)
  624. else:
  625. # otherwise just go to the original destination
  626. return dest
  627. def binaryRepr(number, max_length = 32):
  628. # This will only work reliably for relatively small numbers.
  629. # Increase the value of max_length if you think you're going
  630. # to use long integers
  631. assert number < 2L << max_length
  632. shifts = map (operator.rshift, max_length * [number], \
  633. range (max_length - 1, -1, -1))
  634. digits = map (operator.mod, shifts, max_length * [2])
  635. if not digits.count (1): return 0
  636. digits = digits [digits.index (1):]
  637. return string.join (map (repr, digits), '')
  638. # constant profile defaults
  639. PyUtilProfileDefaultFilename = 'profiledata'
  640. PyUtilProfileDefaultLines = 80
  641. PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
  642. def profile(callback, name, terse):
  643. import __builtin__
  644. if 'globalProfileFunc' in __builtin__.__dict__:
  645. # rats. Python profiler is not re-entrant...
  646. base.notify.warning(
  647. 'PythonUtil.profileStart(%s): aborted, already profiling %s'
  648. #'\nStack Trace:\n%s'
  649. % (name, __builtin__.globalProfileFunc,
  650. #StackTrace()
  651. ))
  652. return
  653. __builtin__.globalProfileFunc = callback
  654. print '***** START PROFILE: %s *****' % name
  655. startProfile(cmd='globalProfileFunc()', callInfo=(not terse))
  656. print '***** END PROFILE: %s *****' % name
  657. del __builtin__.__dict__['globalProfileFunc']
  658. def profiled(category, terse=False):
  659. """ decorator for profiling functions
  660. turn categories on and off via "want-profile-categoryName 1"
  661. e.g.
  662. @profiled('particles')
  663. def loadParticles():
  664. ...
  665. """
  666. assert type(category) is types.StringType, "must provide a category name for @profiled"
  667. if not __dev__:
  668. # if we're not in __dev__, just return the function itself. This
  669. # results in zero runtime overhead, since decorators are evaluated
  670. # at module-load.
  671. def nullDecorator(f):
  672. return f
  673. return nullDecorator
  674. def profileDecorator(f):
  675. def _profiled(*args, **kArgs):
  676. #import pdb;pdb.set_trace()
  677. # must do this in here because we don't have base/simbase
  678. # at the time that PythonUtil is loaded
  679. name = '(%s) %s from %s' % (category, f.func_name, f.__module__)
  680. try:
  681. _base = base
  682. except:
  683. _base = simbase
  684. if _base.config.GetBool('want-profile-%s' % category, 0):
  685. return profile(Functor(f, *args, **kArgs), name, terse)
  686. else:
  687. return f(*args, **kArgs)
  688. #import pdb;pdb.set_trace()
  689. _profiled.__doc__ = f.__doc__
  690. return _profiled
  691. return profileDecorator
  692. # call this from the prompt, and break back out to the prompt
  693. # to stop profiling
  694. #
  695. # OR to do inline profiling, you must make a globally-visible
  696. # function to be profiled, i.e. to profile 'self.load()', do
  697. # something like this:
  698. #
  699. # def func(self=self):
  700. # self.load()
  701. # import __builtin__
  702. # __builtin__.func = func
  703. # PythonUtil.startProfile(cmd='func()', filename='profileData')
  704. # del __builtin__.func
  705. #
  706. def startProfile(filename=PyUtilProfileDefaultFilename,
  707. lines=PyUtilProfileDefaultLines,
  708. sorts=PyUtilProfileDefaultSorts,
  709. silent=0,
  710. callInfo=1,
  711. cmd='run()'):
  712. # uniquify the filename to allow multiple processes to profile simultaneously
  713. filename = '%s.%s' % (filename, randUint31())
  714. import profile
  715. profile.run(cmd, filename)
  716. if not silent:
  717. printProfile(filename, lines, sorts, callInfo)
  718. import os
  719. os.remove(filename)
  720. # call this to see the results again
  721. def printProfile(filename=PyUtilProfileDefaultFilename,
  722. lines=PyUtilProfileDefaultLines,
  723. sorts=PyUtilProfileDefaultSorts,
  724. callInfo=1):
  725. import pstats
  726. s = pstats.Stats(filename)
  727. s.strip_dirs()
  728. for sort in sorts:
  729. s.sort_stats(sort)
  730. s.print_stats(lines)
  731. if callInfo:
  732. s.print_callees(lines)
  733. s.print_callers(lines)
  734. def getSetterName(valueName, prefix='set'):
  735. # getSetterName('color') -> 'setColor'
  736. # getSetterName('color', 'get') -> 'getColor'
  737. return '%s%s%s' % (prefix, string.upper(valueName[0]), valueName[1:])
  738. def getSetter(targetObj, valueName, prefix='set'):
  739. # getSetter(smiley, 'pos') -> smiley.setPos
  740. return getattr(targetObj, getSetterName(valueName, prefix))
  741. class Functor:
  742. def __init__(self, function, *args, **kargs):
  743. assert callable(function), "function should be a callable obj"
  744. self._function = function
  745. self._args = args
  746. self._kargs = kargs
  747. self.__name__ = 'Functor: %s' % self._function.__name__
  748. self.__doc__ = self._function.__doc__
  749. def destroy(self):
  750. del self._function
  751. del self._args
  752. del self._kargs
  753. del self.__name__
  754. del self.__doc__
  755. def __call__(self, *args, **kargs):
  756. """call function"""
  757. _args = list(self._args)
  758. _args.extend(args)
  759. _kargs = self._kargs.copy()
  760. _kargs.update(kargs)
  761. return apply(self._function, _args, _kargs)
  762. def __repr__(self):
  763. s = 'Functor(%s' % self._function.__name__
  764. for arg in self._args:
  765. try:
  766. argStr = repr(arg)
  767. except:
  768. argStr = 'bad repr: %s' % arg.__class__
  769. s += ', %s' % argStr
  770. for karg, value in self._kargs.items():
  771. s += ', %s=%s' % (karg, repr(value))
  772. s += ')'
  773. return s
  774. class Stack:
  775. def __init__(self):
  776. self.__list = []
  777. def push(self, item):
  778. self.__list.append(item)
  779. def top(self):
  780. # return the item on the top of the stack without popping it off
  781. return self.__list[-1]
  782. def pop(self):
  783. return self.__list.pop()
  784. def clear(self):
  785. self.__list = []
  786. def isEmpty(self):
  787. return len(self.__list) == 0
  788. def __len__(self):
  789. return len(self.__list)
  790. class Queue:
  791. # FIFO queue
  792. # interface is intentionally identical to Stack (LIFO)
  793. def __init__(self):
  794. self.__list = []
  795. def push(self, item):
  796. self.__list.append(item)
  797. def top(self):
  798. # return the next item at the front of the queue without popping it off
  799. return self.__list[0]
  800. def pop(self):
  801. return self.__list.pop(0)
  802. def clear(self):
  803. self.__list = []
  804. def isEmpty(self):
  805. return len(self.__list) == 0
  806. def __len__(self):
  807. return len(self.__list)
  808. if __debug__:
  809. q = Queue()
  810. assert q.isEmpty()
  811. q.clear()
  812. assert q.isEmpty()
  813. q.push(10)
  814. assert not q.isEmpty()
  815. q.push(20)
  816. assert not q.isEmpty()
  817. assert len(q) == 2
  818. assert q.top() == 10
  819. assert q.top() == 10
  820. assert q.pop() == 10
  821. assert len(q) == 1
  822. assert not q.isEmpty()
  823. assert q.pop() == 20
  824. assert len(q) == 0
  825. assert q.isEmpty()
  826. """
  827. ParamObj/ParamSet
  828. =================
  829. These two classes support you in the definition of a formal set of
  830. parameters for an object type. The parameters may be safely queried/set on
  831. an object instance at any time, and the object will react to newly-set
  832. values immediately.
  833. ParamSet & ParamObj also provide a mechanism for atomically setting
  834. multiple parameter values before allowing the object to react to any of the
  835. new values--useful when two or more parameters are interdependent and there
  836. is risk of setting an illegal combination in the process of applying a new
  837. set of values.
  838. To make use of these classes, derive your object from ParamObj. Then define
  839. a 'ParamSet' subclass that derives from the parent class' 'ParamSet' class,
  840. and define the object's parameters within its ParamSet class. (see examples
  841. below)
  842. The ParamObj base class provides 'get' and 'set' functions for each
  843. parameter if they are not defined. These default implementations
  844. respectively set the parameter value directly on the object, and expect the
  845. value to be available in that location for retrieval.
  846. Classes that derive from ParamObj can optionally declare a 'get' and 'set'
  847. function for each parameter. The setter should simply store the value in a
  848. location where the getter can find it; it should not do any further
  849. processing based on the new parameter value. Further processing should be
  850. implemented in an 'apply' function. The applier function is optional, and
  851. there is no default implementation.
  852. NOTE: the previous value of a parameter is available inside an apply
  853. function as 'self.getPriorValue()'
  854. The ParamSet class declaration lists the parameters and defines a default
  855. value for each. ParamSet instances represent a complete set of parameter
  856. values. A ParamSet instance created with no constructor arguments will
  857. contain the default values for each parameter. The defaults may be
  858. overriden by passing keyword arguments to the ParamSet's constructor. If a
  859. ParamObj instance is passed to the constructor, the ParamSet will extract
  860. the object's current parameter values.
  861. ParamSet.applyTo(obj) sets all of its parameter values on 'obj'.
  862. SETTERS AND APPLIERS
  863. ====================
  864. Under normal conditions, a call to a setter function, i.e.
  865. cam.setFov(90)
  866. will actually result in the following calls being made:
  867. cam.setFov(90)
  868. cam.applyFov()
  869. Calls to several setter functions, i.e.
  870. cam.setFov(90)
  871. cam.setViewType('cutscene')
  872. will result in this call sequence:
  873. cam.setFov(90)
  874. cam.applyFov()
  875. cam.setViewType('cutscene')
  876. cam.applyViewType()
  877. Suppose that you desire the view type to already be set to 'cutscene' at
  878. the time when applyFov() is called. You could reverse the order of the set
  879. calls, but suppose that you also want the fov to be set properly at the
  880. time when applyViewType() is called.
  881. In this case, you can 'lock' the params, i.e.
  882. cam.lockParams()
  883. cam.setFov(90)
  884. cam.setViewType('cutscene')
  885. cam.unlockParams()
  886. This will result in the following call sequence:
  887. cam.setFov(90)
  888. cam.setViewType('cutscene')
  889. cam.applyFov()
  890. cam.applyViewType()
  891. NOTE: Currently the order of the apply calls following an unlock is not
  892. guaranteed.
  893. EXAMPLE CLASSES
  894. ===============
  895. Here is an example of a class that uses ParamSet/ParamObj to manage its
  896. parameters:
  897. class Camera(ParamObj):
  898. class ParamSet(ParamObj.ParamSet):
  899. Params = {
  900. 'viewType': 'normal',
  901. 'fov': 60,
  902. }
  903. ...
  904. def getViewType(self):
  905. return self.viewType
  906. def setViewType(self, viewType):
  907. self.viewType = viewType
  908. def applyViewType(self):
  909. if self.viewType == 'normal':
  910. ...
  911. def getFov(self):
  912. return self.fov
  913. def setFov(self, fov):
  914. self.fov = fov
  915. def applyFov(self):
  916. base.camera.setFov(self.fov)
  917. ...
  918. EXAMPLE USAGE
  919. =============
  920. cam = Camera()
  921. ...
  922. # set up for the cutscene
  923. savedSettings = cam.ParamSet(cam)
  924. cam.setViewType('closeup')
  925. cam.setFov(90)
  926. ...
  927. # cutscene is over, set the camera back
  928. savedSettings.applyTo(cam)
  929. del savedSettings
  930. """
  931. class ParamObj:
  932. # abstract base for classes that want to support a formal parameter
  933. # set whose values may be queried, changed, 'bulk' changed, and
  934. # extracted/stored/applied all at once (see documentation above)
  935. # ParamSet subclass: container of parameter values. Derived class must
  936. # derive a new ParamSet class if they wish to define new params. See
  937. # documentation above.
  938. class ParamSet:
  939. Params = {
  940. # base class does not define any parameters, but they would
  941. # appear here as 'name': value,
  942. }
  943. def __init__(self, *args, **kwArgs):
  944. self.__class__._compileDefaultParams()
  945. if len(args) == 1 and len(kwArgs) == 0:
  946. # extract our params from an existing ParamObj instance
  947. obj = args[0]
  948. self.paramVals = {}
  949. for param in self.getParams():
  950. self.paramVals[param] = getSetter(obj, param, 'get')()
  951. else:
  952. assert len(args) == 0
  953. if __debug__:
  954. for arg in kwArgs.keys():
  955. assert arg in self.getParams()
  956. self.paramVals = dict(kwArgs)
  957. def getValue(self, param):
  958. if param in self.paramVals:
  959. return self.paramVals[param]
  960. return self._Params[param]
  961. def applyTo(self, obj):
  962. # Apply our entire set of params to a ParamObj
  963. obj.lockParams()
  964. for param in self.getParams():
  965. getSetter(obj, param)(self.getValue(param))
  966. obj.unlockParams()
  967. # CLASS METHODS
  968. def getParams(cls):
  969. # returns safely-mutable list of param names
  970. cls._compileDefaultParams()
  971. return cls._Params.keys()
  972. getParams = classmethod(getParams)
  973. def getDefaultValue(cls, param):
  974. cls._compileDefaultParams()
  975. return cls._Params[param]
  976. getDefaultValue = classmethod(getDefaultValue)
  977. def _compileDefaultParams(cls):
  978. if cls.__dict__.has_key('_Params'):
  979. # we've already compiled the defaults for this class
  980. return
  981. bases = list(cls.__bases__)
  982. # bring less-derived classes to the front
  983. mostDerivedLast(bases)
  984. cls._Params = {}
  985. for c in (bases + [cls]):
  986. # make sure this base has its dict of param defaults
  987. c._compileDefaultParams()
  988. if c.__dict__.has_key('Params'):
  989. # apply this class' default param values to our dict
  990. cls._Params.update(c.Params)
  991. _compileDefaultParams = classmethod(_compileDefaultParams)
  992. # END PARAMSET SUBCLASS
  993. def __init__(self, *args, **kwArgs):
  994. assert issubclass(self.ParamSet, ParamObj.ParamSet)
  995. # If you pass in a ParamSet obj, its values will be applied to this
  996. # object in the constructor.
  997. params = None
  998. if len(args) == 1 and len(kwArgs) == 0:
  999. # if there's one argument, assume that it's a ParamSet
  1000. params = args[0]
  1001. elif len(kwArgs) > 0:
  1002. assert len(args) == 0
  1003. # if we've got keyword arguments, make a ParamSet out of them
  1004. params = self.ParamSet(**kwArgs)
  1005. self._paramLockRefCount = 0
  1006. # this holds dictionaries of parameter values prior to the set that we
  1007. # are performing
  1008. self._priorValuesStack = Stack()
  1009. # this holds the name of the parameter that we are currently modifying
  1010. # at the top of the stack
  1011. self._curParamStack = Stack()
  1012. def setterStub(param, setterFunc, self,
  1013. value):
  1014. # should we apply the value now or should we wait?
  1015. # if this obj's params are locked, we track which values have
  1016. # been set, and on unlock, we'll call the applyers for those
  1017. # values
  1018. if self._paramLockRefCount > 0:
  1019. setterFunc(value)
  1020. priorValues = self._priorValuesStack.top()
  1021. if param not in priorValues:
  1022. try:
  1023. priorValue = getSetter(self, param, 'get')()
  1024. except:
  1025. priorValue = None
  1026. priorValues[param] = priorValue
  1027. self._paramsSet[param] = None
  1028. else:
  1029. # prepare for call to getPriorValue
  1030. self._priorValuesStack.push({
  1031. param: getSetter(self, param, 'get')()
  1032. })
  1033. setterFunc(value)
  1034. # call the applier, if there is one
  1035. applier = getattr(self, getSetterName(param, 'apply'), None)
  1036. if applier is not None:
  1037. self._curParamStack.push(param)
  1038. applier()
  1039. self._curParamStack.pop()
  1040. self._priorValuesStack.pop()
  1041. if hasattr(self, 'handleParamChange'):
  1042. self.handleParamChange((param,))
  1043. # insert stub funcs for param setters
  1044. for param in self.ParamSet.getParams():
  1045. setterName = getSetterName(param)
  1046. getterName = getSetterName(param, 'get')
  1047. # is there a setter defined?
  1048. if not hasattr(self, setterName):
  1049. # no; provide the default
  1050. def defaultSetter(self, value, param=param):
  1051. setattr(self, param, value)
  1052. self.__class__.__dict__[setterName] = defaultSetter
  1053. # is there a getter defined?
  1054. if not hasattr(self, getterName):
  1055. # no; provide the default. If there is no value set, return
  1056. # the default
  1057. def defaultGetter(self, param=param,
  1058. default=self.ParamSet.getDefaultValue(param)):
  1059. return getattr(self, param, default)
  1060. self.__class__.__dict__[getterName] = defaultGetter
  1061. # grab a reference to the setter
  1062. setterFunc = getattr(self, setterName)
  1063. # if the setter is a direct member of this instance, move the setter
  1064. # aside
  1065. if setterName in self.__dict__:
  1066. self.__dict__[setterName + '_MOVED'] = self.__dict__[setterName]
  1067. setterFunc = self.__dict__[setterName]
  1068. # install a setter stub that will a) call the real setter and
  1069. # then the applier, or b) call the setter and queue the
  1070. # applier, depending on whether our params are locked
  1071. self.__dict__[setterName] = Functor(setterStub, param,
  1072. setterFunc, self)
  1073. if params is not None:
  1074. params.applyTo(self)
  1075. def destroy(self):
  1076. for param in self.ParamSet.getParams():
  1077. setterName = getSetterName(param)
  1078. self.__dict__[setterName].destroy()
  1079. del self.__dict__[setterName]
  1080. def setDefaultParams(self):
  1081. # set all the default parameters on ourself
  1082. self.ParamSet().applyTo(self)
  1083. def lockParams(self):
  1084. self._paramLockRefCount += 1
  1085. if self._paramLockRefCount == 1:
  1086. self._handleLockParams()
  1087. def unlockParams(self):
  1088. if self._paramLockRefCount > 0:
  1089. self._paramLockRefCount -= 1
  1090. if self._paramLockRefCount == 0:
  1091. self._handleUnlockParams()
  1092. def _handleLockParams(self):
  1093. # this will store the names of the parameters that are modified
  1094. self._paramsSet = {}
  1095. # this will store the values of modified params (from prior to
  1096. # the lock).
  1097. self._priorValuesStack.push({})
  1098. def _handleUnlockParams(self):
  1099. for param in self._paramsSet:
  1100. # call the applier, if there is one
  1101. applier = getattr(self, getSetterName(param, 'apply'), None)
  1102. if applier is not None:
  1103. self._curParamStack.push(param)
  1104. applier()
  1105. self._curParamStack.pop()
  1106. self._priorValuesStack.pop()
  1107. if hasattr(self, 'handleParamChange'):
  1108. self.handleParamChange(tuple(self._paramsSet.keys()))
  1109. del self._paramsSet
  1110. def paramsLocked(self):
  1111. return self._paramLockRefCount > 0
  1112. def getPriorValue(self):
  1113. # call this within an apply function to find out what the prior value
  1114. # of the param was
  1115. return self._priorValuesStack.top()[self._curParamStack.top()]
  1116. def __repr__(self):
  1117. argStr = ''
  1118. for param in self.ParamSet.getParams():
  1119. argStr += '%s=%s,' % (param,
  1120. repr(getSetter(self, param, 'get')()))
  1121. return '%s(%s)' % (self.__class__.__name__, argStr)
  1122. """
  1123. POD (Plain Ol' Data)
  1124. Like ParamObj/ParamSet, but without lock/unlock/getPriorValue and without
  1125. appliers. Similar to a C++ struct, but with auto-generated setters and
  1126. getters.
  1127. Use POD when you want the generated getters and setters of ParamObj, but
  1128. efficiency is a concern and you don't need the bells and whistles provided
  1129. by ParamObj.
  1130. POD.__init__ *MUST* be called. You should NOT define your own data getters
  1131. and setters. Data values may be read, set, and modified directly. You will
  1132. see no errors if you define your own getters/setters, but there is no
  1133. guarantee that they will be called--and they will certainly be bypassed by
  1134. POD internally.
  1135. EXAMPLE CLASSES
  1136. ===============
  1137. Here is an example of a class heirarchy that uses POD to manage its data:
  1138. class Enemy(POD):
  1139. DataSet = {
  1140. 'faction': 'navy',
  1141. }
  1142. class Sailor(Enemy):
  1143. DataSet = {
  1144. 'build': HUSKY,
  1145. 'weapon': Cutlass(scale=.9),
  1146. }
  1147. EXAMPLE USAGE
  1148. =============
  1149. s = Sailor(faction='undead', build=SKINNY)
  1150. # make two copies of s
  1151. s2 = s.makeCopy()
  1152. s3 = Sailor(s)
  1153. # example sets
  1154. s2.setWeapon(Musket())
  1155. s3.build = TALL
  1156. # example gets
  1157. faction2 = s2.getFaction()
  1158. faction3 = s3.faction
  1159. """
  1160. class POD:
  1161. DataSet = {
  1162. # base class does not define any data items, but they would
  1163. # appear here as 'name': value,
  1164. }
  1165. def __init__(self, **kwArgs):
  1166. self.__class__._compileDefaultDataSet()
  1167. if __debug__:
  1168. for arg in kwArgs.keys():
  1169. assert arg in self.getDataNames(), (
  1170. "unknown argument for %s: '%s'" % (
  1171. self.__class__, arg))
  1172. for name in self.getDataNames():
  1173. if name in kwArgs:
  1174. getSetter(self, name)(kwArgs[name])
  1175. else:
  1176. getSetter(self, name)(self.getDefaultValue(name))
  1177. def setDefaultValues(self):
  1178. # set all the default data values on ourself
  1179. for name in self.getDataNames():
  1180. getSetter(self, name)(self.getDefaultValue(name))
  1181. # this functionality used to be in the constructor, triggered by a single
  1182. # positional argument; that was conflicting with POD subclasses that wanted
  1183. # to define different behavior for themselves when given a positional
  1184. # constructor argument
  1185. def copyFrom(self, other, strict=False):
  1186. # if 'strict' is true, other must have a value for all of our data items
  1187. # otherwise we'll use the defaults
  1188. for name in self.getDataNames():
  1189. if hasattr(other, getSetterName(name, 'get')):
  1190. setattr(self, name, getSetter(other, name, 'get')())
  1191. else:
  1192. if strict:
  1193. raise "object '%s' doesn't have value '%s'" % (other, name)
  1194. else:
  1195. setattr(self, name, self.getDefaultValue(name))
  1196. # support 'p = POD.POD().copyFrom(other)' syntax
  1197. return self
  1198. def makeCopy(self):
  1199. # returns a duplicate of this object
  1200. return self.__class__().copyFrom(self)
  1201. def applyTo(self, obj):
  1202. # Apply our entire set of data to another POD
  1203. for name in self.getDataNames():
  1204. getSetter(obj, name)(getSetter(self, name, 'get')())
  1205. def getValue(self, name):
  1206. return getSetter(self, name, 'get')()
  1207. # CLASS METHODS
  1208. def getDataNames(cls):
  1209. # returns safely-mutable list of datum names
  1210. cls._compileDefaultDataSet()
  1211. return cls._DataSet.keys()
  1212. getDataNames = classmethod(getDataNames)
  1213. def getDefaultValue(cls, name):
  1214. cls._compileDefaultDataSet()
  1215. return cls._DataSet[name]
  1216. getDefaultValue = classmethod(getDefaultValue)
  1217. def _compileDefaultDataSet(cls):
  1218. if cls.__dict__.has_key('_DataSet'):
  1219. # we've already compiled the defaults for this class
  1220. return
  1221. # create setters & getters for this class
  1222. if cls.__dict__.has_key('DataSet'):
  1223. for name in cls.DataSet:
  1224. setterName = getSetterName(name)
  1225. if not hasattr(cls, setterName):
  1226. def defaultSetter(self, value, name=name):
  1227. setattr(self, name, value)
  1228. cls.__dict__[setterName] = defaultSetter
  1229. getterName = getSetterName(name, 'get')
  1230. if not hasattr(cls, getterName):
  1231. def defaultGetter(self, name=name,
  1232. default=cls.DataSet[name]):
  1233. return getattr(self, name, default)
  1234. cls.__dict__[getterName] = defaultGetter
  1235. # this dict will hold all of the aggregated default data values for
  1236. # this particular class, including values from its base classes
  1237. cls._DataSet = {}
  1238. bases = list(cls.__bases__)
  1239. # bring less-derived classes to the front
  1240. mostDerivedLast(bases)
  1241. for c in (bases + [cls]):
  1242. # skip multiple-inheritance base classes that do not derive from POD
  1243. if issubclass(c, POD):
  1244. # make sure this base has its dict of data defaults
  1245. c._compileDefaultDataSet()
  1246. if c.__dict__.has_key('DataSet'):
  1247. # apply this class' default data values to our dict
  1248. cls._DataSet.update(c.DataSet)
  1249. _compileDefaultDataSet = classmethod(_compileDefaultDataSet)
  1250. # END CLASS METHODS
  1251. def __repr__(self):
  1252. argStr = ''
  1253. for name in self.getDataNames():
  1254. argStr += '%s=%s,' % (name, repr(getSetter(self, name, 'get')()))
  1255. return '%s(%s)' % (self.__class__.__name__, argStr)
  1256. """ TODO
  1257. if __dev__:
  1258. @staticmethod
  1259. def unitTest():
  1260. tColor = 'red'
  1261. tColor2 = 'blue'
  1262. class test(POD):
  1263. DataSet = {
  1264. 'color': tColor,
  1265. }
  1266. t = test()
  1267. assert t.getColor() == tColor
  1268. t.setColor(tColor2)
  1269. assert t.getColor() == tColor2
  1270. t2 = test().makeCopy()
  1271. assert t2.getColor() == t.getColor() == tColor2
  1272. """
  1273. def bound(value, bound1, bound2):
  1274. """
  1275. returns value if value is between bound1 and bound2
  1276. otherwise returns bound that is closer to value
  1277. """
  1278. if bound1 > bound2:
  1279. return min(max(value, bound2), bound1)
  1280. else:
  1281. return min(max(value, bound1), bound2)
  1282. def lerp(v0, v1, t):
  1283. """
  1284. returns a value lerped between v0 and v1, according to t
  1285. t == 0 maps to v0, t == 1 maps to v1
  1286. """
  1287. return v0 + (t * (v1 - v0))
  1288. def average(*args):
  1289. """ returns simple average of list of values """
  1290. val = 0.
  1291. for arg in args:
  1292. val += arg
  1293. return val / len(args)
  1294. def addListsByValue(a, b):
  1295. """
  1296. returns a new array containing the sums of the two array arguments
  1297. (c[0] = a[0 + b[0], etc.)
  1298. """
  1299. c = []
  1300. for x, y in zip(a, b):
  1301. c.append(x + y)
  1302. return c
  1303. def boolEqual(a, b):
  1304. """
  1305. returns true if a and b are both true or both false.
  1306. returns false otherwise
  1307. (a.k.a. xnor -- eXclusive Not OR).
  1308. """
  1309. return (a and b) or not (a or b)
  1310. def lineupPos(i, num, spacing):
  1311. """
  1312. use to line up a series of 'num' objects, in one dimension,
  1313. centered around zero
  1314. 'i' is the index of the object in the lineup
  1315. 'spacing' is the amount of space between objects in the lineup
  1316. """
  1317. assert num >= 1
  1318. assert i >= 0 and i < num
  1319. pos = float(i) * spacing
  1320. return pos - ((float(spacing) * (num-1))/2.)
  1321. def formatElapsedSeconds(seconds):
  1322. """
  1323. Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
  1324. representing the indicated elapsed time in seconds.
  1325. """
  1326. sign = ''
  1327. if seconds < 0:
  1328. seconds = -seconds
  1329. sign = '-'
  1330. # We use math.floor() instead of casting to an int, so we avoid
  1331. # problems with numbers that are too large to represent as
  1332. # type int.
  1333. seconds = math.floor(seconds)
  1334. hours = math.floor(seconds / (60 * 60))
  1335. if hours > 36:
  1336. days = math.floor((hours + 12) / 24)
  1337. return "%s%d days" % (sign, days)
  1338. seconds -= hours * (60 * 60)
  1339. minutes = (int)(seconds / 60)
  1340. seconds -= minutes * 60
  1341. if hours != 0:
  1342. return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
  1343. else:
  1344. return "%s%d:%02d" % (sign, minutes, seconds)
  1345. def solveQuadratic(a, b, c):
  1346. # quadratic equation: ax^2 + bx + c = 0
  1347. # quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
  1348. # returns None, root, or [root1, root2]
  1349. # a cannot be zero.
  1350. if a == 0.:
  1351. return None
  1352. # calculate the determinant (b^2 - 4ac)
  1353. D = (b * b) - (4. * a * c)
  1354. if D < 0:
  1355. # there are no solutions (sqrt(negative number) is undefined)
  1356. return None
  1357. elif D == 0:
  1358. # only one root
  1359. return (-b) / (2. * a)
  1360. else:
  1361. # OK, there are two roots
  1362. sqrtD = math.sqrt(D)
  1363. twoA = 2. * a
  1364. root1 = ((-b) - sqrtD) / twoA
  1365. root2 = ((-b) + sqrtD) / twoA
  1366. return [root1, root2]
  1367. def stackEntryInfo(depth=0, baseFileName=1):
  1368. """
  1369. returns the sourcefilename, line number, and function name of
  1370. an entry in the stack.
  1371. 'depth' is how far back to go in the stack; 0 is the caller of this
  1372. function, 1 is the function that called the caller of this function, etc.
  1373. by default, strips off the path of the filename; override with baseFileName
  1374. returns (fileName, lineNum, funcName) --> (string, int, string)
  1375. returns (None, None, None) on error
  1376. """
  1377. try:
  1378. stack = None
  1379. frame = None
  1380. try:
  1381. stack = inspect.stack()
  1382. # add one to skip the frame associated with this function
  1383. frame = stack[depth+1]
  1384. filename = frame[1]
  1385. if baseFileName:
  1386. filename = os.path.basename(filename)
  1387. lineNum = frame[2]
  1388. funcName = frame[3]
  1389. result = (filename, lineNum, funcName)
  1390. finally:
  1391. del stack
  1392. del frame
  1393. except:
  1394. result = (None, None, None)
  1395. return result
  1396. def lineInfo(baseFileName=1):
  1397. """
  1398. returns the sourcefilename, line number, and function name of the
  1399. code that called this function
  1400. (answers the question: 'hey lineInfo, where am I in the codebase?')
  1401. see stackEntryInfo, above, for info on 'baseFileName' and return types
  1402. """
  1403. return stackEntryInfo(1, baseFileName)
  1404. def callerInfo(baseFileName=1, howFarBack=0):
  1405. """
  1406. returns the sourcefilename, line number, and function name of the
  1407. caller of the function that called this function
  1408. (answers the question: 'hey callerInfo, who called me?')
  1409. see stackEntryInfo, above, for info on 'baseFileName' and return types
  1410. """
  1411. return stackEntryInfo(2+howFarBack, baseFileName)
  1412. def lineTag(baseFileName=1, verbose=0, separator=':'):
  1413. """
  1414. returns a string containing the sourcefilename and line number
  1415. of the code that called this function
  1416. (equivalent to lineInfo, above, with different return type)
  1417. see stackEntryInfo, above, for info on 'baseFileName'
  1418. if 'verbose' is false, returns a compact string of the form
  1419. 'fileName:lineNum:funcName'
  1420. if 'verbose' is true, returns a longer string that matches the
  1421. format of Python stack trace dumps
  1422. returns empty string on error
  1423. """
  1424. fileName, lineNum, funcName = callerInfo(baseFileName)
  1425. if fileName is None:
  1426. return ''
  1427. if verbose:
  1428. return 'File "%s", line %s, in %s' % (fileName, lineNum, funcName)
  1429. else:
  1430. return '%s%s%s%s%s' % (fileName, separator, lineNum, separator,
  1431. funcName)
  1432. def findPythonModule(module):
  1433. # Look along the python load path for the indicated filename.
  1434. # Returns the located pathname, or None if the filename is not
  1435. # found.
  1436. filename = module + '.py'
  1437. for dir in sys.path:
  1438. pathname = os.path.join(dir, filename)
  1439. if os.path.exists(pathname):
  1440. return pathname
  1441. return None
  1442. def describeException(backTrace = 4):
  1443. # When called in an exception handler, returns a string describing
  1444. # the current exception.
  1445. def byteOffsetToLineno(code, byte):
  1446. # Returns the source line number corresponding to the given byte
  1447. # offset into the indicated Python code module.
  1448. import array
  1449. lnotab = array.array('B', code.co_lnotab)
  1450. line = code.co_firstlineno
  1451. for i in range(0, len(lnotab), 2):
  1452. byte -= lnotab[i]
  1453. if byte <= 0:
  1454. return line
  1455. line += lnotab[i+1]
  1456. return line
  1457. infoArr = sys.exc_info()
  1458. exception = infoArr[0]
  1459. exceptionName = getattr(exception, '__name__', None)
  1460. extraInfo = infoArr[1]
  1461. trace = infoArr[2]
  1462. stack = []
  1463. while trace.tb_next:
  1464. # We need to call byteOffsetToLineno to determine the true
  1465. # line number at which the exception occurred, even though we
  1466. # have both trace.tb_lineno and frame.f_lineno, which return
  1467. # the correct line number only in non-optimized mode.
  1468. frame = trace.tb_frame
  1469. module = frame.f_globals.get('__name__', None)
  1470. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1471. stack.append("%s:%s, " % (module, lineno))
  1472. trace = trace.tb_next
  1473. frame = trace.tb_frame
  1474. module = frame.f_globals.get('__name__', None)
  1475. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1476. stack.append("%s:%s, " % (module, lineno))
  1477. description = ""
  1478. for i in range(len(stack) - 1, max(len(stack) - backTrace, 0) - 1, -1):
  1479. description += stack[i]
  1480. description += "%s: %s" % (exceptionName, extraInfo)
  1481. return description
  1482. def mostDerivedLast(classList):
  1483. """pass in list of classes. sorts list in-place, with derived classes
  1484. appearing after their bases"""
  1485. def compare(a, b):
  1486. if issubclass(a, b):
  1487. result=1
  1488. elif issubclass(b, a):
  1489. result=-1
  1490. else:
  1491. result=0
  1492. #print a, b, result
  1493. return result
  1494. classList.sort(compare)
  1495. def clampScalar(value, a, b):
  1496. # calling this ought to be faster than calling both min and max
  1497. if a < b:
  1498. if value < a:
  1499. return a
  1500. elif value > b:
  1501. return b
  1502. else:
  1503. return value
  1504. else:
  1505. if value < b:
  1506. return b
  1507. elif value > a:
  1508. return a
  1509. else:
  1510. return value
  1511. def weightedChoice(choiceList, rng=random.random, sum=None):
  1512. """given a list of (weight, item) pairs, chooses an item based on the
  1513. weights. rng must return 0..1. if you happen to have the sum of the
  1514. weights, pass it in 'sum'."""
  1515. # TODO: add support for dicts
  1516. if sum is None:
  1517. sum = 0.
  1518. for weight, item in choiceList:
  1519. sum += weight
  1520. rand = rng()
  1521. accum = rand * sum
  1522. for weight, item in choiceList:
  1523. accum -= weight
  1524. if accum <= 0.:
  1525. return item
  1526. # rand is ~1., and floating-point error prevented accum from hitting 0.
  1527. # Or you passed in a 'sum' that was was too large.
  1528. # Return the last item.
  1529. return item
  1530. def randFloat(a, b=0., rng=random.random):
  1531. """returns a random float in [a, b]
  1532. call with single argument to generate random float between arg and zero
  1533. """
  1534. return lerp(a, b, rng())
  1535. def normalDistrib(a, b, gauss=random.gauss):
  1536. """
  1537. NOTE: assumes a < b
  1538. Returns random number between a and b, using gaussian distribution, with
  1539. mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve
  1540. between a and b. Outlying results are clipped to a and b.
  1541. ------------------------------------------------------------------------
  1542. http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
  1543. The 68-95-99.7% Rule
  1544. ====================
  1545. All normal density curves satisfy the following property which is often
  1546. referred to as the Empirical Rule:
  1547. 68% of the observations fall within 1 standard deviation of the mean.
  1548. 95% of the observations fall within 2 standard deviations of the mean.
  1549. 99.7% of the observations fall within 3 standard deviations of the mean.
  1550. Thus, for a normal distribution, almost all values lie within 3 standard
  1551. deviations of the mean.
  1552. ------------------------------------------------------------------------
  1553. In calculating our standard deviation, we divide (b-a) by 6, since the
  1554. 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
  1555. """
  1556. return max(a, min(b, gauss((a+b)*.5, (b-a)/6.)))
  1557. def weightedRand(valDict, rng=random.random):
  1558. """
  1559. pass in a dictionary with a selection -> weight mapping. Eg.
  1560. {"Choice 1": 10,
  1561. "Choice 2": 30,
  1562. "bear": 100}
  1563. -Weights need not add up to any particular value.
  1564. -The actual selection will be returned.
  1565. """
  1566. selections = valDict.keys()
  1567. weights = valDict.values()
  1568. totalWeight = 0
  1569. for weight in weights:
  1570. totalWeight += weight
  1571. # get a random value between 0 and the total of the weights
  1572. randomWeight = rng() * totalWeight
  1573. # find the index that corresponds with this weight
  1574. for i in range(len(weights)):
  1575. totalWeight -= weights[i]
  1576. if totalWeight <= randomWeight:
  1577. return selections[i]
  1578. assert True, "Should never get here"
  1579. return selections[-1]
  1580. def randUint31(rng=random.random):
  1581. """returns a random integer in [0..2^31).
  1582. rng must return float in [0..1]"""
  1583. return int(rng() * 0x7FFFFFFF)
  1584. def randInt32(rng=random.random):
  1585. """returns a random integer in [-2147483648..2147483647].
  1586. rng must return float in [0..1]
  1587. """
  1588. i = int(rng() * 0x7FFFFFFF)
  1589. if rng() < .5:
  1590. i *= -1
  1591. return i
  1592. def randUint32(rng=random.random):
  1593. """returns a random integer in [0..2^32).
  1594. rng must return float in [0..1]"""
  1595. return long(rng() * 0xFFFFFFFFL)
  1596. class SerialNumGen:
  1597. """generates serial numbers"""
  1598. def __init__(self, start=None):
  1599. if start is None:
  1600. start = 0
  1601. self.__counter = start-1
  1602. def next(self):
  1603. self.__counter += 1
  1604. return self.__counter
  1605. _serialGen = SerialNumGen()
  1606. def serialNum():
  1607. global _serialGen
  1608. return _serialGen.next()
  1609. def uniqueName(name):
  1610. global _serialGen
  1611. return '%s-%s' % (name, _serialGen.next())
  1612. def beginExports(modname):
  1613. """The beginExports/endExports construct is used to bracket
  1614. a set of top-level python declarations. The effect is to
  1615. add those declarations to the module's list of exported
  1616. symbols. In other words, the purpose of this bracketing
  1617. construct is to make it easier to properly initialize the
  1618. export-list for a module. The parameter should be the
  1619. current module's name."""
  1620. if (sys.modules.has_key(modname) == 0):
  1621. raise "beginExports("+modname+"): no such module"
  1622. mod = sys.modules[modname]
  1623. if (mod.__dict__.has_key("__begin_exports__")):
  1624. raise "beginExports("+modname+"): incorrect nesting"
  1625. mod.__begin_exports__ = set(mod.__dict__.keys())
  1626. if (mod.__dict__.has_key("__all__")==0):
  1627. mod.__all__ = []
  1628. def endExports(modname):
  1629. """The beginExports/endExports construct is used to bracket
  1630. a set of top-level python declarations. The effect is to
  1631. add those declarations to the module's list of exported
  1632. symbols. In other words, the purpose of this bracketing
  1633. construct is to make it easier to properly initialize the
  1634. export-list for a module. The parameter should be the
  1635. current module's name."""
  1636. if (sys.modules.has_key(modname) == 0):
  1637. raise "beginExports("+modname+"): no such module"
  1638. mod = sys.modules[modname]
  1639. if (mod.__dict__.has_key("__begin_exports__")==0):
  1640. raise "beginExports("+modname+"): incorrect nesting"
  1641. begin_exports = mod.__begin_exports__
  1642. del mod.__dict__["__begin_exports__"]
  1643. end_exports = set(mod.__dict__.keys())
  1644. added = list(end_exports.difference(begin_exports))
  1645. for x in added:
  1646. if (x[0]!="_"):
  1647. mod.__all__.append(x)
  1648. # __builtins__["beginExports"] = beginExports
  1649. # __builtins__["endExports"] = endExports
  1650. class Enum:
  1651. """Pass in list of strings or string of comma-separated strings.
  1652. Items are accessible as instance.item, and are assigned unique,
  1653. increasing integer values. Pass in integer for 'start' to override
  1654. starting value.
  1655. Example:
  1656. >>> colors = Enum('red, green, blue')
  1657. >>> colors.red
  1658. 0
  1659. >>> colors.green
  1660. 1
  1661. >>> colors.blue
  1662. 2
  1663. >>> colors.getString(colors.red)
  1664. 'red'
  1665. """
  1666. if __debug__:
  1667. # chars that cannot appear within an item string.
  1668. InvalidChars = string.whitespace
  1669. def _checkValidIdentifier(item):
  1670. invalidChars = string.whitespace+string.punctuation
  1671. invalidChars = invalidChars.replace('_','')
  1672. invalidFirstChars = invalidChars+string.digits
  1673. if item[0] in invalidFirstChars:
  1674. raise SyntaxError, ("Enum '%s' contains invalid first char" %
  1675. item)
  1676. if not disjoint(item, invalidChars):
  1677. for char in item:
  1678. if char in invalidChars:
  1679. raise SyntaxError, (
  1680. "Enum\n'%s'\ncontains illegal char '%s'" %
  1681. (item, char))
  1682. return 1
  1683. _checkValidIdentifier = staticmethod(_checkValidIdentifier)
  1684. def __init__(self, items, start=0):
  1685. if type(items) == types.StringType:
  1686. items = items.split(',')
  1687. self._stringTable = {}
  1688. # make sure we don't overwrite an existing element of the class
  1689. assert self._checkExistingMembers(items)
  1690. assert uniqueElements(items)
  1691. i = start
  1692. for item in items:
  1693. # remove leading/trailing whitespace
  1694. item = string.strip(item)
  1695. # is there anything left?
  1696. if len(item) == 0:
  1697. continue
  1698. # make sure there are no invalid characters
  1699. assert Enum._checkValidIdentifier(item)
  1700. self.__dict__[item] = i
  1701. self._stringTable[i] = item
  1702. i += 1
  1703. def getString(self, value):
  1704. return self._stringTable[value]
  1705. def __contains__(self, value):
  1706. return value in self._stringTable
  1707. def __len__(self):
  1708. return len(self._stringTable)
  1709. def copyTo(self, obj):
  1710. # copies all members onto obj
  1711. for name, value in self._stringTable:
  1712. setattr(obj, name, value)
  1713. if __debug__:
  1714. def _checkExistingMembers(self, items):
  1715. for item in items:
  1716. if hasattr(self, item):
  1717. return 0
  1718. return 1
  1719. ############################################################
  1720. # class: Singleton
  1721. # Purpose: This provides a base metaclass for all classes
  1722. # that require one and only one instance.
  1723. #
  1724. # Example: class mySingleton:
  1725. # __metaclass__ = PythonUtil.Singleton
  1726. # def __init__(self, ...):
  1727. # ...
  1728. #
  1729. # Note: This class is based on Python's New-Style Class
  1730. # design. An error will occur if a defined class
  1731. # attemps to inherit from a Classic-Style Class only,
  1732. # ie: class myClassX:
  1733. # def __init__(self, ...):
  1734. # ...
  1735. #
  1736. # class myNewClassX(myClassX):
  1737. # __metaclass__ = PythonUtil.Singleton
  1738. # def __init__(self, ...):
  1739. # myClassX.__init__(self, ...)
  1740. # ...
  1741. #
  1742. # This causes problems because myNewClassX is a
  1743. # New-Style class that inherits from only a
  1744. # Classic-Style base class. There are two ways
  1745. # simple ways to resolve this issue.
  1746. #
  1747. # First, if possible, make myClassX a
  1748. # New-Style class by inheriting from object
  1749. # object. IE: class myClassX(object):
  1750. #
  1751. # If for some reason that is not an option, make
  1752. # myNewClassX inherit from object and myClassX.
  1753. # IE: class myNewClassX(object, myClassX):
  1754. ############################################################
  1755. class Singleton(type):
  1756. def __init__(cls, name, bases, dic):
  1757. super(Singleton, cls).__init__(name, bases, dic)
  1758. cls.instance=None
  1759. def __call__(cls, *args, **kw):
  1760. if cls.instance is None:
  1761. cls.instance=super(Singleton, cls).__call__(*args, **kw)
  1762. return cls.instance
  1763. class SingletonError(ValueError):
  1764. """ Used to indicate an inappropriate value for a Singleton."""
  1765. def printListEnum(l):
  1766. # log each individual item with a number in front of it
  1767. digits = 0
  1768. n = len(l)
  1769. while n > 0:
  1770. digits += 1
  1771. n /= 10
  1772. format = '%0' + '%s' % digits + 'i:%s'
  1773. for i in range(len(l)):
  1774. print format % (i, l[i])
  1775. def gcDebugOn():
  1776. import gc
  1777. return (gc.get_debug() & gc.DEBUG_SAVEALL) == gc.DEBUG_SAVEALL
  1778. def safeRepr(obj):
  1779. try:
  1780. return repr(obj)
  1781. except:
  1782. return '<** FAILED REPR OF %s **>' % obj.__class__.__name__
  1783. def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None):
  1784. """ caps the length of iterable types """
  1785. if _visitedIds is None:
  1786. _visitedIds = set()
  1787. if id(obj) in _visitedIds:
  1788. return '<ALREADY-VISITED %s>' % itype(obj)
  1789. if type(obj) in (types.TupleType, types.ListType):
  1790. s = ''
  1791. s += {types.TupleType: '(',
  1792. types.ListType: '[',}[type(obj)]
  1793. if len(obj) > maxLen:
  1794. o = obj[:maxLen]
  1795. ellips = '...'
  1796. else:
  1797. o = obj
  1798. ellips = ''
  1799. _visitedIds.add(id(obj))
  1800. for item in o:
  1801. s += fastRepr(item, maxLen, _visitedIds=_visitedIds)
  1802. s += ', '
  1803. _visitedIds.remove(id(obj))
  1804. s += ellips
  1805. s += {types.TupleType: ')',
  1806. types.ListType: ']',}[type(obj)]
  1807. return s
  1808. elif type(obj) is types.DictType:
  1809. s = '{'
  1810. if len(obj) > maxLen:
  1811. o = obj.keys()[:maxLen]
  1812. ellips = '...'
  1813. else:
  1814. o = obj.keys()
  1815. ellips = ''
  1816. _visitedIds.add(id(obj))
  1817. for key in o:
  1818. value = obj[key]
  1819. s += '%s: %s, ' % (fastRepr(key, maxLen, _visitedIds=_visitedIds),
  1820. fastRepr(value, maxLen, _visitedIds=_visitedIds))
  1821. _visitedIds.remove(id(obj))
  1822. s += ellips
  1823. s += '}'
  1824. return s
  1825. elif type(obj) is types.StringType:
  1826. maxLen *= strFactor
  1827. if len(obj) > maxLen:
  1828. return repr(obj[:maxLen])
  1829. else:
  1830. return repr(obj)
  1831. else:
  1832. return safeRepr(obj)
  1833. def tagRepr(obj, tag):
  1834. """adds a string onto the repr output of an instance"""
  1835. def reprWithTag(oldRepr, tag, self):
  1836. return oldRepr() + '::<TAG=' + tag + '>'
  1837. oldRepr = getattr(obj, '__repr__', None)
  1838. if oldRepr is None:
  1839. def stringer(s):
  1840. return s
  1841. oldRepr = Functor(stringer, repr(obj))
  1842. stringer = None
  1843. obj.__repr__ = new.instancemethod(Functor(reprWithTag, oldRepr, tag), obj, obj.__class__)
  1844. reprWithTag = None
  1845. return obj
  1846. def tagWithCaller(obj):
  1847. """add info about the caller of the caller"""
  1848. tagRepr(obj, str(callerInfo(howFarBack=1)))
  1849. def isDefaultValue(x):
  1850. return x == type(x)()
  1851. # debugging functions that conditionally bring up the debugger in __dev__
  1852. # all can be used with assert, as in 'assert _equal(a,b)'
  1853. def setTrace():
  1854. if __dev__:
  1855. print StackTrace()
  1856. import pdb;pdb.set_trace()
  1857. # setTrace
  1858. return True
  1859. def _equal(a,b):
  1860. if a != b:
  1861. if __dev__:
  1862. print StackTrace()
  1863. import pdb;pdb.set_trace()
  1864. # setTrace
  1865. else:
  1866. assert a == b
  1867. return True
  1868. def _notEqual(a,b):
  1869. if a == b:
  1870. if __dev__:
  1871. print StackTrace()
  1872. import pdb;pdb.set_trace()
  1873. # setTrace
  1874. else:
  1875. assert a != b
  1876. return True
  1877. def _isNone(a):
  1878. if a is not None:
  1879. if __dev__:
  1880. print StackTrace()
  1881. import pdb;pdb.set_trace()
  1882. # setTrace
  1883. else:
  1884. assert a is None
  1885. return True
  1886. def _notNone(a):
  1887. if a is None:
  1888. if __dev__:
  1889. print StackTrace()
  1890. import pdb;pdb.set_trace()
  1891. pass # import pdb;pdb.set_trace()
  1892. else:
  1893. assert a is not None
  1894. return True
  1895. def _contains(container,item):
  1896. if item not in container:
  1897. if __dev__:
  1898. print StackTrace()
  1899. import pdb;pdb.set_trace()
  1900. # setTrace
  1901. else:
  1902. assert item in container
  1903. return True
  1904. def _notIn(container,item):
  1905. if item in container:
  1906. if __dev__:
  1907. print StackTrace()
  1908. import pdb;pdb.set_trace()
  1909. # setTrace
  1910. else:
  1911. assert item not in container
  1912. return True
  1913. class ScratchPad:
  1914. """empty class to stick values onto"""
  1915. def __init__(self, **kArgs):
  1916. for key, value in kArgs.items():
  1917. setattr(self, key, value)
  1918. class Sync:
  1919. _SeriesGen = SerialNumGen()
  1920. def __init__(self, name, other=None):
  1921. self._name = name
  1922. if other is None:
  1923. self._series = self._SeriesGen.next()
  1924. self._value = 0
  1925. else:
  1926. self._series = other._series
  1927. self._value = other._value
  1928. def invalidate(self):
  1929. self._value = None
  1930. def change(self):
  1931. self._value += 1
  1932. def sync(self, other):
  1933. if (self._series != other._series) or (self._value != other._value):
  1934. self._series = other._series
  1935. self._value = other._value
  1936. return True
  1937. else:
  1938. return False
  1939. def isSynced(self, other):
  1940. return ((self._series == other._series) and
  1941. (self._value == other._value))
  1942. def __repr__(self):
  1943. return '%s(%s)<family=%s,value=%s>' % (self.__class__.__name__,
  1944. self._name, self._series, self._value)
  1945. class RefCounter:
  1946. def __init__(self, byId=False):
  1947. self._byId = byId
  1948. self._refCounts = {}
  1949. def _getKey(self, item):
  1950. if self._byId:
  1951. key = id(item)
  1952. else:
  1953. key = item
  1954. def inc(self, item):
  1955. key = self._getKey(item)
  1956. self._refCounts.setdefault(key, 0)
  1957. self._refCounts[key] += 1
  1958. def dec(self, item):
  1959. """returns True if ref count has hit zero"""
  1960. key = self._getKey(item)
  1961. self._refCounts[key] -= 1
  1962. result = False
  1963. if self._refCounts[key] == 0:
  1964. result = True
  1965. del self._refCounts[key]
  1966. return result
  1967. def itype(obj):
  1968. t = type(obj)
  1969. if t is types.InstanceType:
  1970. return '%s of <class %s>' % (repr(types.InstanceType),
  1971. str(obj.__class__))
  1972. else:
  1973. return t
  1974. def getNumberedTypedString(items, maxLen=5000, numPrefix=''):
  1975. """get a string that has each item of the list on its own line,
  1976. and each item is numbered on the left from zero"""
  1977. digits = 0
  1978. n = len(items)
  1979. while n > 0:
  1980. digits += 1
  1981. n /= 10
  1982. digits = digits
  1983. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1984. first = True
  1985. s = ''
  1986. for i in xrange(len(items)):
  1987. if not first:
  1988. s += '\n'
  1989. first = False
  1990. objStr = fastRepr(items[i])
  1991. if len(objStr) > maxLen:
  1992. snip = '<SNIP>'
  1993. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1994. s += format % (i, itype(items[i]), objStr)
  1995. return s
  1996. def printNumberedTyped(items, maxLen=5000):
  1997. """print out each item of the list on its own line,
  1998. with each item numbered on the left from zero"""
  1999. digits = 0
  2000. n = len(items)
  2001. while n > 0:
  2002. digits += 1
  2003. n /= 10
  2004. digits = digits
  2005. format = '%0' + '%s' % digits + 'i:%s \t%s'
  2006. first = True
  2007. for i in xrange(len(items)):
  2008. first = False
  2009. objStr = fastRepr(items[i])
  2010. if len(objStr) > maxLen:
  2011. snip = '<SNIP>'
  2012. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2013. print format % (i, itype(items[i]), objStr)
  2014. import __builtin__
  2015. __builtin__.Functor = Functor
  2016. __builtin__.Stack = Stack
  2017. __builtin__.Queue = Queue
  2018. __builtin__.SerialNumGen = SerialNumGen
  2019. __builtin__.ScratchPad = ScratchPad
  2020. __builtin__.uniqueName = uniqueName
  2021. __builtin__.serialNum = serialNum
  2022. __builtin__.profiled = profiled
  2023. __builtin__.setTrace = setTrace
  2024. __builtin__._equal = _equal
  2025. __builtin__._notEqual = _notEqual
  2026. __builtin__._isNone = _isNone
  2027. __builtin__._notNone = _notNone
  2028. __builtin__._contains = _contains
  2029. __builtin__._notIn = _notIn
  2030. __builtin__.itype = itype