• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.Timer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中utils.Timer的典型用法代码示例。如果您正苦于以下问题:Python Timer类的具体用法?Python Timer怎么用?Python Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Timer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: ToggleAnimation

class ToggleAnimation(AnimationActionSprite, Triggered):
    "Animation that can be toggled on/off. """
    def __init__(self, **others):
        Triggered.__init__(self, **others)
        AnimationActionSprite.__init__(self, **others)
        
        self.debugging = False
        self.playing = False
        self.timer = Timer(0.2)
        
        self.animation_player.backwards = True

    def update(self, player, collisions_group, **others):
        self.dprint("\n### ToggleAnimation.update()")
        e = self.get_trigger(self.triggered_code)
        self.dprint("\tEvent:" + str(e))
        if self.timer.finished and e:
            self.timer.reset()
            self.dprint("\t\tToggling Animation")
            if self.playing:
                self.dprint("\t\t\tDeactivating animation")
                self.playing = False
            else:
                self.dprint("\t\t\tActivating animation")
                self.playing = True
        
        if self.playing:
            self.next_frame()
开发者ID:Fenixin,项目名称:yogom,代码行数:28,代码来源:actionsprite.py


示例2: _find_seeks_index

def _find_seeks_index(dbfile, indexname, queries, debug=False):
    """Use the index file to find exact seek positions for relevant
    records. End locations are not necessary since we are guaranteed that
    the data will be present, so a number of occurances is sufficient for
    prompt termination."""
    timer = Timer(rl_min_dur=1)
    locs = Counter()
    if debug:
        print "  Searching index..."
    indexfh = ChunkedFile(dbfile, indexname, mode='r')
    last_bookmark = 0
    for query in sorted(queries):
        # Use bookmarks to rapidly search the index!
        bookmark = indexfh.find_bookmark(query.encode('utf-8'))
        if bookmark != last_bookmark:
            indexfh.seek(bookmark)
            #print "  Seek to", bookmark
            last_bookmark = bookmark
        for i, line in enumerate(indexfh):
            title, nums = line.decode('utf-8').split('\t')
            if i % 100 == 0:
                timer.step()
            if title in queries:
                locs.update(int(x) for x in nums.split(' '))
            elif title > query:
                break   # This works because the index is sorted.
    indexfh.close()
    for start, nresults in sorted(locs.items()):
        yield (start, None, nresults)
    if debug:
        print '  Completed in', timer, 'seconds.'
开发者ID:engelkek,项目名称:python-imdb,代码行数:31,代码来源:parsers.py


示例3: RemoteSubscriber

class RemoteSubscriber(object):
    def __init__(self, uuid, commandID, ipaddress="", port=32400, protocol="http", name=""):
        self.poller         = False
        self.uuid           = uuid
        self.commandID      = commandID
        self.url            = ""
        self.name           = name
        self.lastUpdated    = Timer()

        if ipaddress and protocol:
            self.url = "%s://%s:%s" % (protocol, ipaddress, port)

    def refresh(self, sub):
        log.debug("RemoteSubscriber::refresh %s (cid=%s)" % (self.uuid, sub.commandID))

        if sub.url != self.url:
            log.debug("RemoteSubscriber::refresh new url %s", sub.url)
            self.url = sub.url

        if sub.commandID != self.commandID:
            log.debug("RemoteSubscriber::refresh new commandID %s", sub.commandID)
            self.commandID = sub.commandID

        self.lastUpdated.restart()

    def shouldRemove(self):
        if self.lastUpdated.elapsed() > SUBSCRIBER_REMOVE_INTERVAL:
            log.debug("RemoteSubscriber::shouldRemove removing %s because elapsed: %lld" % (self.uuid, self.lastUpdated.elapsed()))
            return True

        log.debug("RemoteSubscriber::shouldRemove will not remove %s because elapsed: %lld" % (self.uuid, self.lastUpdated.elapsed()))
        return False
开发者ID:noonat,项目名称:omplex,代码行数:32,代码来源:subscribers.py


示例4: convert_model_data

