home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1774 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  9.3 KB  |  311 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from IPython.external.path import path as Path
  5. import os
  6. import stat
  7. import time
  8. import cPickle as pickle
  9. import UserDict
  10. import warnings
  11. import glob
  12.  
  13. def gethashfile(key):
  14.     return '%02x' % abs(hash(key) % 256)[-2:]
  15.  
  16. _sentinel = object()
  17.  
  18. class PickleShareDB(UserDict.DictMixin):
  19.     
  20.     def __init__(self, root):
  21.         self.root = Path(root).expanduser().abspath()
  22.         if not self.root.isdir():
  23.             self.root.makedirs()
  24.         
  25.         self.cache = { }
  26.  
  27.     
  28.     def __getitem__(self, key):
  29.         fil = self.root / key
  30.         
  31.         try:
  32.             mtime = fil.stat()[stat.ST_MTIME]
  33.         except OSError:
  34.             raise KeyError(key)
  35.  
  36.         if fil in self.cache and mtime == self.cache[fil][1]:
  37.             return self.cache[fil][0]
  38.         
  39.         try:
  40.             obj = pickle.load(fil.open())
  41.         except:
  42.             mtime == self.cache[fil][1]
  43.             raise KeyError(key)
  44.  
  45.         self.cache[fil] = (obj, mtime)
  46.         return obj
  47.  
  48.     
  49.     def __setitem__(self, key, value):
  50.         fil = self.root / key
  51.         parent = fil.parent
  52.         if parent and not parent.isdir():
  53.             parent.makedirs()
  54.         
  55.         pickled = pickle.dump(value, fil.open('w'))
  56.         
  57.         try:
  58.             self.cache[fil] = (value, fil.mtime)
  59.         except OSError:
  60.             e = None
  61.             if e.errno != 2:
  62.                 raise 
  63.             e.errno != 2
  64.  
  65.  
  66.     
  67.     def hset(self, hashroot, key, value):
  68.         hroot = self.root / hashroot
  69.         if not hroot.isdir():
  70.             hroot.makedirs()
  71.         
  72.         hfile = hroot / gethashfile(key)
  73.         d = self.get(hfile, { })
  74.         d.update({
  75.             key: value })
  76.         self[hfile] = d
  77.  
  78.     
  79.     def hget(self, hashroot, key, default = _sentinel, fast_only = True):
  80.         hroot = self.root / hashroot
  81.         hfile = hroot / gethashfile(key)
  82.         d = self.get(hfile, _sentinel)
  83.         if d is _sentinel:
  84.             if fast_only:
  85.                 if default is _sentinel:
  86.                     raise KeyError(key)
  87.                 default is _sentinel
  88.                 return default
  89.             d = self.hdict(hashroot)
  90.         
  91.         return d.get(key, default)
  92.  
  93.     
  94.     def hdict(self, hashroot):
  95.         hfiles = self.keys(hashroot + '/*')
  96.         hfiles.sort()
  97.         if not len(hfiles) or hfiles[-1]:
  98.             pass
  99.         last = ''
  100.         if last.endswith('xx'):
  101.             hfiles = [
  102.                 last] + hfiles[:-1]
  103.         
  104.         all = { }
  105.         for f in hfiles:
  106.             
  107.             try:
  108.                 all.update(self[f])
  109.             except KeyError:
  110.                 print 'Corrupt', f, 'deleted - hset is not threadsafe!'
  111.                 del self[f]
  112.  
  113.             self.uncache(f)
  114.         
  115.         return all
  116.  
  117.     
  118.     def hcompress(self, hashroot):
  119.         hfiles = self.keys(hashroot + '/*')
  120.         all = { }
  121.         for f in hfiles:
  122.             all.update(self[f])
  123.             self.uncache(f)
  124.         
  125.         self[hashroot + '/xx'] = all
  126.         for f in hfiles:
  127.             p = self.root / f
  128.             if p.basename() == 'xx':
  129.                 continue
  130.             
  131.             p.remove()
  132.         
  133.  
  134.     
  135.     def __delitem__(self, key):
  136.         fil = self.root / key
  137.         self.cache.pop(fil, None)
  138.         
  139.         try:
  140.             fil.remove()
  141.         except OSError:
  142.             pass
  143.  
  144.  
  145.     
  146.     def _normalized(self, p):
  147.         return str(self.root.relpathto(p)).replace('\\', '/')
  148.  
  149.     
  150.     def keys(self, globpat = None):
  151.         return _[2]
  152.  
  153.     
  154.     def uncache(self, *items):
  155.         if not items:
  156.             self.cache = { }
  157.         
  158.         for it in items:
  159.             self.cache.pop(it, None)
  160.         
  161.  
  162.     
  163.     def waitget(self, key, maxwaittime = 60):
  164.         wtimes = [
  165.             0.2] * 3 + [
  166.             0.5] * 2 + [
  167.             1]
  168.         tries = 0
  169.         waited = 0
  170.         while None:
  171.             
  172.             try:
  173.                 val = self[key]
  174.                 return val
  175.             except KeyError:
  176.                 pass
  177.  
  178.             if waited > maxwaittime:
  179.                 raise KeyError(key)
  180.             time.sleep(wtimes[tries])
  181.             waited += wtimes[tries]
  182.             if tries < len(wtimes) - 1:
  183.                 tries += 1
  184.                 continue
  185.             continue
  186.             return None
  187.  
  188.     
  189.     def getlink(self, folder):
  190.         return PickleShareLink(self, folder)
  191.  
  192.     
  193.     def __repr__(self):
  194.         return "PickleShareDB('%s')" % self.root
  195.  
  196.  
  197.  
  198. class PickleShareLink:
  199.     
  200.     def __init__(self, db, keydir):
  201.         self.__dict__.update(locals())
  202.  
  203.     
  204.     def __getattr__(self, key):
  205.         return self.__dict__['db'][self.__dict__['keydir'] + '/' + key]
  206.  
  207.     
  208.     def __setattr__(self, key, val):
  209.         self.db[self.keydir + '/' + key] = val
  210.  
  211.     
  212.     def __repr__(self):
  213.         db = self.__dict__['db']
  214.         keys = db.keys(self.__dict__['keydir'] + '/*')
  215.         return ';'.join % ([], []([ Path(k).basename() for k in keys ]))
  216.  
  217.  
  218.  
  219. def test():
  220.     db = PickleShareDB('~/testpickleshare')
  221.     db.clear()
  222.     print 'Should be empty:', db.items()
  223.     db['hello'] = 15
  224.     db['aku ankka'] = [
  225.         1,
  226.         2,
  227.         313]
  228.     db['paths/nest/ok/keyname'] = [
  229.         1,
  230.         (5, 46)]
  231.     db.hset('hash', 'aku', 12)
  232.     db.hset('hash', 'ankka', 313)
  233.     print '12 =', db.hget('hash', 'aku')
  234.     print '313 =', db.hget('hash', 'ankka')
  235.     print 'all hashed', db.hdict('hash')
  236.     print db.keys()
  237.     print db.keys('paths/nest/ok/k*')
  238.     print dict(db)
  239.     db.uncache()
  240.     lnk = db.getlink('myobjects/test')
  241.     lnk.foo = 2
  242.     lnk.bar = lnk.foo + 5
  243.     print lnk.bar
  244.  
  245.  
  246. def stress():
  247.     db = PickleShareDB('~/fsdbtest')
  248.     import time
  249.     import sys
  250.     for i in range(1000):
  251.         for j in range(1000):
  252.             if i % 15 == 0 and i < 200:
  253.                 if str(j) in db:
  254.                     del db[str(j)]
  255.                     continue
  256.                 continue
  257.             
  258.             if j % 33 == 0:
  259.                 time.sleep(0.02)
  260.             
  261.             db[str(j)] = db.get(str(j), []) + [
  262.                 (i, j, 'proc %d' % os.getpid())]
  263.             db.hset('hash', j, db.hget('hash', j, 15) + 1)
  264.         
  265.         print i,
  266.         sys.stdout.flush()
  267.         if i % 10 == 0:
  268.             db.uncache()
  269.             continue
  270.     
  271.  
  272.  
  273. def main():
  274.     import textwrap
  275.     usage = textwrap.dedent('    pickleshare - manage PickleShare databases \n    \n    Usage:\n        \n        pickleshare dump /path/to/db > dump.txt\n        pickleshare load /path/to/db < dump.txt\n        pickleshare test /path/to/db\n    ')
  276.     DB = PickleShareDB
  277.     import sys
  278.     if len(sys.argv) < 2:
  279.         print usage
  280.         return None
  281.     cmd = sys.argv[1]
  282.     args = sys.argv[2:]
  283.     if cmd == 'dump':
  284.         if not args:
  285.             args = [
  286.                 '.']
  287.         
  288.         db = DB(args[0])
  289.         import pprint
  290.         pprint.pprint(db.items())
  291.     elif cmd == 'load':
  292.         cont = sys.stdin.read()
  293.         db = DB(args[0])
  294.         data = eval(cont)
  295.         db.clear()
  296.         for k, v in db.items():
  297.             db[k] = v
  298.         
  299.     elif cmd == 'testwait':
  300.         db = DB(args[0])
  301.         db.clear()
  302.         print db.waitget('250')
  303.     elif cmd == 'test':
  304.         test()
  305.         stress()
  306.     
  307.  
  308. if __name__ == '__main__':
  309.     main()
  310.  
  311.