Beispiel #1
1
    def run(self):  
        # initialize windows side   
        tosdb.admin_init(self._addr, AINIT_TIMEOUT)   
        tosdb.vinit(root=self._dll_root)

        # create block
        blk = tosdb.VTOSDB_DataBlock(self._addr, BLOCK_SIZE, date_time=True)
        blk.add_items(*(self._symbols))
        blk.add_topics('last')
        if args.vol:
            blk.add_topics('volume')
     
        # generate filename             
        dprfx = _strftime("%Y%m%d", _localtime())
        isec = int(self._intrvl * 60)  
        for s in self._symbols:
            #
            # create GetOnTimeInterval object for each symbol
            # 
            p = self._out_dir + '/' + dprfx + '_' \
                + s.replace('/','-S-').replace('$','-D-').replace('.','-P-') \
                +'_' + _val_type + '_' + str(self._intrvl) + 'min.tosdb'           
            iobj = _Goti.send_to_file(blk, s, p, _TI.vals[isec], isec/10)
            print(repr(iobj), file=_stderr)
            self._iobjs.append(iobj)

        for i in self._iobjs:
            if i:
                i.join()

        while(True): # why??
            _sleep(10)
Beispiel #2
0
 def dst(self, dt):
     """datetime -> DST offset in minutes east of UTC."""
     tt = _localtime(
         _mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second,
                  dt.weekday(), 0, -1)))
     if tt.tm_isdst > 0: return _dstdiff
     return _zero
Beispiel #3
0
def spawn(dllroot,outdir,intrvl,val_type,*symbols):   
    if val_type not in ['OHLCV','OHLC','CV','C']:
        raise ValueError("invalid val_type (OHLCV,OHLC,CV or C)")

    exc_cmd = "from tosdb.intervalize import " + CLS_BASE + val_type + " as _Goti"
    exec(exc_cmd, globals())
    
    tosdb.init(root=dllroot)
    
    # create block
    blk = tosdb.TOSDB_DataBlock(BLOCK_SIZE, date_time=True)
    blk.add_items(*(symbols))
    blk.add_topics('last')
    if 'V' in val_type:
        blk.add_topics('volume')
        
    # generate filename          
    dprfx = _strftime("%Y%m%d", _localtime())
    isec = int(intrvl * 60)  
    iobjs = list()

    for s in symbols:
        #
        # create GetOnTimeInterval object for each symbol
        # 
        p = _path(outdir) + '/' + dprfx + '_' \
            + s.replace('/','-S-').replace('$','-D-').replace('.','-P-') \
            + '_' + val_type + '_' + str(intrvl) + 'min.tosdb'       
        iobj = _Goti.send_to_file(blk, s, p, getattr(_TI,_TI.val_dict[isec]), isec/10)
        print( repr(iobj) )
        iobjs.append( iobj )
    
    return iobjs
Beispiel #4
0
 def __init__(self, addr, auth, outdir, pidfile, errorfile, interval, itype,
              symbols):
     _Daemon.__init__(self, pidfile, stderr=errorfile)
     self._addr = addr
     self._auth = auth
     self._outdir = _path(outdir)
     self._interval = interval
     self._has_vol = 'V' in itype
     self._is_ohlc = 'OHLC' in itype
     self._symbols = symbols
     self._iobj = None
     # date prefix for filename
     dprfx = _strftime("%Y%m%d", _localtime())
     # generate paths from filenames
     self._paths = {s.upper() : (_path(self._outdir) + '/' + dprfx + '_' \
                                + s.replace('/','-S-').replace('$','-D-').replace('.','-P-') \
                                + '_' + itype + '_' + str(self._interval) + 'sec.tosdb') \
                                  for s in self._symbols}
     # create callback object
     if self._has_vol:
         self._callback = _ohlcv_callbacks._Matcher(
             'ohlc' if self._is_ohlc else 'c', self._write)
     else:
         l = (lambda o: str((o.o, o.h, o.l, o.c))) if self._is_ohlc else (
             lambda o: str(o.c))
         self._callback = _ohlcv_callbacks._Basic(l, self._write)