def convert_model_data(subpath):
    tm = Timer()
    fullpath = os.path.join(baseDir, subpath)

    objects = {}
    mtllib = None
    vertices = []
    texcoords = [[0, 0]]
    normals = []
    mtlBaseDir = os.path.split(fullpath)[0]

    lineID = 0
    for line in open(fullpath, "r"):
        lineID += 1
        # print lineID
        if line.startswith('#'): continue
        v = line.split()
        if not v: continue

        if v[0] == 'o' or v[0] == 'g':
            name = v[1].split('_')[0]
            obj = _Object(name)
            objects[obj.name] = obj
        elif v[0] == 'usemtl':
            materialName = v[1]
            obj.material = mtllib.get(materialName)
        elif v[0] == 'v':
            assert len(v) == 4
            v = map(float, v[1:4])
            vertices.append(v)
        elif v[0] == 'vn':
            assert len(v) == 4
            v = map(float, v[1:4])
            normals.append(v)
        elif v[0] == 'vt':
            assert len(v) == 3
            v = map(float, v[1:3])
            texcoords.append(v)
        elif v[0] == 'mtllib':
            mtllib = MaterialLib.load(os.path.realpath(
                os.path.join(mtlBaseDir, v[1])))
        elif v[0] == 'f':
            indices = v[1:]
            assert len(indices) == 3, 'please use triangle faces'
            # each index tuple: (v, t, n)
            for x in indices:
                x = x.split('/')
                vi, ti, ni = map(int, x)
                obj.vdata.extend(
                    texcoords[ti] + normals[ni-1] + vertices[vi-1])
    data = {
        'objects': objects,
        'mtllib': mtllib,
    }
    print 'convert {}, time: {}ms'.format(subpath, tm.tick())
    return data
开发者ID:ZhanruiLiang,项目名称:mirrorman,代码行数:56,代码来源:objReader.py


示例5: __init__

class QueryExecutor:

    index = None
    timer = None

    def __init__(self, index):
        self.index = index


    def executeQueries(self, queryList):
        self.timer = Timer()
        self.timer.start()

        queryMatchingList = []
        executedTokens = 0

        for query in queryList:
            searchTokens = query.getSearchTokens()
            excludedTokens = query.getExcludedTokens()

            searchResult = QueryResult()
            for token in searchTokens:
                executedTokens += 1
                tmpPostingsList = self.index.getDictionary().getPostingsList(token)
                searchResult.addPostingList(token, tmpPostingsList)

            excludedResult = QueryResult()
            for token in excludedTokens:
                tmpPostingsList = self.index.getDictionary().getPostingsList(token)
                excludedResult.addPostingList(token, tmpPostingsList)

            if(len(excludedResult.getItems()) > 0):
                queryMatching = QueryResult.mergeWithExclusions(searchResult, excludedResult)
            else:
                queryMatching = searchResult

            queryMatchingList.append(queryMatching)

        queryMatching = QueryResult.mergeWithIntersection(queryMatchingList)

        rankedResult = RankedResult()
        for doc, queryResultItem in queryMatching.getItems().items():
            rank = RankProvider.provideRank(queryResultItem, executedTokens)
            rankedResultItem = RankedResultItem(doc, rank, queryResultItem)
            rankedResult.addRankedResultItem(rankedResultItem)

        self.timer.stop()

        return rankedResult.getSortedResult()


    def getTimer(self):
        return self.timer
开发者ID:mmalfertheiner,项目名称:inverted-index,代码行数:53,代码来源:queryexecutor.py


示例6: load_models

def load_models():
    tm = Timer()
    if config.GZIP_LEVEL is not None:
        infile = gzip.open(config.DAT_PATH, 'rb', config.GZIP_LEVEL)
    else:
        infile = open(config.DAT_PATH, 'rb')
    # data = infile.read()
    modeldatas = cPickle.loads(infile.read())
    infile.close()
    print 'load dat time: {}ms'.format(tm.tick())
    for filepath, data in modeldatas.iteritems():
        models[filepath] = load_single(filepath, data)
开发者ID:ZhanruiLiang,项目名称:mirrorman,代码行数:12,代码来源:objReader.py


示例7: __init__

    def __init__(self, screen, pos, images, scroll_period, duration=-1):
        """
        If duration == -1, animation goes on indefinetly.
        """

        self.screen = screen
        self.pos = pos
        self.images = [pygame.image.load(image) for image in images]
        self.image_ptr = 0
        self.scroll_period = scroll_period
        self.duration = duration
        self.active = True

        self.scroll_timer = Timer(scroll_period, self.advance_images)
        self.active_timer = Timer(duration, self.inactivate, 1)
开发者ID:fifiman,项目名称:Asteroid-Shooter,代码行数:15,代码来源:animation.py


示例8: __init__

    def __init__(self):
        self._player      = None
        self._video       = None
        self._lock        = RLock()
        self.last_update = Timer()

        self.__part      = 1
