Exemplo n.º 1
0
    def fetch_ladder(self, season_id, region, bid, timeout=60):
        """
        Fetch ladder from blizzard api.

        :return: <status code, ApiLadder or None, fetch time, fetch duration>
        """

        if season_id >= 28:
            url_prefix = self.REGION_URL_PREFIXES_2[region]
            url = "%s/ladder/%d" % (url_prefix, bid)
            timer = Timer()
            status, data = self.http_get_json(url, timeout, ACCESS_TOKEN_AUTH)
        else:
            url_prefix = self.REGION_URL_PREFIXES_1[region]
            url = "%s/ladder/%d" % (url_prefix, bid)
            timer = Timer()
            status, data = self.http_get_json(url, timeout, API_KEY_AUTH)

        al = ApiLadder(data, url)

        return LadderResponse(status, al, utcnow(), timer.end())
Exemplo n.º 2
0
    def fetch_player_ladders(self, region, player_path, timeout=60):
        """
        Fetch player ladders from blizzard api.

        :return: <status code, ApiPlayerLadders or None, fetch time, fetch duration>
        """
        url_prefix = self.REGION_URL_PREFIXES_1[region]
        url = '%s%sladders' % (url_prefix, player_path)
        timer = Timer()
        status, data = self.http_get_json(url, timeout, API_KEY_AUTH)
        return PlayerLaddersResponse(status, ApiPlayerLadders(data, url),
                                     utcnow(), timer.end())
def main(args):
    torch.manual_seed(args.seed)
    np.random.seed(args.seed)
    random.seed(args.seed)
    if args.cpu:
        logger.critical('use CPU !')
        args.cuda = False
    elif args.cuda:
        logger.critical("use CUDA")
        torch.cuda.manual_seed(args.seed)

    args = vars(args)
    logger.info('model args:')
    for k, v in args.items():
        logger.info(f'--{k}: {v}')
    logger.critical(f"Running parser in {args['mode']} mode")

    if args['mode'] == 'train':
        with Timer('train time:'):
            train(args)
    else:
        with Timer('predict time:'):
            evaluate(args)
Exemplo n.º 4
0
    def fetch_current_season(self, region, timeout=60):
        """
        Fetch current season information.

        :return: <status code, ApiSeasonInfo or None, fetch time, fetch duration>
        """
        url_prefix = self.REGION_URL_PREFIXES[region]
        region_id = self.REGION_IDS[region]

        url = f'{url_prefix}/sc2/ladder/season/{region_id}'
        timer = Timer()
        status, data = self.http_get_json(url, timeout, ACCESS_TOKEN_AUTH)
        return SeasonResponse(status, ApiSeason(data, url), utcnow(),
                              timer.end())
Exemplo n.º 5
0
    def fetch_ladder(self, region, bid, timeout=60):
        """
        Fetch ladder from blizzard api.

        :return: <status code, ApiLadder or None, fetch time, fetch duration>
        """

        url_prefix = self.REGION_URL_PREFIXES[region]

        url = f"{url_prefix}/data/sc2/ladder/{bid}"
        timer = Timer()
        status, data = self.http_get_json(url, timeout, ACCESS_TOKEN_AUTH)
        al = ApiLadder(data, url)
        return LadderResponse(status, al, utcnow(), timer.end())
Exemplo n.º 6
0
    def __init__(self):
        #初始化信息
        self.userName = global_config.get('config', 'userName')
        self.eomsHost = global_config.get('config', 'eomsHost')
        if self.userName:
            self.nick_name = self.userName
        else:
            self.nick_name = 'anonymous'

        #初始化变量
        self.spider_session = RequestSession()
        self.spider_session.load_cookies_from_local(
            self.nick_name)  #如果本地有cookies,则直接加载
        self.Userlogin = UserLogin(self.spider_session)
        self.session = self.spider_session.get_session()
        self.user_agent = self.spider_session.user_agent
        self.timer = Timer()
Exemplo n.º 7
0
 def connect_and_run(self) -> None:
     """Connect to the server and run the client"""
     logging.info('Connecting to server: {}:{}', self.host, self.port)
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sock.settimeout(self.SOCKET_TIMEOUT)
     try:
         self.sock.connect((self.host, self.port))
     except socket.error as err:
         logging.error('Unable to connect: {} (retrying in {}s)', err,
                       self.RECONNECT_DELAY)
         return
     logging.info("Connected to server")
     # Initialize a timer to periodically send a SystemInfoMessage
     send_system_info_timer = Timer(self.SYSTEM_INFO_INTERVAL,
                                    start_expired=True)
     try:
         # Inform the server of the current state of the Arduino connection
         send_obj(self.sock,
                  ArduinoConnectionMessage(self.arduino.is_connected()))
         while True:
             # Send a SystemInfoMessage if send_stats_interval has elapsed
             if send_system_info_timer.is_expired():
                 send_obj(self.sock, get_system_info_message())
                 send_system_info_timer.restart()
             # Receive and handle a command
             command = recv_obj(self.sock, self.SOCKET_TIMEOUT)
             self.handle_command(command)
     except socket.error as err:
         logging.error('Connection closed: {} (reconnecting in {}s)', err,
                       self.RECONNECT_DELAY)
     finally:
         self.sock.close()
         # If the Arduino is connected, try and stop the motors
         if self.arduino.is_connected():
             try:
                 self.arduino.write_speeds(None)
             except serial.SerialException:
                 pass
         # Stop the currently playing sound, if any
         self.sound_player.stop()