Beispiel #5
0
 def __sub__(self, other_or_micro_sec):
     other = other_or_micro_sec
     if isinstance(other, int):  # subtracting an integer
         if other < 0:
             return self.__add__(other * -1)
         other_sec = other // 1000000
         ms_diff = self.micro - (other % 1000000)
         if ms_diff < 0:  # take a second, if needed
             other_sec += 1
             ms_diff += 1000000
         # reduce to seconds, decrement, return to stuct_time
         mk_time = self._mktime
         mk_time -= other_sec
         new_time = _localtime(mk_time)
         return TOSDB_DateTime(new_time, micro_second=ms_diff)
     elif isinstance(other,
                     TOSDB_DateTime):  # subtracting another TOSDB_DateTime
         try:  # try to get other's time in seconds
             sec_diff = self._mktime - other._mktime
             ms_diff = self.micro - other.micro
             # convert the diff in micro_seconds to the diff-tuple
             return TOSDB_DateTime.micro_to_dtd(sec_diff * 1000000 +
                                                ms_diff)
         except Exception as e:
             raise TOSDB_DateTimeError("invalid TOSDB_DateTime object", e)
     else:
         raise TOSDB_DateTimeError(
             "other_or_micro_sec not TOSDB_DateTime or int")
Beispiel #6
0
 def __sub__(self, other_or_micro_sec ):
     other = other_or_micro_sec
     # if we are subtracting an integer
     if isinstance( other , int ):
         if other < 0:
             return self.__add__( other * -1 )
         other_sec = other // 1000000
         ms_diff = self.micro - ( other % 1000000 )
         if ms_diff < 0: # take a second, if needed
             other_sec += 1
             ms_diff += 1000000
         # reduce to seconds, decrement, return to stuct_time          
         mk_time = self._mktime
         mk_time -= other_sec
         new_time = _localtime( mk_time )
         # return a new TOSDB_DateTime 
         return TOSDB_DateTime( new_time, micro_second = ms_diff )            
     # if we are subtracting another TOSDB_DateTime
     elif isinstance( other, TOSDB_DateTime):
         try: # try to get other's time in seconds                                         
             sec_diff = self._mktime - other._mktime         
             ms_diff = self.micro - other.micro
             # convert the diff in micro_seconds to the diff-tuple
             return TOSDB_DateTime.micro_to_dtd( sec_diff * 1000000 + ms_diff)     
         except Exception as e:
             raise TOSDB_DateTimeError( "invalid TOSDB_DateTime object", e )
     else:
         raise TOSDB_DateTimeError( "other_or_micro_sec must be " +
                                    "TOSDB_DateTime or int" )
Beispiel #7
0
def spawn(dllroot,outdir,intrvl,val_type,*symbols):
   
    if val_type not in ['OHLCV','OHLC','CV','C']:
         raise ValueError("invalid val_type (OHLCV,OHLC,CV or C)")

    exec( "from tosdb.intervalize import " + CLS_BASE + val_type + " as _Goti",
          globals() )
    
    tosdb.init( root=dllroot )
    
    # create block
    blk = tosdb.TOSDB_DataBlock( BLOCK_SIZE, date_time=True)
    blk.add_items( *(symbols) )
    blk.add_topics( 'last' )
    if 'V' in val_type:
        blk.add_topics( 'volume' )
        
    # generate filename                
    dprfx = _strftime("%Y%m%d", _localtime())
    isec = int(intrvl * 60)    
    iobjs = list()
    for s in symbols:
        #
        # create GetOnTimeInterval object for each symbol
        # 
        p = _path(outdir) + '/' + dprfx + '_' + \
                s.replace('/','-S-').replace('$','-D-').replace('.','-P-') + \
                '_' + val_type + '_' + str(intrvl) + 'min.tosdb'           
        iobj = _Goti.send_to_file( blk, s, p, getattr(_TI,_TI.val_dict[ isec ]),
                                   isec/10)
        print( repr(iobj) )
        iobjs.append( iobj )
    
    return iobjs
Beispiel #8
0
 def utcoffset(self, dt):
     """datetime -> minutes east of UTC (negative for west of UTC)."""
     tt = _localtime(
         _mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second,
                  dt.weekday(), 0, -1)))
     if tt.tm_isdst > 0: return _dstoffset
     return _stdoffset