开发者ID:noonat,项目名称:omplex,代码行数:7,代码来源:player.py


示例9: update_display

    def update_display(self, elevators, floors):

        # elevator positions
        for i, e in enumerate(elevators):
            self.print_elevator(i, e.old_pos, c=" " * (len(str(e)) + 2))
            self.print_elevator(i, e.pos, c=str(e), color=e.state)

        # rider counds
        for f in xrange(len(floors)):
            m = len(floors[f])
            self.screen.print_at(" " * 20, self.frame_x + 2, self.frame_y + self.frame_h - 2 - f)

            label = "{:<10}{:<3}({})".format("*" * min(m, 10), "..." if m > 10 else "", m)
            self.screen.print_at(label, self.frame_x + 2, self.frame_y + self.frame_h - 2 - f)

        # stats:
        self.screen.print_at(" " * self.frame_w, self.frame_x, self.frame_y - 1)
        self.screen.print_at(
            "Time: {:<6.1f}, Produced: {:<6}, Delivered: {:<6} ({:<2.0f}%), Died: {:<6} ({:2.0f}%)".format(
                Timer.timer(self.game).time(),
                self.game.produced,
                self.game.delivered,
                100.0 * self.game.delivered / self.game.produced,
                self.game.died,
                100.0 * self.game.died / self.game.produced,
            ),
            self.frame_x,
            self.frame_y - 1,
        )

        self.screen.refresh()
开发者ID:yuribak,项目名称:pylevator,代码行数:31,代码来源:elev.py


示例10: __init__

 def __init__(self):
     pygame.init()
     self.screen = pygame.display.set_mode( [self.SCREEN_WIDTH,self.SCREEN_HEIGHT],0,32 )
     self.tile_img = pygame.image.load(self.BG_TITLE_IMG).convert_alpha()
     self.tile_img_rect = self.tile_img.get_rect()
     self.field_box = self.getFieldBox()
     self.tboard = self.getTboard()
     self.mboard = self.getMBoard()
     self.clock = pygame.time.Clock()
     self.creep_images = list()
     self.paused = False
     self.creep_images = [
             ( pygame.image.load(f1).convert_alpha(), pygame.image.load(f2).convert_alpha() )
               for f1,f2 in self.CREEP_FILENAMES ]
     explosion_img = pygame.image.load('images/explosion1.png').convert_alpha()
     self.explosion_images = [ explosion_img, pygame.transform.rotate(explosion_img,90) ]
     self.field_rect = self.getFieldRect()
     self.creeps = pygame.sprite.Group()
     self.spawnNewCreep()
     self.creep_spawn_timer = Timer(500, self.spawnNewCreep)
     self.createWalls()
     # create the grid path representation of the grid
     self.grid_nrows = self.FIELD_SIZE[1]/self.GRID_SIZE
     self.grid_ncols = self.FIELD_SIZE[0]/self.GRID_SIZE
     self.goal_coord = self.grid_nrows - 1, self.grid_ncols - 1
     self.gridpath = GridPath(self.grid_nrows,self.grid_ncols,self.goal_coord)
     for wall in self.walls:
         self.gridpath.set_blocked(wall)
     self.options = dict( draw_grid=False )
开发者ID:MeetLuck,项目名称:works,代码行数:29,代码来源:creep2.py


示例11: storeIndex

    def storeIndex(self):
        self.timer = Timer()
        self.timer.start()

        storage = Storage()
        storage.saveIndex(self.dictionary)

        self.timer.stop()
开发者ID:mmalfertheiner,项目名称:inverted-index,代码行数:8,代码来源:index.py


示例12: worker

def worker(args):
    label, method = args

    # call the requested method
    try:
        logger.info('%s: call to DataBuilder.%s' % (label, method))
        t = Timer()
        data = getattr(databuilder, method)()
        t.stop()
        logger.info('%s: done [%.1fs]' % (label, t.elapsed))
        return label, data, None

    except:
        import StringIO
        import traceback
        buffer = StringIO.StringIO()
        traceback.print_exc(file = buffer)
        return label, None, buffer.getvalue()
开发者ID:cms-sw,项目名称:web-confdb,代码行数:18,代码来源:task.py


示例13: __init__

 def __init__(self, **others):
     Triggered.__init__(self, **others)
     OnceAnimationActionSprite.__init__(self, **others)
     
     self.debugging = False
     self.playing = False
     self.timer = Timer(0.2)
     
     self.debugging = False