Exemplo n.º 8
0
    def fetch_league(self,
                     region,
                     season_id,
                     version,
                     mode,
                     league,
                     timeout=60):
        """
        Fetch league information.

        :return: <status code, ApiLeagueInfo or None, fetch time, fetch duration>
        """

        url_prefix = self.REGION_URL_PREFIXES[region]
        queue_id = self.QUEUE_ID_MAJOR[version] + self.QUEUE_ID_MINOR[mode]
        team_type = self.TEAM_TYPE[mode]

        url = f'{url_prefix}/data/sc2/league/{season_id}/{queue_id}/{team_type}/{league}'
        bid = league + team_type * 10 + queue_id * 100 + season_id * 100000
        timer = Timer()
        status, data = self.http_get_json(url, timeout, ACCESS_TOKEN_AUTH)
        return LeagueResponse(status, ApiLeague(data, url, bid), utcnow(),
                              timer.end())
Exemplo n.º 9
0
 def __init__(self,*args,**kwargs):
     super(ExplorationFirstRoundStateWithTimer,self).__init__(*args,**kwargs)
     self._timer = Timer(limit=self._MAP_UPDATE_TIME_LIMIT,end_callback=self.ask_for_map_update)
Exemplo n.º 10
0
import sys
from common.timer import Timer
from spider.spider import Spider

if __name__ == '__main__':

    spider = Spider()
    timer = Timer()

    while (True):
        spider.tousu_order()
        timer.cycleDelay()
Exemplo n.º 11
0
 def __init__(self):
     self.domain = GetSysConfig('user_server_addr')
     self.__store = {}
     # CURLClient.__init__(self, domain)
     self.timer = Timer(10, self, 'UserTokenCheck')
     self.timer.start()
            if flag == 'pretrain':
                check.append(mode.vocab.id2unit(d.item()))
            else:
                check.append(mode.id2unit(d.item()))
        print(check)

    # print('|word size: {}'.format(word.size()))
    # print('|words mask size: {}'.format(words_mask.size()))
    # print('|wordchars size: {}'.format(wordchars.size()))
    #
    # print('|pretrained: {}'.format(pretrained.dtype))
    # check(word, sdp_dataset.vocab['word'], 0, flag='word')
    # check(word, sdp_dataset.vocab['word'], -1, flag='word')
    # check(pretrained, pretrain)
    # from pprint import pprint
    #
    # pprint(sdp_dataset[0])
    # print("===" * 10)
    # for i, data in enumerate(dataloader):
    #     if i != 0:
    #         break
    #     pprint(data)
    from common.timer import Timer

    with Timer('dataset:'):
        for _, data in enumerate(sdp_dataset):
            pass
    # with Timer('dataloader:'):
    #     for _, data in enumerate(dataloader):
    #         pass
Exemplo n.º 13
0
 def __init__(self):
     thread_num = 3
     schedule_name = 'WorkFlow'
     super(WorkFlowMgr,self).__init__(thread_num, schedule_name)
     schedu_timer = Timer(10, self, "WorkFlowDriver")
     schedu_timer.start()
Exemplo n.º 14
0
os.environ["SDL_VIDEODRIVER"] = 'dummy'
#init the pygame and display setup
pygame.init()
pygame.display.init()
screen = pygame.display.set_mode([1, 1])
#init the queue
pygame.fastevent.init()
#init the joystick
#js = pygame.joystick.Joystick(0)
#js.init()
#start the connection
hardware.init()
con = Connection()
con.openListen()
#start the timer
t = Timer()
t.startTimer()
#run the user init code
rc = robotCode.RobotCode(con)
#queue processing loop
while True:
    #let the queue do what it needs
    pygame.fastevent.pump()
    #pull the next event
    ev = pygame.fastevent.poll()
    if ev.type == pygame.NOEVENT:
        #on an empty queue wait
        time.sleep(.2)
    elif ev.type == evtype.USRICK:
        #if an ick event respond to it
        pass
Exemplo n.º 15
0
import time

import numpy
import pop_factory
from common.timer import Timer


r = numpy.random.rand(10000)
snp_tuple = pop_factory.SNPTuples(100, "1", 50000)
snp_tuple.add_tuple("G", 0.70)
snp_tuple.add_tuple("A", 0.90)
snp_tuple.add_tuple("T", 1.0)

x = [100, 200]
start = time.perf_counter()
for i in range(10000000):
    with Timer("in_list") as t:
        y = 100 not in x
end = time.perf_counter()
print("elapsed %s" % str(end - start))
print(str(Timer.report_all()))

x = {100: 1, 200: 2}
start = time.perf_counter()
for i in range(10000000):
    with Timer("in_dict") as t:
        y = 100 not in x
end = time.perf_counter()
print("elapsed %s" % str(end - start))
print(str(Timer.report_all()))