Beispiel #9
0
    def run(self):
        # initialize windows side
        tosdb.admin_init(self._addr, AINIT_TIMEOUT)
        tosdb.vinit(root=self._dll_root)

        # create block
        blk = tosdb.VTOSDB_DataBlock(self._addr, BLOCK_SIZE, date_time=True)
        blk.add_items(*(self._symbols))
        blk.add_topics('last')
        if args.vol:
            blk.add_topics('volume')

        # generate filename
        dprfx = _strftime("%Y%m%d", _localtime())
        isec = int(self._intrvl * 60)
        for s in self._symbols:
            #
            # create GetOnTimeInterval object for each symbol
            #
            p = self._out_dir + '/' + dprfx + '_' + \
                    s.replace('/','-S-').replace('$','-D-').replace('.','-P-') + \
                    '_' + _val_type + '_' + str(self._intrvl) + 'min.tosdb'
            iobj = _Goti.send_to_file(blk, s, p, _TI.vals[isec], isec / 10)
            print(repr(iobj), file=_stderr)
            self._iobjs.append(iobj)

        for i in self._iobjs:
            if i:
                i.join()

        while (True):
            _sleep(10)
Beispiel #10
0
 def dst(self, dt):
     """datetime -> DST offset in minutes east of UTC."""
     tt = _localtime(
         _mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second,
                  dt.weekday(), 0, -1)))
     if tt.tm_isdst > 0: return _dstdiff
     return _zero
Beispiel #11
0
def localtime(date):
    """Convert a PyEphem date into local time, returning a Python datetime."""
    microseconds = int(round(24 * 60 * 60 * 1000000 * date))
    seconds, microseconds = divmod(microseconds, 1000000)
    seconds -= 2209032000  # difference between epoch 1900 and epoch 1970
    y, m, d, H, M, S, wday, yday, isdst = _localtime(seconds)
    return _datetime(y, m, d, H, M, S, microseconds)
Beispiel #12
0
def localtime(date):
    """Convert a PyEphem date into local time, returning a Python datetime."""
    microseconds = int(round(24 * 60 * 60 * 1000000 * date))
    seconds, microseconds = divmod(microseconds, 1000000)
    seconds -= 2209032000  # difference between epoch 1900 and epoch 1970
    y, m, d, H, M, S, wday, yday, isdst = _localtime(seconds)
    return _datetime(y, m, d, H, M, S, microseconds)
    def do_now(self, args):
        """now"""
        args = args.split()
        if _debug: TestConsoleCmd._debug("do_now %r", args)

        y = _localtime()
        print("y: {}".format(y))
Beispiel #14
0
 def utcoffset(self, dt):
     """datetime -> minutes east of UTC (negative for west of UTC)."""
     tt = _localtime(
         _mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second,
                  dt.weekday(), 0, -1)))
     if tt.tm_isdst > 0: return _dstoffset
     return _stdoffset
def gettime():
    OLD = str(_localtime())
    YEAR = str((OLD.split(',')[0]).split('=')[1])
    MONTH = str((OLD.split(',')[1]).split('=')[1])
    DAY = str((OLD.split(',')[2]).split('=')[1])
    HOUR = str((OLD.split(',')[3]).split('=')[1])
    MINUTE = str((OLD.split(',')[4]).split('=')[1])
    SECOND = str((OLD.split(',')[5]).split('=')[1])
    if len(str(MINUTE)) == 1: MINUTE = '0' + str(MINUTE)
    NEW = [(MONTH + '/' + DAY + '/' + YEAR), (HOUR + ':' + MINUTE + ':' + SECOND)]
    return NEW
Beispiel #16
0
def init(dllpath=None, root="C:\\", bypass_check=False):
    """ Initialize the underlying tos-databridge DLL

  dllpath: string of the exact path of the DLL
  root: string of the directory to start walking/searching to find the DLL
  """
    global _dll
    rel = set()
    if not bypass_check and dllpath is None and root == "C:\\":
        if abort_init_after_warn():
            return False

    def _remove_older_versions():
        nonlocal rel
        getver = lambda x: _search(_REGEX_VER_SFFX, x).group().strip('-')
        vers = tuple(zip(map(getver, rel), rel))
        vers_max = max(vers)[0].split('.')[0]
        mtup = tuple(( x[0].split('.')[1],x[1]) \
                       for x in vers if x[0].split('.')[0] == vers_max )
        mtup_max = max(mtup)[0]
        rel = set(x[1] for x in mtup if x[0] == mtup_max)

    try:
        if dllpath is None:
            matcher = _partial(_match, _REGEX_DLL_NAME)  # regex match function
            for nfile in map(matcher, _listdir(_curdir)):
                if nfile:  # try the current dir first
                    rel.add(_curdir + _sep + nfile.string)
            if not rel:  # no luck, walk the dir tree
                for root, dirs, files in _walk(root):
                    for file in map(matcher, files):
                        if file:
                            rel.add(root + _sep + file.string)
                if not rel:  # if still nothing throw
                    raise TOSDB_InitError(" could not locate DLL")
            if len(rel) > 1:  # only use the most recent version(s)
                _remove_older_versions()
            # most recently updated
            d = dict(zip(map(lambda x: _stat(x).st_mtime, rel), rel))
            rec = max(d)
            dllpath = d[rec]
        _dll = _WinDLL(dllpath)
        print("+ Using Module ", dllpath)
        print("+ Last Update ", _asctime(_localtime(_stat(dllpath).st_mtime)))
        if connect():
            print("+ Succesfully Connected to Service \ Engine")
        else:
            print("- Failed to Connect to Service \ Engine")
        return True  # indicate the lib was loaded (but not if connect succeeded)
    except TOSDB_Error:
        raise
    except Exception as e:
        raise TOSDB_InitError("unable to initialize library", e)
Beispiel #17
0
def main(arg=None):
    if arg is None:
        _files_r.print_pending_tasks()
    elif arg in ('create', '--create', '-c'):
        _files_w.create_file(_localtime(_time()))
    elif arg in ('edit', '--edit', '-c'):
        _files_w.edit_file(_localtime(_time()))
    elif arg == 'commit all':
        _git.commit_all(_localtime(_time()))
    elif arg == 'push':
        _git.push()
    elif arg == 'directory':
        _shell.directory()
    elif arg == 'ls':
        _shell.ls()
    elif arg == 'll':
        _shell.ll()
    elif arg in ('help', '-h', '--help'):
        print(get_help())
    else:
        print(get_help(), file=_stderr)
        _exit(1)
Beispiel #18
0
 def __add__(self, micro_seconds ):
     if not isinstance(micro_seconds, int):                
         raise TOSDB_DateTimeError( "micro_seconds must be integer" )
     incr_sec = micro_seconds // 1000000
     ms_new = self.micro + ( micro_seconds % 1000000  )        
     if ms_new >= 1000000:
         incr_sec += 1
         ms_new -= 1000000
     # reduce to seconds, increment, return to _struct_time        
     mk_time = self._mktime 
     mk_time += incr_sec       
     new_time = _localtime( mk_time ) 
     # return a new TOSDB_DateTime 
     return TOSDB_DateTime( new_time, micro_second = ms_new )                
Beispiel #19
0
 def __add__(self, micro_seconds):
     if not isinstance(micro_seconds, int):
         raise TOSDB_DateTimeError("micro_seconds must be integer")
     incr_sec = micro_seconds // 1000000
     ms_new = self.micro + (micro_seconds % 1000000)
     if ms_new >= 1000000:
         incr_sec += 1
         ms_new -= 1000000
     # reduce to seconds, increment, return to _struct_time
     mk_time = self._mktime
     mk_time += incr_sec
     new_time = _localtime(mk_time)
     # return a new TOSDB_DateTime
     return TOSDB_DateTime(new_time, micro_second=ms_new)
Beispiel #20
0
def init(dllpath = None, root = "C:\\", bypass_check=False):
    """ Initialize the underlying tos-databridge DLL

    dllpath: string of the exact path of the DLL
    root: string of the directory to start walking/searching to find the DLL
    """  
    global _dll
    rel = set()
    if not bypass_check and dllpath is None and root == "C:\\":
        if abort_init_after_warn():
            return
    try:
        if dllpath is None:
            matcher = _partial( _match, _REGEX_DLL_NAME)  # regex match function
            for nfile in map( matcher, _listdir( _curdir )):
                if nfile: # try the current dir first             
                    rel.add( _curdir+ _sep + nfile.string )                    
            if not rel:                
                for root,dirs, files in _walk(root): # no luck, walk the dir tree 
                    for file in map( matcher, files):  
                        if file:                           
                            rel.add( root + _sep + file.string )                           
                if not rel: # if still nothing throw
                    raise TOSDB_Error(" could not locate DLL")    
            if len(rel) > 1:  # only use the most recent version(s)
                ver = _compile('-[\d]{1,2}.[\d]{1,2}-')
                vers = tuple( zip( map( 
                    lambda x: _search(ver,x).group().strip('-'), rel), rel) )
                vers_max = max(vers)[0].split('.')[0]
                mtup = tuple( (x[0].split('.')[1],x[1]) 
                              for x in vers if x[0].split('.')[0] == vers_max)         
                mtup_max = max(mtup)[0]
                rel = set( x[1] for x in mtup if x[0] == mtup_max )                      
            # find the most recently updated
            d = dict( zip(map( lambda x : _stat(x).st_mtime, rel), rel ) )
            rec = max(d)
            dllpath = d[ rec ]
        _dll = _WinDLL( dllpath )
        print( "+ Using Module ", dllpath )
        print( "+ Last Update ", _asctime(_localtime(_stat(dllpath).st_mtime)))
        if connect():
            print("+ Succesfully Connected to Service \ Engine")       
        else:
            print("- Failed to Connect to Service \ Engine")
        return True # indicate the lib was loaded
    except Exception as e:
        raise TOSDB_CLibError( "unable to initialize library", e )        
Beispiel #21
0
 def __init__(self, addr, auth, outdir, pidfile, errorfile, interval, itype, symbols):
     _Daemon.__init__(self, pidfile, stderr = errorfile)
     self._addr = addr    
     self._auth = auth
     self._outdir = _path(outdir)
     self._interval = interval
     self._has_vol = 'V' in itype
     self._is_ohlc = 'OHLC' in itype
     self._symbols = symbols   
     self._iobj = None     
     # date prefix for filename          
     dprfx = _strftime("%Y%m%d", _localtime())
     # generate paths from filenames
     self._paths = {s.upper() : (_path(self._outdir) + '/' + dprfx + '_' \
                                + s.replace('/','-S-').replace('$','-D-').replace('.','-P-') \
                                + '_' + itype + '_' + str(self._interval) + 'sec.tosdb') \
                                  for s in self._symbols}
     # create callback object
     if self._has_vol:            
         self._callback = _ohlcv_callbacks._Matcher('ohlc' if self._is_ohlc else 'c', self._write)
     else:
         l = (lambda o: str((o.o, o.h, o.l, o.c))) if self._is_ohlc else (lambda o: str(o.c))
         self._callback = _ohlcv_callbacks._Basic(l, self._write)       
Beispiel #22
0
def spawn(outdir, interval, is_ohlc, has_vol, *symbols):
    global _paths

    itype = ("OHLC" if is_ohlc else "C") + ("V" if has_vol else "")    
    # date prefix for filename                    
    dprfx = _strftime("%Y%m%d", _localtime())
    # generate paths from filenames
    _paths = {s.upper() : (_path(outdir) + '/' + dprfx + '_' \
                          + s.replace('/','-S-').replace('$','-D-').replace('.','-P-') \
                          + '_' + itype + '_' + str(interval) + 'sec.tosdb')
                          for s in symbols}  

    # create callback object
    if has_vol:
        callback = _ohlcv_callbacks._Matcher('ohlc' if is_ohlc else 'c', _write)
    else:
        l = (lambda o: str((o.o, o.h, o.l, o.c))) if is_ohlc else (lambda o: str(o.c))
        callback = _ohlcv_callbacks._Basic(l, _write)   
  
    # create block
    blk = tosdb.TOSDB_ThreadSafeDataBlock(BLOCK_SIZE, date_time=True)
    blk.add_items(*(symbols))
    blk.add_topics('last')        
    if has_vol:
        blk.add_topics('volume')  
     
    # create interval object
    IObj = OHLCIntervals if is_ohlc else CIntervals
    iobj = IObj(blk, interval, interval_cb=callback.callback)
    try:
        while iobj.running():
            _sleep(1)
    except:
        iobj.stop()
    finally:
        blk.close()     
Beispiel #23
0
'''
from time import localtime as _localtime

orgname = 'Flask'
appname = 'App++'
appname_low = appname.lower().rstrip('+')  # rm rstrip on name change
fullname = '%s %s' % (orgname, appname)
# reversed dotted notation, for libraries, android, etc:
revname = '.'.join(reversed(orgname.split('.'))) + '.' + appname

__version__ = version = '0.50'
__author__ = authors = ', '.join([
    'Firstinald_M_McLasterson',  # add more below
    'and contributors',
])
copyright_date = '© 2017-%s' % _localtime().tm_year
__copyright__ = copyright = '%s, %s' % (copyright_date, orgname)

description = 'A_short_descriptive_blurb_to_explain_the_project_goes_here.'
# delete this line and line below when description has been updated:
description += ''' (Edit title, version, and this description, etc. in
                      ../main/meta.py) '''
email = '*****@*****.**',

#~ __license__     = license = 'Proprietary, see LICENSE file for details.'
__license__ = license = 'Unlicense, The - https://unlicense.org'

pkg_reqs = (  # for setup.py
    'bcrypt',
    'flask>=0.12',
    'flask_admin',
Beispiel #24
0
def init(dllpath=None, root="C:\\", bypass_check=False):
    """ Initialize the underlying tos-databridge DLL and try to connect.

    Returns True if library was successfully loaded, not necessarily that
    it was also able to connect. Details are sent to stdout.
    
    init(dllpath=None, root="C:\\", bypass_check=False)
    
    dllpath      :: str  :: exact path of the DLL -or-
    root         :: str  :: directory to start walking/searching to find the DLL
    bypass_check :: bool :: used by virtual layer implemenation (DO NOT SET)

    returns -> bool 

    throws TOSDB_InitError TOSDB_Error
    """
    global _dll, _dll_depend1
    rel = set()
    if not bypass_check and dllpath is None and root == "C:\\":
        if abort_init_after_warn():
            return False

    def _remove_older_versions():
        nonlocal rel
        getver = lambda x: _search(_REGEX_VER_SFFX, x).group().strip('-')
        vers = tuple(zip(map(getver, rel), rel))
        vers_max = max(vers)[0].split('.')[0]
        mtup = tuple(( x[0].split('.')[1],x[1]) \
                       for x in vers if x[0].split('.')[0] == vers_max )
        mtup_max = max(mtup)[0]
        rel = set(x[1] for x in mtup if x[0] == mtup_max)

    def _get_depends1_dll_path(dllpath):
        d = _path.dirname(dllpath)
        dbg = _match(_REGEX_DBG_DLL_PATH, dllpath)
        base = d + "/" + DLL_DEPENDS1_NAME + "-" + SYS_ARCH_TYPE
        path = base + ("_d.dll" if dbg else ".dll")
        return path

    try:
        if dllpath is None:
            matcher = _partial(_match, _REGEX_DLL_NAME)
            for nfile in map(matcher, _listdir(_curdir)):
                if nfile:  # try the current dir first
                    rel.add(_curdir + _sep + nfile.string)
            if not rel:  # no luck, walk the dir tree
                for root, dirs, files in _walk(root):
                    for file in map(matcher, files):
                        if file:
                            rel.add(root + _sep + file.string)
                if not rel:  # if still nothing throw
                    raise TOSDB_InitError(" could not locate DLL")
            if len(rel) > 1:  # only use the most recent version(s)
                _remove_older_versions()
            # most recently updated
            d = dict(zip(map(lambda x: _stat(x).st_mtime, rel), rel))
            rec = max(d)
            dllpath = d[rec]

        dllpath_depends1 = _get_depends1_dll_path(dllpath)
        _dll_depend1 = _CDLL(dllpath_depends1)
        _dll = _CDLL(dllpath)
        print("+ Using Module(s) ", dllpath)
        print("                  ", dllpath_depends1)
        print("+ Last Update:", _asctime(_localtime(_stat(dllpath).st_mtime)))
        print("+ Process ID:", str(_getpid()))
        if connect():
            print("+ Succesfully Connected to Service\Engine")
            if connected():
                print("+ Succesfully Connected to TOS")
            else:
                print("- Failed to Connect to TOS")
        else:
            print("- Failed to Connect to Service\Engine")
            print("- Failed to Connect to TOS")
        return True  # indicate the lib was loaded (but not if connect succeeded)
    except Exception as e:
        raise TOSDB_InitError("unable to initialize library:", e)
Beispiel #25
0
def localtime(date):
    """Convert a PyEphem date into naive local time, returning a Python datetime."""
    seconds, microseconds = _convert_to_seconds_and_microseconds(date)
    y, m, d, H, M, S, wday, yday, isdst = _localtime(seconds)
    return _datetime(y, m, d, H, M, S, microseconds)
Beispiel #26
0
 def __str__( self ):
     return _strftime( "%m/%d/%y %H:%M:%S", 
                       _localtime( self._mktime ) ) + " " + str(self.micro)
Beispiel #27
0
def localtime(date):
    """Convert a PyEphem date into naive local time, returning a Python datetime."""
    seconds, microseconds = _convert_to_seconds_and_microseconds(date)
    y, m, d, H, M, S, wday, yday, isdst = _localtime(seconds)
    return _datetime(y, m, d, H, M, S, microseconds)
Beispiel #28
0
def init(dllpath=None, root="C:\\", bypass_check=False):
    """ Initialize the underlying tos-databridge DLL

    dllpath: string of the exact path of the DLL
    root: string of the directory to start walking/searching to find the DLL
    """  
    global _dll, _dll_depend1
    rel = set()
    if not bypass_check and dllpath is None and root == "C:\\":
        if abort_init_after_warn():
            return False

    def _remove_older_versions():
        nonlocal rel  
        getver = lambda x: _search(_REGEX_VER_SFFX,x).group().strip('-')
        vers = tuple(zip(map(getver, rel), rel))
        vers_max = max(vers)[0].split('.')[0]
        mtup = tuple(( x[0].split('.')[1],x[1]) \
                       for x in vers if x[0].split('.')[0] == vers_max )         
        mtup_max = max(mtup)[0]
        rel = set(x[1] for x in mtup if x[0] == mtup_max)

    def _get_depends1_dll_path(dllpath):
        d = _path.dirname(dllpath)
        return d + "/" + DLL_DEPENDS1_NAME + "-" + SYS_ARCH_TYPE + ".dll"
    
    try:   
        if dllpath is None:
            matcher = _partial(_match, _REGEX_DLL_NAME)  
            for nfile in map(matcher, _listdir(_curdir)):
                if nfile: # try the current dir first             
                    rel.add(_curdir+ _sep + nfile.string)                    
            if not rel: # no luck, walk the dir tree              
                for root, dirs, files in _walk(root):  
                    for file in map(matcher, files):  
                        if file:                           
                            rel.add(root + _sep + file.string)                           
                if not rel: # if still nothing throw
                    raise TOSDB_InitError(" could not locate DLL")          
            if len(rel) > 1:  # only use the most recent version(s)
                _remove_older_versions()              
            # most recently updated
            d = dict(zip(map(lambda x: _stat(x).st_mtime, rel), rel)) 
            rec = max(d)
            dllpath = d[rec]

        dllpath_depends1 = _get_depends1_dll_path(dllpath)
        _dll_depend1 = _CDLL(dllpath_depends1)
        _dll = _CDLL(dllpath)
        
        print("+ Using Module(s) ", dllpath)
        print("                  ", dllpath_depends1)
        print("+ Last Update ", _asctime(_localtime(_stat(dllpath).st_mtime)))
        if connect():
            print("+ Succesfully Connected to Service \ Engine")       
        else:
            print("- Failed to Connect to Service \ Engine")
        return True # indicate the lib was loaded (but not if connect succeeded)
    except TOSDB_Error:
        raise
    except Exception as e:
        raise TOSDB_InitError("unable to initialize library", e)        
Beispiel #29
0
 def __str__(self):
     ftime = _strftime("%m/%d/%y %H:%M:%S", _localtime(self._mktime))
     return ftime + " " + str(self.micro)
    Project metadata is specified here.

    This module *should not* import anything from the project or third-party
    modules, to avoid dependencies in setup.py or circular import issues.
'''
from os.path import join as _join
from time import localtime as _localtime

pkgname = 'console'
full_name = 'Console'  # rendered for Makefile
__version__ = version = '0.9906'
__author__ = authors = ', '.join([
    'Mike Miller',
    #~ 'and contributors',
])
copyright = '© 2018-%s' % _localtime().tm_year
description = ('Comprehensive, composable utility library for ANSI terminals.'
               ' Better, stronger, faster.  Tch-tch-tch-tch…')
email = '*****@*****.**'
license = 'LGPL 3',
keywords = ('ansi terminal emulator console color detection '
            'escape sequence cursor style screen shell xterm')

# online repo information
repo_account = 'mixmastamyk'
repo_name = pkgname
repo_provider = 'github.com'
doc_url = 'https://mixmastamyk.bitbucket.io/console/'
repo_url = 'https://%s/%s/%s' % (repo_provider, repo_account, repo_name)
project_urls = {
    'Repository': repo_url,
Beispiel #31
0
 def tzname(self, dt):
     """datetime -> string name of time zone."""
     tt = _localtime(_mktime((dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
     return _time.tzname[tt.tm_isdst > 0]
Beispiel #32
0
def formatted_local_time():

    return _asctime(_localtime())