开发者ID:Fenixin,项目名称:yogom,代码行数:9,代码来源:actionsprite.py


示例14: __init__

    def __init__(self, uuid, commandID, ipaddress="", port=32400, protocol="http", name=""):
        self.poller         = False
        self.uuid           = uuid
        self.commandID      = commandID
        self.url            = ""
        self.name           = name
        self.lastUpdated    = Timer()

        if ipaddress and protocol:
            self.url = "%s://%s:%s" % (protocol, ipaddress, port)
开发者ID:noonat,项目名称:omplex,代码行数:10,代码来源:subscribers.py


示例15: run

 def run(self):
     """run
     """
     all_greenlet = []
     # 定时爬取
     for group_url in self.group_list:
         # timer = Timer(random.randint(0, self.interval), self.interval)
         timer = Timer(random.randint(0, 2), self.interval)
         greenlet = gevent.spawn(
             timer.run, self._init_page_tasks, group_url)
         all_greenlet.append(greenlet)
     # 生产 & 消费
     all_greenlet.append(gevent.spawn(self._page_loop))
     all_greenlet.append(gevent.spawn(self._topic_loop))
     # 重载代理,10分
     proxy_timer = Timer(PROXY_INTERVAL, PROXY_INTERVAL)
     all_greenlet.append(
         gevent.spawn(proxy_timer.run(self.reload_proxies)))
     gevent.joinall(all_greenlet)
开发者ID:bnulxe,项目名称:douban-group-spider,代码行数:19,代码来源:spider.py


示例16: __init__

    def __init__(self, ):
        super(Scene, self).__init__()

        self.fps = Timer()
        self.surf_main = pg.display.get_surface()

        self.running = False
        self.loaded = False

        self.last_time = 0
开发者ID:,项目名称:,代码行数:10,代码来源:


示例17: __str__

 def __str__(self):
     s = "%s:\n\n" % self.id
     for system in self.systems:
         s += "%s config:\n%s\n\n" % (system, pformat(system.config))
     s += "\n"
     for run_time in self.runs:
         s += Timer.format_run_times(run_time)
         s += "\n"
     s += "\n"
     return s
开发者ID:mxm,项目名称:yoka,代码行数:10,代码来源:lib.py


示例18: __init__

    def __init__(self):
        self.currentItems   = {}
        self.currentStates  = {}
        self.idleTimer      = Timer()
        self.subTimer       = Timer()
        self.serverTimer    = Timer()
        self.stopped        = False
        self.halt           = False

        threading.Thread.__init__(self)
开发者ID:noonat,项目名称:omplex,代码行数:10,代码来源:timeline.py


示例19: ToggleText

class ToggleText(TextActionSprite, Triggered):
    """ Text that toggles on/off when a trigger event is received. 
        Special parameters are:
        - Delay: amount of time to wait before you can toggle the text
                again.
    """
    def __init__(self, **others):
        Triggered.__init__(self, **others)
        TextActionSprite.__init__(self, **others)
        
        
        # custom parameters
        self.custom_properties = { "Delay" : {"type" : float, "destination" : "delay"} }
        self.parse_catching_errors(self.custom_properties, others, self.__dict__)

        # create the timer
        self.timer = Timer(self.delay)

        # prints lots of debugging text
        self.debugging = False
    
    def update(self, player, collisions_group, **others):
        self.dprint("\n### TriggeredText.update()")
        e = self.get_trigger(self.triggered_code)
        self.dprint("\tEvent:" + str(e))
        if e and self.timer.finished:
            self.timer.reset()
            self.dprint("\t\tToggling text")

            if self.showing:
                self.update_position(player)
                self.dprint("\t\t\tDeactivating text")
                self.showing = False
            else:
                self.update_position(player)
                self.dprint("\t\t\tActivating text")
                self.showing = True
        
        self.update_alpha()
    
    def do(self):
        pass
开发者ID:Fenixin,项目名称:yogom,代码行数:42,代码来源:actionsprite.py


示例20: __init__

    def __init__(self, source, parserType):
        self.source = source
        self.parserType = parserType
        self.dictionary = Dictionary()

        self.timer = Timer()
        self.timer.start()

        self.setup()

        self.timer.stop()
开发者ID:mmalfertheiner,项目名称:inverted-index,代码行数:11,代码来源:index.py



注:本文中的utils.Timer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.Util类代码示例发布时间:2022-05-26
下一篇:
Python utils.TextLoader类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap