#!/usr/bin/env python
import time

#--------------------GENERAL CLASS----------------
class StackDict:
  """Stackable Dictionary, first in, last out
>>> d = StackDict()
>>> d['x']=1
>>> d['a']=2
>>> d['1']=3
>>> d['b']=4
>>> d
{'a': 2, 'x': 1, '1': 3, 'b': 4}
>>> d.getkey(0)
'x'
>>> d._data
[('x', 1), ('a', 2), ('1', 3), ('b', 4)]
>>> d.getvalue(0)
1
>>> d.getkey(-1)
'b'
>>> d.getvalue(-1)
4
  """
  def __init__(self, *argv, **keyw):
    if len(self.__class__.__bases__) == 0:
      self._parent = None
    else:
      self._parent = self.__class__.__bases__[0]
    self._data = []
    self._keys = []
    self._items = []
    self.init(argv, keyw)

  def init(self, *argv, **keyw):
    pass

  def test_key(self, key, *argv, **keyw):
    if keyw.has_key(key):
      return keyw[key]
    else:
      return None
 
  def __repr__(self):
    return repr(dict(self._data))

  def __setitem__(self, key, item):
    _keys = [i[0] for i in self._data]
    if key in _keys:
      index = _keys.index(key)
      self._data[index] = (key, item)
    else:
      self._data.append((key, item))

  def __getitem__(self, key):
    index = [i[0] for i in self._data].index(key)
    return self._data[index][1]

  def __delitem__(self, key):
    index = [i[0] for i in self._data].index(key)
    self._data.remove(self._data[index])

  def dict(self):
    return dict(self._data)

  def has_key(self, key):
    _keys = [i[0] for i in self._data]
    if key in _keys:
      return True
    else:
      return False

  def keys(self): return [i[0] for i in self._data]

  def values(self): return [i[1] for i in self._data]

  def items(self): return self._data

  def clear(self): self.__init__()

  def copy(self):
    import copy
    return copy.copy(self)

  def pop(self, key):
    item = self[key]
    del self[key]
    return item

  def getkey(self, index):
    return self._keys[index]

  def getvalue(self, index):
    return self._items[index]


class StackListDict(StackDict):
  def __setitem__(self, key, item):
    _keys = [i[0] for i in self._data]
    if key in _keys:
      index = _keys.index(key)
      self._data[index] = (key, [item])
    else:
      self._data.append((key, [item]))


class TimeIt:
  """Time count"""
  def __init__(self):
    self.start=time.time()
    self.last_print=self.start
    self.p_start=self.start

  def now(self):
    return time.time()

  def use(self):
    """ used time in current period """
    t_now=self.now()
    t_use=t_now-self.p_start
    self.p_start=t_now
    return t_use

  def all(self):
    """ all time from start point """
    return time.time()-self.start

  def print_use(self,msg='nomsg'):
    t_now = self.now()
    print 'time use in %s after %5.3f: %7.5f <br />\n' \
          % (msg, self.last_print, t_now-self.last_print)
    self.last_print = t_now
