def main(): description = ("Launches an MS server and several clients in quick " "succession.") parser = argparse.ArgumentParser(description=description) parser.add_argument("client_count", type=int, choices=range(2, 7), help="Number of clients to launch") args = parser.parse_args() # Try and kill any existing processes to avoid port conflicts. common.kill_remaining_processes() def sigint_handler(signum, frame): _ = signum, frame common.kill_remaining_processes() # Catch Ctrl-C interrupts so we can (try to) kill our spawned processes. signal.signal(signal.SIGINT, sigint_handler) ms_srv = common.MatchMakingServer(2222) ms_srv.start() common.sleep(2) clients = common.start_multiple_clients(ms_srv.port, args.client_count) ms_srv.wait() for client in clients: client.wait()
def stackitems(item): thing = pyautogui.locateOnScreen('imgs/inventoryitemhangar.png') inventorylist = cm.Area(thing.left + 25, thing.top + 70, 500, 250) cm.sleep(1) box = inventorylist.toAbsTuple() ocr = cm.grabandocr(box) #todo implement ocr with highestsim check for s in ocr.splitlines(): if (s.split()[-1][:5] in item.lower()): offsetpos = inventorylist mousex = offsetpos.x + int(s.split()[6]) / 4 + 5 mousey = offsetpos.y + int(s.split()[7]) / 4 + 5 cm.clickxy(mousex, mousey, clicks=1, right=True) cm.sleep(0.2) box = (mousex + 15, mousey + 2, mousex + 15 + 135, mousey + 3 + 250) ocr = cm.grabandocr(box) for s in ocr.splitlines(): if (s.split()[-1] == "stack"): mousex = mousex + 18 + int(s.split()[6]) / 4 + 5 mousey = mousey + 3 + int(s.split()[7]) / 4 + 5 cm.clickxy(mousex, mousey) return
def _setSlideshowCollection(self): common.debug("Starting slideshow collection") artistsArray = self.getArtistNames() artistsIndex = 0 for artist in artistsArray: if self._isPlaybackChanged(): common.debug( "Cancel slideshow collection due to the change of player content" ) break if artist is None or artist == '': continue artistsIndex += 1 common.debug("Collecting slideshow for artist [%s]" % artist) self.dir_cache = self._resdir(artist) common.trace("Cache directory for artist [%s]: %s" % (artist, self.dir_cache)) self._setSkinSlideshow(self.dir_show, self.dir_cache) if artistsIndex == 1: self._setSkinArtistBiografy(artist) self._setSkinArtistAlbumInfo(artist) self._setSkinArtistImages(artist) self._cache2show() self._setSkinSlideshow(self.dir_cache, self.dir_show) common.sleep() common.debug('Ended slideshow collection')
def test_too_little_players(self): """c1 connects to the matchmaking server. Game doesn't start and we see one player waiting. """ ms_srv = common.MatchMakingServer(2222) ms_srv.start() common.sleep(2) _ = common.start_multiple_clients(ms_srv.port, 1) common.sleep(common.MatchMakingServer.GAME_START_TIMEOUT) starting_game_found = False player_count_found = False with open(ms_srv.local_log_path) as log_file: for line in log_file: if "Starting Game" in line: starting_game_found = True continue elif "1 players" in line: player_count_found = True continue self.assertTrue(player_count_found, "MS server should have been connected to") self.assertFalse(starting_game_found, "Game should not have started")
def clear(): print("clearing quickbar...") show() cm.sleep(0.2) cm.clickPointPNG('imgs/resetquickbar.png', 5, 5) cm.sleep(0.5) cm.clickPointPNG('imgs/yesno.png', 5, 5) itemlist.clear()
def search_market(item): pos = pyautogui.locateOnScreen('imgs/search.png') pyautogui.moveTo(pos.left - 70, pos.top + pos.height / 2) pyautogui.doubleClick(pos.left - 70, pos.top + pos.height / 2) cm.safetypewrite(item) cm.sleep(0.3) pyautogui.moveTo(pos.left + pos.width / 2, pos.top + pos.height / 2) pyautogui.click(pos.left + pos.width / 2, pos.top + pos.height / 2) pyautogui.moveTo(200, 10)
def get_job_obj(self) -> dict: """ 获取任务 :return: 任务字典 """ while True: job_str = self.redis.lpop(self.__get_job_key()) if job_str: return json.loads(job_str) common.sleep(10)
def test_del(self, str_): eles = self.ready_test_del() for i in range(0, len(eles)): # 如果新建菜单不可见,就点击一次新建按钮 if common.is_show(self.driver, Page_garbage.newxpaths['xpath_menu_new']): ele = common.wait_until_show( self.driver, Page_garbage.newxpaths['xpath_new_button']) common.click(ele) if eles[i].text == str_: common.click(eles[i]) common.wait_until( driver=self.driver, method=lambda a: True if (self.driver.title != 'ProcessOn - 我的文件') else False) # 为了系统有时间保存这一次作品 common.sleep(2) # 返回我的文件 self.driver.get(Page_garbage.newxpaths['url_my']) # 删除第一个文件 common.context_click( driver=self.driver, ele=common.s_wait_until_show( driver=self.driver, xpath=Page_garbage.newxpaths['xpath_file_listitems']) [0]) eles = common.s_wait_until_show( driver=self.driver, xpath=Page_garbage.newxpaths['xpath_menu_context_click']) for i in range(0, len(eles)): if '删除' in eles[i].text: common.click(eles[i]) common.click( common.wait_until_show( self.driver, Page_garbage.newxpaths['xpath_del_ok'])) break # 前往回收站 self.driver.get(Page_garbage.newxpaths['url_g']) # 断言回收站里面的文件数量是不是上一个加1 try: # 出现异常意味着没找到元素,此时count为0 count_now = len( common.s_wait_until_show( driver=self.driver, xpath=Page_garbage. newxpaths['xpath_file_listitems'], sec=2)) except: count_now = 0 assert count_now == self.count_of_g + 1 break
def guiinit(): #close undock window cm.clickPointPNG('imgs/undock.png', 173, 3) if pyautogui.locateOnScreen('imgs/myordersselling.png', confidence=0.9) is None: cm.clickPointPNG('imgs/marketordersbutton.png', 10, 10, cache=True) #make regional market search results big so ocr can read better thing = pyautogui.locateOnScreen('imgs/search.png', confidence=0.9) pyautogui.moveTo(thing.left + 75, thing.top + 27) cm.sleep(1) pyautogui.dragRel(300, 0, 1, button='left') cm.sleep(1) variables.bidaplh = cm.getAPandLH(True) variables.sellaplh = cm.getAPandLH(False)
def test_method(self): self.info("Creating new district...") (ret, output) = common.create_district(self.district_name) self.assert_equal(0, ret, "Unable to create district:%s") nodes = common.get_nodes() pnodes=[] for node in nodes: pnodes.append(common.get_public_ip_from_private(node)) self.assert_true((len(nodes)>=2), "There must be at least 2 ndoes...") for node in nodes: ret = common.add_node2district(self.district_name,node) self.assert_equal(0, ret, "Error during adding node into district") #Creating 1st app self.info("Creating app#1...") (ret, status) = self.config.rest_api.app_create(self.app_name1, common.app_types[self.test_variant]) self.assert_equal('Created', ret, "Error during creating app#1 - %s"%self.app_name1) self.info("Waiting...") common.sleep(90) self.info("Creating app#2...") (ret,status) = self.config.rest_api.app_create(self.app_name2, common.app_types[self.test_variant]) self.assert_equal('Created', ret, "Error during creating app#2 - %s"%self.app_name2) (gear_group1, gear_count) = self.config.rest_api.get_gears(self.app_name1) app1_gear=gear_group1[0]['gears'][0]['id'] (gear_group2, gear_count) = self.config.rest_api.get_gears(self.app_name2) app2_gear=gear_group2[0]['gears'][0]['id'] gears={} print "*"*80 for node in pnodes: gears[node] = common.get_gears_per_node(node) if gears[node].has_key(app1_gear): print "\tApp1's gear[%s] is deployed on %s"%(app1_gear, node) app1_node=node if gears[node].has_key(app2_gear): print "\tApp2's gear[%s] is deployed on %s"%(app2_gear, node) app2_node=node print "*"*80 self.assert_true((app1_node!=app2_node), "App1 should not reside on the same node as App2") ''' db = brokerdb.BrokerDB(collections = ['district']) districts = db.get_collection('district') print "DISTRICTS: [UUID | NAME | NODES]" for district in districts: #print district.keys() print "\t",district['uuid'], district['name'], district['server_identities'] print uuid1,uuid2 ''' return self.passed("%s passed" % self.__class__.__name__)
def _setSkinSlideshow(self, dir1=None, dir2=None): if (dir1 is None or dir1 == '' or not os.path.isdir(dir1) or dir1 == self.dir_root) and (dir2 is None or dir2 == '' or not os.path.isdir(dir2)): if self._resinpath(dir1) > 0: self.setSkinProperty("SlideshowAddon", dir1) common.debug('Set slideshow location to ROOT: %s' % dir1) else: self.setSkinProperty("SlideshowAddon") common.debug('Reset slideshow location for ROOT: %s' % dir1) elif dir1 is not None and dir1 != '' and os.path.isdir(dir1) and ( dir2 is None or dir2 == '' or not os.path.isdir(dir2)): if self._resinpath(dir1) > 0: common.debug('Set slideshow primary location: %s' % dir1) self.setSkinProperty("SlideshowAddon", dir1) else: self.setSkinProperty("SlideshowAddon") common.debug('Reset slideshow primary location: %s' % dir1) elif (dir1 is None or dir1 == '' or not os.path.isdir(dir1) or dir1 == self.dir_root) and (dir2 is not None and dir2 != '' and os.path.isdir(dir2)): self.setSkinProperty("SlideshowAddon") common.sleep(1000) if self._resinpath(dir2) > 0: self.setSkinProperty("SlideshowAddon", dir2) common.debug('Set slideshow secondary location: %s' % dir2) else: self.setSkinProperty("SlideshowAddon") common.debug('Reset slideshow secondary location: %s' % dir2) elif (dir1 is not None and dir1 != '' and os.path.isdir(dir1) and dir1 != self.dir_root) and (dir2 is not None and dir2 != '' and os.path.isdir(dir2) and dir2 != self.dir_root): if dir1 != self.addoninfo: if self._resinpath(dir1) > 0: common.debug('Set slideshow temporary location: %s' % dir1) self.setSkinProperty("SlideshowAddon", dir1) else: self.setSkinProperty("SlideshowAddon") common.debug('Reset slideshow temporary location: %s' % dir1) common.sleep(1000) if dir2 != self.addoninfo: if self._resinpath(dir2) > 0: common.debug('Set slideshow target location: %s' % dir2) self.setSkinProperty("SlideshowAddon", dir2) else: self.setSkinProperty("SlideshowAddon") common.debug('Reset slideshow target location: %s' % dir2)
def lookup(target, uid, secret, color=common.bcolors.WARNING): if uid is None or secret is None: print('Missing Censys API UID or secret. Skipping...') return None API_URL = 'https://censys.io/api/v1' API_PATH = '/search/certificates' response = requests.post(API_URL + API_PATH, auth=(uid, secret), json={'query': 'parsed.names:{}'.format(target)}) if response.status_code != 200: print('Got status {} from Censys search. Skipping...'.format(response.status_code)) print(response.json()['error']) return None data = response.json() table = PrettyTable() table.field_names = ["Censys Certificates", "Trust", "Issuer", "Issued", "Expires"] for cert in data['results'][:5]: cert_data = raw_cert(cert['parsed.fingerprint_sha256'], uid, secret) if cert_data is None: continue cert_names = cert_data['parsed']['names'] cert_names_len = len(cert_names) if cert_names_len == 1: cert_names = cert_names[0] elif cert_names_len > 3: cert_names = 'Valid for ' + str(len(cert_names)) + ' domains' cert_start = cert_data['parsed']['validity']['start'] cert_start = cert_start[:cert_start.index('T')] cert_end = cert_data['parsed']['validity']['end'] cert_end = cert_end[:cert_end.index('T')] cert_trusted = '' try: if 'trusted' in cert_data['tags']: cert_trusted = "Trusted" except KeyError: pass table.add_row([cert_names, cert_trusted, cert_data['parsed']['issuer']['common_name'][0], cert_start, cert_end]) common.sleep(1) if data['metadata']['count'] > 5: table.add_row(['...', '...', '...', '...', '...']) table.add_row(['Total Results', data['metadata']['count'], "", "", ""]) print(color + str(table) + common.bcolors.ENDC)
def onClick_1215(self): if self.YesNoDialog(31994): if not self._isrecoveryrunnung(): self.setPropertyControlDisable(1215) self.info("Starting system backup process") self._lock() common.runBuiltinCommand("RunScript", "service.clue", "service.recovery,mode=backup") common.setSkinProperty(10000, "SystemRecovery.Running", "true") while self._isrecoveryrunnung(): common.sleep() self._unlock() self.setPropertyControlEnable(1215) else: self.warn("System backup process is already running")
def download_all_financial_sheet(stock_code): utils.clean_directory(finance_sheet_directory(stock_code)) try: for sheet_type, sheet_info in sheet_types.items(): for sheet_part in sheet_info['parts']: for term_type in sheet_info['terms']: _download_sheet(stock_code, sheet_type, term_type, sheet_part) utils.sleep(1) except Exception as e: logger.error( 'download_all_financial_sheet(stock_code[{}]) failed.{}'.format( stock_code, error.exception_string(e))) utils.clean_directory(finance_sheet_directory(stock_code)) raise e
def onClick_1216(self): if self.YesNoDialog(31995): if not self._isupdaterunnung(): self.setPropertyControlDisable(1216) self.info("Starting system update process") self._lock() common.runBuiltinCommand("RunScript", "service.clue", "service.sysupdate,silent=off") common.setSkinProperty(10000, "SystemUpdate.Running", "true") while self._isupdaterunnung(): common.sleep() self._unlock() self.setPropertyControlEnable(1216) else: self.warn("System update process is already running")
def run(self, *args): params = self.params(args) if "mode" in params: self.mode = params['mode'] if params['mode'] in [ "backup", "restore" ] else "backup" if not self._isrunnung(): self.info("Starting system recovery process in %s mode" % self.mode) common.runBuiltinCommand("RunScript", "program.recovery", "mode=%s" % self.mode) while self._isrunnung(): common.sleep() self.info("Ending system recovery process") else: self.warn("Recovery process is already running")
def run(self, *args): params = self.params(args) if "silent" in params: self.silent = self.any2bool(params['silent']) common.setSkinProperty(10000, "SystemUpdate.Running", "true") update = self.sys.check_updates() if update is not None: common.DlgNotificationMsg(32903, time=7500) common.sleep(10) update = self.sys.doanload_updates() if update: if not self.silent: common.AskRestart(32904) else: self.notice("Reboot system to apply downloaded release update") common.runBuiltinCommand("Reboot") common.setSkinProperty(10000, "SystemUpdate.Running")
def main(): init.preInit() init.setupGit() init.postInit() if not hasHandlers(): print("No handlers defined, exiting.") exit(0) if env.CD_LOCAL_MODE == 'false': setInterruptHandlers() lastConfig = 0 while stillAlive(): # refresh config token once an hour if time.time() - lastConfig > 60 * 60: print('Refreshing Kube config') init.generateKubeconfig() lastConfig = time.time() if stillAlive(): fetchAndSaveNewEvents() # keep dispatching events until all have been dispatched # unless an interrupt arrives which we catch so we can finish the current dispatch call while stillAlive() and processNextEvent(): sleep(1) #will prevent busyloop in case of a bug of some sort # finished processing all events, take a break if stillAlive(): sleep(60) print("Clean exit.") exit(0) else: print("Running in local mode: no comments an no status updates in GH, reading events from /app/testEvents.json") init.generateKubeconfig() print("Running handlers for events in /app/testEvents.json") with open("/app/testEvents.json") as f: events = json.load(f) for event in events: runHandlers(event, False) for event in events: runHandlers(event, True) print("Clean exit.")
def test_basic_format(self): """Play a game. Communication between nodes, and with the matchmaking server should be logged in a file in a ShiViz compatible format. """ ms_srv = common.MatchMakingServer(2222) ms_srv.start() common.sleep(2) clients = common.start_multiple_clients(ms_srv.port, 2) # Wait for a bit to make sure a game starts and is played for a while. common.sleep(common.MatchMakingServer.GAME_START_TIMEOUT * 1.1) # This regex is supposed to match lines like: # localhost:9990 {"localhost:9990":2} # 127.0.0.1:2222 {"127.0.0.1:2222":2, "localhost:9999":2} # Lines in this format are consumable by ShiViz. govector_log_regex = re.compile( r'(.*:\d{4,5}?) {(".*:\d{4,5}?":\d*)(, ".*:\d{4,5}?":\d*)*}') with open(ms_srv.govector_log_path) as log_file: lines = log_file.readlines() for line in lines[0::2]: match = govector_log_regex.match(line) self.assertIsNotNone(match, "Line '{}' should be ShiViz compat".format(line)) self.assertEquals(match.group(1), "127.0.0.1:{}".format(ms_srv.port), "Sender should be the MS") for line in lines[1::2]: self.assertIsNone(govector_log_regex.match(line), "Line '{}' should be regular text".format(line)) for client in clients: with open(client.govector_log_path) as log_file: lines = log_file.readlines() for line in lines[0::2]: self.assertIsNotNone(govector_log_regex.match(line), "Line '{}' should be ShiViz compat".format(line)) for line in lines[1::2]: self.assertIsNone(govector_log_regex.match(line), "Line '{}' should be regular text".format(line))
def refreshOrderList(): cm.clickPointPNG('imgs/marketordersbutton.png', 10, 10, cache=True) cm.sleep(0.2) cm.clickPointPNG('imgs/marketordersbutton.png', 10, 10, cache=True) cm.sleep(0.2) while pyautogui.locateOnScreen('imgs/myordersselling.png', confidence=0.9) is None: print("didnt properly reopen order list") cm.clickPointPNG('imgs/marketordersbutton.png', 10, 10, cache=True) cm.sleep(1)
def test_multi_client_failure(self): """A leader client (1) is started followed by two normal clients (2, 3, 4). 2 and 3 fail. 1 should stay as leader and broadcast that 2 and 3 failed to all other clients, and 4 should stay as a client. """ ms_srv = common.MatchMakingServer(2222) ms_srv.start() common.sleep(2) clients = common.start_multiple_clients(ms_srv.port, 4) common.sleep(common.MatchMakingServer.GAME_START_TIMEOUT * 0.9) # Kill client 2 and 3. client2 = clients[1] client2.kill() client3 = clients[2] client3.kill() # Wait for (unexpected, but potential) leader re-election to occur. common.sleep(8) leader = clients[0] with open(leader.local_log_path) as log_file: found_leader_msg = False found_node_msg = False for line in log_file: if common.line_indicates_leader(line): found_leader_msg = True continue elif common.line_indicates_node(line): found_node_msg = True continue self.assertFalse(found_node_msg, "Leader should never have been a node") self.assertTrue(found_leader_msg, "Leader should always been such") client4 = clients[3] with open(client4.local_log_path) as log_file: found_leader_msg = False found_node_msg = False for line in log_file: if common.line_indicates_leader(line): found_leader_msg = True continue elif common.line_indicates_node(line): found_node_msg = True continue self.assertTrue(found_node_msg, "Client 4 should have been a node at some point") self.assertFalse(found_leader_msg, "Client 4 should never have been a leader")
def test_client_failure(self): """A leader client (1) is started followed by two normal clients (2, 3). 2 fails, and the leader should inform all other clients that 2 has failed. 1 should stay the leader, 3 should stay as a client. """ ms_srv = common.MatchMakingServer(2222) ms_srv.start() common.sleep(2) clients = common.start_multiple_clients(ms_srv.port, 3) # XXX: This sleep is rather fragile because we need to resume after # the MS has started the game, but before the game has ended. common.sleep(common.MatchMakingServer.GAME_START_TIMEOUT * 0.9) # Kill client 2. client2 = clients[1] client2.kill() # Wait for (unexpected, but potential) leader re-election to occur. common.sleep(8) leader = clients[0] with open(leader.local_log_path) as log_file: found_leader_msg = False found_node_msg = False for line in log_file: if common.line_indicates_leader(line): found_leader_msg = True continue elif common.line_indicates_node(line): found_node_msg = True continue self.assertFalse(found_node_msg, "Leader should never have been a node") self.assertTrue(found_leader_msg, "Leader should always been such") client3 = clients[2] with open(client3.local_log_path) as log_file: found_leader_msg = False found_node_msg = False for line in log_file: if common.line_indicates_leader(line): found_leader_msg = True continue elif common.line_indicates_node(line): found_node_msg = True continue self.assertTrue(found_node_msg, "Client 3 should have been a node at some point") self.assertFalse(found_leader_msg, "Client 3 should never have been a leader")
def test_start_by_timeout(self): """c1 connects to the matchmaking server. Then c2 connects to the matchmaking server. When the countdown timer expires, the game starts. """ ms_srv = common.MatchMakingServer(2222) ms_srv.start() common.sleep(2) _ = common.start_multiple_clients(ms_srv.port, 1) # Wait for a while to make sure MS server logs that one client is # connected. common.sleep(7) client2 = common.Client(node_port=9003, node_rpc_port=9002, ms_port=ms_srv.port, http_srv_port=9001) client2.start() common.sleep(common.MatchMakingServer.GAME_START_TIMEOUT) starting_game_found = False one_player_found = False two_players_found = False with open(ms_srv.local_log_path) as log_file: for line in log_file: if "Starting Game" in line: starting_game_found = True continue elif "1 players" in line: one_player_found = True continue elif "2 players" in line: two_players_found = True continue self.assertTrue(one_player_found, ("MS server should have been connected to by one " "player at some point")) self.assertTrue(two_players_found, ("MS server should have been connected to by two " "players at some point")) self.assertTrue(starting_game_found, "Game should have started")
def sellitemininventory(typeid, price): item = api.getNameFromID(typeid) cm.clickPointPNG('imgs/inventorytopright.png', 0, 25, 2, cache=True) cm.sleep(0.2) cm.safetypewrite(item) stackitems(item) cm.sleep(0.5) thing = pyautogui.locateOnScreen('imgs/inventoryitemhangar.png') inventorylist = cm.Area(thing.left + 25, thing.top + 70, 500, 250) cm.sleep(1) box = inventorylist.toAbsTuple() ocr = cm.grabandocr(box) #todo implement ocr with highestsim check for s in ocr.splitlines(): if (s.split()[-1][:5] in item.lower()): offsetpos = inventorylist mousex = offsetpos.x + int(s.split()[6]) / 4 + 5 mousey = offsetpos.y + int(s.split()[7]) / 4 + 5 cm.clickxy(mousex, mousey, clicks=1, right=True) cm.sleep(0.2) box = (mousex + 15, mousey + 2, mousex + 15 + 135, mousey + 3 + 200) ocr = cm.grabandocr(box) for s in ocr.splitlines(): if (s.split()[-1] == "sell"): mousex = mousex + 18 + int(s.split()[6]) / 4 + 5 mousey = mousey + 3 + int(s.split()[7]) / 4 + 5 cm.clickxy(mousex, mousey) cm.sleep(5) #todo replace this with clickpointpng thing = pyautogui.locateOnScreen('imgs/sellitems.png') pricefield = cm.Point(thing.left + thing.width / 2, thing.top + 80) thing = pyautogui.locateOnScreen( 'imgs/sellitemsellcancel.png') sellbutton = cm.Point(thing.left + 25, thing.top + 12) thing = pyautogui.locateOnScreen( 'imgs/sellitemduration.png') duration = cm.Point(thing.left - 50, thing.top + 28) #set duration to 3 months cm.clickPoint(duration) for _ in range(10): pyautogui.press('down') cm.clickPoint(duration) #set price pyautogui.moveTo(pricefield.x, pricefield.y) cm.sleep(0.3) pyautogui.doubleClick(pricefield.x, pricefield.y) cm.safetypewrite(price) cm.clickPoint(sellbutton) cm.sleep(0.5) thing = pyautogui.locateOnScreen( 'imgs/sellitemconfirm.png') confirmbutton = cm.Point(thing.left + 145, thing.top + 193) cm.clickPoint(confirmbutton) thing = pyautogui.locateOnScreen("imgs/warning.png", confidence=0.9) if thing is not None: cm.clickPointPNG("imgs/yesno.png", 20, 10) return 1 return 0
def buyorder(typeid, price, quantity): quickbar.openItem(typeid) cm.sleep(3) thing = pyautogui.locateOnScreen('imgs/placebuyorder.png') buyorderpos = cm.Point(thing.left + thing.width / 2, thing.top + thing.height / 2) cm.clickPoint(buyorderpos) cm.sleep(2) thing = pyautogui.locateOnScreen('imgs/buyorderadvanced.png') if thing is not None: advanced = cm.Point(thing.left + thing.width / 2, thing.top + thing.height / 2) cm.clickPoint(advanced) cm.sleep(1) thing = pyautogui.locateOnScreen('imgs/buyorderoriginpoint.png') bidpricefield = cm.Point(thing.left + 143, thing.top + 33) quantityfield = cm.Point(thing.left + 143, thing.top + 169) duration = cm.Point(thing.left + 143, thing.top + 190) threemonths = cm.Point(thing.left + 143, thing.top + 332) buything = pyautogui.locateOnScreen('imgs/buyandcancel.png') buybutton = cm.Point(buything.left + 25, buything.top + 7) cm.clickPoint(bidpricefield, 2) cm.sleep(0.3) cm.safetypewrite(price) cm.clickPoint(quantityfield, 2) cm.sleep(0.3) cm.safetypewrite(quantity) cm.clickPoint(duration) for _ in range(10): pyautogui.press('down') cm.clickPoint(duration) cm.clickPoint(buybutton, 1) cm.sleep(0.6) thing = pyautogui.locateOnScreen('imgs/confirmorder.png') confirmyes = cm.Point(thing.left + 149, thing.top + 197) cm.clickPoint(confirmyes) thing = pyautogui.locateOnScreen("imgs/warning.png", confidence=0.9) if thing is not None: cm.clickPointPNG("imgs/yesno.png", 20, 10)
def getTopOrders(typeid): quickbar.openItem(typeid) cm.sleep(0.2) marketlogsfolder = os.path.expanduser( '~\\Documents\\EVE\\logs\\Marketlogs') deleteMarketLogs() cm.clickPointPNG("imgs/exporttofile.png", 5, 5, cache=True) loopidx = 0 while True: if (len(os.listdir(marketlogsfolder)) > 0): print("found file in marketlogs...") break if loopidx % 5 == 0: print("didn't open item") quickbar.openItem(typeid) cm.clickPointPNG("imgs/exporttofile.png", 5, 5, cache=True) else: cm.sleep(0.5) loopidx += 1 if os.listdir(marketlogsfolder)[-1].startswith('My Orders'): print("wrong file exported") return getTopOrders(typeid) logfile = marketlogsfolder + "\\" + os.listdir(marketlogsfolder)[-1] buyorders, sellorders = [], [] exitflag = False try: with open(logfile) as export: reader = csv.DictReader(export) for l in reader: #if we didnt wait long enough for item to load if (int(l['typeID']) != typeid): exitflag = True break if (int(l['jumps']) != 0): continue o = cm.Order(typeid, int(l['orderID']), str(l['bid']) == "True", float(l['price']), int(float(l['volEntered'])), int(float(l['volRemaining'])), DateUtilParser(l['issueDate']).timestamp()) if (o.bid): buyorders.append(o) else: sellorders.append(o) os.remove(logfile) except: print("exception while reading item export") cm.sleep(5) return getTopOrders(typeid) if (exitflag): print("wrong item was exported") quickbar.addItemToQuickbar(typeid) return getTopOrders(typeid) #highest first buyorders.sort(key=lambda x: x.price, reverse=True) #lowest first sellorders.sort(key=lambda x: x.price, reverse=False) return (buyorders[0:6], sellorders[0:6])
def show(): cm.clickPointPNG('imgs/regionalmarkettopleft.png', 76, 58, cache=True) cm.sleep(0.5)
def test_client_then_leader_failure(self): """A leader client (1) is started followed by three normal clients (2, 3, 4). 3 fails followed by the leader client failing. 2 should become the new leader and inform all other clients that 3 has failed, and 4 should stay as a client. """ ms_srv = common.MatchMakingServer(2222) ms_srv.start() common.sleep(2) clients = common.start_multiple_clients(ms_srv.port, 4) # XXX: This sleep is rather fragile because we need to resume after # the MS has started the game, but before the game has ended. common.sleep(common.MatchMakingServer.GAME_START_TIMEOUT * 0.9) # Kill client 3 and leader. client3 = clients[2] client3.kill() leader = clients[0] leader.kill() # Wait for leader re-election to occur. common.sleep(8) client2 = clients[1] with open(client2.local_log_path) as log_file: found_leader_msg = False found_node_msg = False found_node_msg_after_leader = False for line in log_file: if common.line_indicates_leader(line): found_leader_msg = True continue elif common.line_indicates_node(line): found_node_msg = True if found_leader_msg: found_node_msg_after_leader = True continue self.assertTrue(found_node_msg, "Client 2 should have been a node at some point") self.assertTrue(found_leader_msg, "Client 2 should have become the leader") self.assertFalse(found_node_msg_after_leader, "Client 2 should not have turn back into a node") client4 = clients[3] with open(client4.local_log_path) as log_file: found_leader_msg = False found_node_msg = False for line in log_file: if common.line_indicates_leader(line): found_leader_msg = True continue elif common.line_indicates_node(line): found_node_msg = True continue self.assertTrue(found_node_msg, "Client 4 should have always been a node") self.assertFalse(found_leader_msg, "Client 4 should never have been a leader")
def loadOrders(): itemhandlerlist = variables.itemhandlerlist marketlogsfolder = os.path.expanduser( '~\\Documents\\EVE\\logs\\Marketlogs') deleteMarketLogs() cm.exportMyOrders() loopidx = 0 while True: if (len(os.listdir(marketlogsfolder)) > 0): break thing = pyautogui.locateOnScreen("imgs/nobuyorsell.png", confidence=0.9) if thing is not None: okbutton = cm.Point(thing.left + 169, thing.top + 194) cm.clickPoint(okbutton) return if loopidx % 5 == 0: cm.exportMyOrders() else: cm.sleep(0.5) loopidx += 1 if not os.listdir(marketlogsfolder)[-1].startswith('My Orders'): return loadOrders() logfile = marketlogsfolder + "\\" + os.listdir(marketlogsfolder)[-1] neworders = [] try: with open(logfile) as export: reader = csv.DictReader(export) for l in reader: neworders.append( cm.Order(int(l['typeID']), int(l['orderID']), str(l['bid']) == "True", float(l['price']), int(float(l['volEntered'])), int(float(l['volRemaining'])), DateUtilParser(l['issueDate']).timestamp())) os.remove(logfile) except: cm.sleep(5) return loadOrders() for no in neworders: if not any(no.typeid == ih.typeid for ih in itemhandlerlist): print("initiating leftoveritemhandler for order:" + api.getNameFromID(no.typeid)) itemhandlerlist.append(cm.LeftoverItemHandler(no.typeid, [], None)) quickbar.addItemToQuickbar(no.typeid) #sort each neworder back into the itemhandlers for itemhandler in itemhandlerlist: itemhandler.sellorderlist = [] itemhandler.buyorder = None for no in neworders: if (itemhandler.typeid == no.typeid): if no.bid: itemhandler.buyorder = no else: itemhandler.sellorderlist.append(no)
import common from requests.adapters import HTTPAdapter import time # import logging # logging.basicConfig(level=logging.DEBUG) s = requests.session() s.mount('http://', HTTPAdapter(max_retries=5)) url = "https://laravel-china.org/users/%d" uid = 0 while True: uid+=1 response = s.get(url % uid) if response.status_code != 200: common.sleep(uid) continue e = etree.HTML(response.content) name = e.xpath("//h3[@class='media-heading']/text()")[0].strip() label = e.xpath("//a[@class='label label-success role']/text()") if label: label = label[0] else: label = "" followers = e.xpath("//div[@class='follow-info row']/div[1]/a/text()")[0] discuss = e.xpath("//div[@class='follow-info row']/div[2]/a/text()")[0] article = e.xpath("//div[@class='follow-info row']/div[3]/a/text()")[0] row = {'uid': uid, 'name': name, 'label': label, 'followers': followers, 'discuss': discuss, 'article': article} common.save_mysql(row)
def getImageList(self, params): common.trace("Starting to search images using parameters: %s" %str(params), "duckgo") images = [] if params.get('mbid', '') == '': common.warn("No artist identified over MusicBrainz, search stopped") return images if "fullname" in params and not common.isempty(params['fullname']): keywords = params['fullname'] + " AND (singer OR band)" elif "alias" in params and not common.isempty(params['alias']): keywords = params['alias'] + " AND (singer OR band)" elif "artist" in params and not common.isempty(params['artist']): keywords = params['artist'] + " AND (singer OR band)" else: keywords = None if keywords is not None and "location" in params and not common.isempty(params['location']): keywords = keywords + " AND " + params['location'] elif keywords is not None and "lang" in params and not common.isempty(params['lang']): keywords = keywords + " AND " + params['lang'] if keywords is not None: payload = {'q': keywords} common.trace("Hitting DuckDuckGo for token", "duckgo") data = common.urlcall(self.DDG_SEARCH_URL, "POST", payload=payload) searchObj = re.search(r'vqd=([\d-]+)\&', data, re.M | re.I) if not searchObj: common.error("Token parsing failed!", "duckgo") return images else: common.debug("Obtained token: %s" % searchObj.group(1), "duckgo") headers = { 'authority': 'duckduckgo.com', 'accept': 'application/json, text/javascript, */*; q=0.01', 'sec-fetch-dest': 'empty', 'x-requested-with': 'XMLHttpRequest', 'user-agent': common.agent(), 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'referer': 'https://duckduckgo.com/' } payload = { "q": keywords, "vqd": searchObj.group(1), "v7exp": "a", "o": "json", "l": "wt-wt", "f": ",,,", "p": '1' } data = None while True: try: data = common.urlcall(self.DDG_SEARCH_URL + "i.js", headers=headers, payload=payload, output='json') break except ValueError as e: common.trace("Calling url failure; sleep and retry", "duckgo") common.sleep(500) continue index = 0 max = common.any2int(params['limit'], 0) for obj in data["results"]: contextual = str(obj["title"].encode('utf-8')).lower().find(params['artist'].lower() + " ") >= 0 dimension = int(obj["width"]) >= 876 if common.any2bool(params.get('getall', 'false')) else int(obj["width"]) >= 1920 if contextual and dimension: index += 1 images.append(obj["image"]) if max > 0 and index >= max: break if not images: return [] else: return self._delExclusions(images, params.get('exclusionsfile'))
def read_fifo(self, dest, grp_no, mem_no, nwords, woffset=0): """ Get data from ADC unit's DDR memory. Readout is robust (retransmit on failure) and congestion-aware (adjusts an amount of data per request). Attrs: dest: an object which has a `push(smth)' method and an `index' property. grp_no: ADC group number. mem_no: memory unit number. nwords: number of words to read to dest. woffset: index of the first word. Returns: Number of words. """ #TODO: make finished an argument by ref, so we can get the value even after Except fifo_addr = SIS3316_FPGA_ADC_GRP_MEM_BASE + grp_no * SIS3316_FPGA_ADC_GRP_MEM_OFFSET # Network congestion window: wcwnd_limit = FIFO_READ_LIMIT wcwnd = wcwnd_limit/2 wcwnd_max = wcwnd_limit/2 wmtu = 1440/4 #TODO: determine MTU automatically (can be jumbo frames) wfinished = 0 binitial_index = dest.index while wfinished < nwords: try: # Configure FIFO self._fifo_transfer_reset(grp_no) #cleanup self._fifo_transfer_read(grp_no, mem_no, woffset + wfinished) except self._WrongResponceExcept: #some trash in socket self.cleanup_socket() #~ print "<< trash in socket" sleep(self.default_timeout) continue except self._TimeoutExcept: sleep(self.default_timeout) continue #FIXME: Retry on timeout forever?! # Data transmission while wfinished < nwords: try: wnum = min(nwords - wfinished, FIFO_READ_LIMIT, wcwnd) msg = b''.join(( '\x30', pack('<HI', wnum-1, fifo_addr) )) # Morgan pack_id = b'\x22' msg = b''.join(( '\x30', pack_id, pack('<HI', wnum-1, fifo_addr) )) self._req(msg) self._ack_fifo_read(dest, wnum) # <- exceptions are most probable here if wcwnd_max > wcwnd: #recovery after congestion wcwnd += (wcwnd_max - wcwnd)/2 else: #probe new maximum wcwnd = min(wcwnd_limit, wcwnd + wmtu + (wcwnd - wcwnd_max) ) except self._UnorderedPacketExcept: # sotffail: some packets accidently was dropped #~ print "<< unordered", wcwnd break except self._TimeoutExcept: # hardfail (network congestion) wcwnd_max = wcwnd wcwnd = wcwnd / 2 # Reduce window by 50% #~ print wcwnd, '%0.3f%%'% (1.0 * wfinished/nwords * 100,) , 'cwnd reduced' break finally: # Note: executes before `break' bfinished = (dest.index - binitial_index) assert bfinished % 4 == 0, "Should read a four-byte words. %d, init %d" %(bfinished, binitial_index) wfinished = bfinished/4 #end while if wcwnd is 0: raise self._TimeoutExcept("many") #end while self._fifo_transfer_reset(grp_no) #cleanup return wfinished
def changeOrder(order, newprice): refreshOrderList() position, itemsinlist = getOrderPosition(order) itemname = api.getNameFromID(order.typeid) print("changing order of item: " + itemname + " in position: " + str(position)) if order.bid: actingPoint, listheight = variables.bidaplh else: actingPoint, listheight = variables.sellaplh pyautogui.moveTo(actingPoint.x, actingPoint.y) cm.sleep(0.2) #this scrolls so the order is visible, and adjusts the position itemsfitinlist = math.ceil(listheight / 20) if (position >= itemsfitinlist): pagescrollcount = math.floor(position / itemsfitinlist) position -= (itemsinlist % itemsfitinlist) pyautogui.scroll(int(-130 * itemsfitinlist * pagescrollcount)) pyautogui.move(0, 20 * position) pyautogui.click(button='right', clicks=1) cm.sleep(0.5) pyautogui.move(35, 10) cm.sleep(0.5) pyautogui.click() thing = pyautogui.locateOnScreen("imgs/modifyorder.png", confidence=0.9) for a in range(100): if thing is None: thing = pyautogui.locateOnScreen("imgs/modifyorder.png", confidence=0.9) cm.sleep(0.2) else: break if thing is None: refreshAllOrders() return changeOrder(order, newprice) box = cm.Area(thing.left + 100, thing.top + 21, 300, 19) ocr = cm.grabandocr(box).splitlines() ocrname = "" for line in ocr: if (len(line.split()) > 11): ocrname += line.split()[-1] + " " print("checking if we clicked the right order...") print("itemname: " + itemname.lower() + ", ocrname: " + ocrname) if cm.similar(ocrname.lower(), itemname.lower()) < 0.5: print("failed similar check") cm.clickxy(thing.left + 265, thing.top + 192) cm.sleep(0.5) refreshAllOrders() return changeOrder(order, newprice) cm.sleep(0.2) pyautogui.keyDown('ctrl') pyautogui.keyDown('c') cm.sleep(0.2) pyautogui.keyUp('c') pyautogui.keyUp('ctrl') realprice = pyperclip.paste() cm.safetypewrite(newprice) cm.sleep(0.2) pyautogui.typewrite(['enter']) cm.sleep(0.5) thing = pyautogui.locateOnScreen("imgs/warning.png", confidence=0.9) if thing is not None: cm.clickPointPNG("imgs/yesno.png", 20, 10) #reset scroll pyautogui.moveTo(actingPoint.x + 10, actingPoint.y + 10) pyautogui.scroll(100000) order.price = float(newprice) order.issuedate = cm.getEVETimestamp()
def create_setup(): """Copy files from template and update them with user input.""" global app_name, app_version, app_license, app_author, app_email, \ app_url, app_keywords, DEFAULT_AUTHOR, DEFAULT_EMAIL, \ DEFAULT_LICENSE, DEFAULT_URL, DEFAULT_VERSION data_lst = common.load_data() if data_lst: (DEFAULT_AUTHOR, DEFAULT_EMAIL, DEFAULT_LICENSE, DEFAULT_URL, DEFAULT_VERSION) = data_lst while not app_name: app_name = input(lcl.Q_APP_NAME).decode(lcl.INPUT_ENC) app_version = input(lcl.Q_APP_VERSION + '[' + DEFAULT_VERSION + '] ').decode(lcl.INPUT_ENC) if not app_version: app_version = DEFAULT_VERSION app_license = input(lcl.Q_APP_LICENSE + '[' + DEFAULT_LICENSE + '] ').decode(lcl.INPUT_ENC) if not app_license: app_license = DEFAULT_LICENSE app_author = input(lcl.Q_APP_AUTHOR + '[' + DEFAULT_AUTHOR + '] ').decode(lcl.INPUT_ENC) if not app_author: app_author = DEFAULT_AUTHOR app_email = input(lcl.Q_APP_EMAIL + '[' + DEFAULT_EMAIL + '] ').decode(lcl.INPUT_ENC) if not app_email: app_email = DEFAULT_EMAIL app_url = input(lcl.Q_APP_URL + '[' + DEFAULT_URL + '] ').decode(lcl.INPUT_ENC) if not app_url: app_url = DEFAULT_URL app_keywords = input(lcl.Q_APP_KEYWORDS).decode(lcl.INPUT_ENC) if not app_keywords: app_keywords = app_name data_lst = [app_author, app_email, app_license, app_url, app_version] common.save_data(data_lst) app_url += app_name # backup existing files backup = False filenames = glob.glob('*') filenames += glob.glob('.*') if filenames: backup = True os.mkdir(BAK_DIR) for filename in filenames: dest = BAK_DIR + '/' + filename.split(os.sep)[-1] shu.move(filename, dest) filenames = glob.glob(common.DATA_PATH + 'template/*') filenames += glob.glob(common.DATA_PATH + 'template/.*') # remove doc dir filenames = [filename for filename in filenames if 'template' + os.sep + 'doc' not in filename] # copy files and dirs for filename in filenames: if os.path.isfile(filename): shu.copyfile(filename, filename.split(os.sep)[-1]) else: shu.copytree(filename, filename.split(os.sep)[-1]) common.sleep(2) os.rename('APPLICATION_NAME', app_name) # rename application dir # collect all filenames, including from 1st level subdirs filenames = glob.glob('*') filenames = [filename for filename in filenames if BAK_DIR not in filename] filenames += glob.glob('.*') new_filenames = [] for filename in filenames: if os.path.isdir(filename): new_filenames += glob.glob(filename + '/*') filenames += new_filenames exceptions = ['__init__.py', 'build.cmd', 'requirements.txt', 'requirements-dev.txt', 'setup.py', 'setup_py2exe.py', 'setup_utils.py'] # delete .pyc files and update files for filename in filenames: if os.path.isfile(filename): if '.pyc' in filename: os.remove(filename) else: if filename.split(os.sep)[-1] not in exceptions: update_file(filename) create_redir2rtd_zip() if backup: os.remove(app_name + APPLICATION_TEMPLATE_FILE) # remove app template # restore files from backup, but only if they don't already exist filenames = glob.glob(BAK_DIR + '/*') for filename in filenames: dest = app_name + '/' + filename.split(os.sep)[-1] if not os.path.isfile(dest): shu.copyfile(filename, dest) else: os.rename(app_name + APPLICATION_TEMPLATE_FILE, app_name + '/' + app_name + '.py') # rename app template print(lcl.REMINDERS)
def refreshAllOrders(): itemhandlerlist = variables.itemhandlerlist marketlogsfolder = os.path.expanduser( '~\\Documents\\EVE\\logs\\Marketlogs') deleteMarketLogs() cm.exportMyOrders() loopidx = 0 while True: if (len(os.listdir(marketlogsfolder)) > 0): break thing = pyautogui.locateOnScreen("imgs/nobuyorsell.png", confidence=0.9) if thing is not None: okbutton = cm.Point(thing.left + 169, thing.top + 194) cm.clickPoint(okbutton) return if loopidx % 5 == 0: cm.exportMyOrders() else: cm.sleep(0.5) loopidx += 1 if not os.listdir(marketlogsfolder)[-1].startswith('My Orders'): return refreshAllOrders() logfile = marketlogsfolder + "\\" + os.listdir(marketlogsfolder)[-1] neworders = [] try: with open(logfile) as export: reader = csv.DictReader(export) for l in reader: neworders.append( cm.Order(int(l['typeID']), int(l['orderID']), str(l['bid']) == "True", float(l['price']), int(float(l['volEntered'])), int(float(l['volRemaining'])), DateUtilParser(l['issueDate']).timestamp())) os.remove(logfile) except: cm.sleep(5) return refreshAllOrders() oldorders = [] for itemhandler in itemhandlerlist: ihcopy = copy.deepcopy(itemhandler) if ihcopy.buyorder is not None: oldorders.append(ihcopy.buyorder) if ihcopy.sellorderlist: oldorders += ihcopy.sellorderlist newfromoldorders = [] #the newfromoldorders list will contain every order even finished ones, the itemhandler will remove those in its handle func for oo in oldorders: curorder = copy.deepcopy(oo) for no in neworders: if areOrdersTheSame(oo, no): curorder.volremaining = no.volremaining if (curorder.volremaining > curorder.volentered): curorder.volremaining = curorder.volentered if (curorder.orderid == -1): curorder.orderid = no.orderid curorder.issuedate = no.issuedate break curorder.finished = ( not any(areOrdersTheSame(oo, no) for no in neworders) and cm.getEVETimestamp() - oo.issuedate > 20) newfromoldorders.append(curorder) #the order export can be heavily delayed sometimes, so we just add old orders that are freshly made for oo in oldorders: if (not any(areOrdersTheSame(nfo, oo) for nfo in newfromoldorders) and cm.getEVETimestamp() - oo.issuedate < 20): newfromoldorders.append(oo) #sort each neworder back into the itemhandlers for itemhandler in itemhandlerlist: itemhandler.sellorderlist = [] itemhandler.buyorder = None for nfo in newfromoldorders: if (itemhandler.typeid == nfo.typeid): if nfo.bid: itemhandler.buyorder = nfo else: itemhandler.sellorderlist.append(nfo)
common.debug( str(selectedRestore) + ": " + params['archive']) else: common.DlgNotificationMsg(common.translate(30045), time=5000) common.debug(params['archive'] + ' is not a valid restore point') else: # allow user to select the backup to restore from selectedRestore = common.SelectDialog( title=common.translate(30021), options=pointNames) if selectedRestore != -1: recovery.doSelectRestore(restorePoints[selectedRestore][0]) common.DlgNotificationMsg(common.translate(30055), time=5000) elif mode == recovery.Backup: common.DlgNotificationMsg(common.translate(30054), time=5000) # execute selected operation (Backup or Restore) execute = recovery.run(mode) if execute: if mode == recovery.Restore: common.DlgNotificationMsg(common.translate(30057), time=5000) common.sleep(5000) if common.YesNoDialog(common.translate(30058)): common.restart() elif mode == recovery.Backup: common.DlgNotificationMsg(common.translate(30056), time=5000) else: # can't go any further common.OkDialog(common.translate(30045)) common.Addon().openSettings()
def test_method(self): # 1.Create an app (retcode, output) = rhtest.TestStep(self, "1. Create a %s app"%self.variant, common.create_app, function_parameters=[self.app_name, self.app_type, self.user_email, self.user_passwd], expect_description="the app should be created successfully", expect_return=0)() # 2.Create thread dump log file (retcode, output) = rhtest.TestStep(self, "2.Create thread dump log file", "rhc threaddump %s -l %s -p '%s' %s" % (self.app_name, self.user_email, self.user_passwd, common.RHTEST_RHC_CLIENT_OPTIONS), expect_description="the app should be created successfully", expect_return=0, expect_str = ["RESULT:\nSuccess"])() # 3.Use rhc tail to tail thread dump log file in a subprocess try: obj = re.search(r"The thread dump file.* -f ([^\s]+)", output) logfile = obj.group(1) except: return self.abort("Unable to find logfile from recent stdout") cmd = "stdbuf -o0 rhc tail %s -l %s -p '%s' -f %s -o '-n +1' %s" %(self.app_name, self.user_email, self.user_passwd, logfile, common.RHTEST_RHC_CLIENT_OPTIONS) (retcode, output) = rhtest.TestStep(self, "3.Run 'rhc tail' in a subprocess", self.create_proc, function_parameters=[cmd], expect_return = 0, expect_description="'rhc tail' should be started")() # 4.Check the output if self.variant == 'jbossas': regex = ["DeploymentScanner-threads", "Periodic Recovery", "Transaction Reaper"] elif self.variant in ("ruby", "ruby-1.9"): regex = ["Current thread", "backtrace dump"] for r in regex: (retcode, output) = rhtest.TestStep(self, "4.Check the output", self.p.grep_output, function_parameters=[r, 3, 5, 0, False], expect_description="'%s' should be found in the output" % (r), expect_return=0)() # 5.Check the output if self.variant == 'jbossas': regex = "DestroyJavaVM" (retcode, output) = rhtest.TestStep(self, "5.Check the output", self.p.grep_output, function_parameters=[regex, 3, 5, 0, False], expect_description="'%s' should be found in the output" % (regex), expect_return=0)() # 8.Restart the app (retcode, output) = rhtest.TestStep(self, "6.Restart the app", "rhc app restart %s -l %s -p '%s' %s" % (self.app_name, self.user_email, self.user_passwd, common.RHTEST_RHC_CLIENT_OPTIONS), expect_description="App should be restarted", expect_return=0)() # 9.Check the output if self.variant == 'jbossas': common.sleep(30) #regex = "CORBA Naming Service started" regex = ["ORB Run Thread"] elif self.variant in ("ruby", "ruby-1.9"): regex = ["spawn_rack_application", "spawn_application"] for r in regex: (retcode, output)= rhtest.TestStep(self, "7.Check the output", self.p.grep_output, function_parameters=[r, 3, 5, 0], expect_description="'%s' should be found in the output" % (r), expect_return=0)() return self.passed("%s passed" % self.__class__.__name__)
def addItemToQuickbar(typeid): dontShow() itemname = api.getNameFromID(typeid) pyautogui.moveTo(200, 10) pyautogui.sleep(0.3) thing = pyautogui.locateOnScreen('imgs/regionalmarkettopleft.png', confidence=0.9) thing2 = pyautogui.locateOnScreen('imgs/search.png', confidence=0.9) if thing is None or thing2 is None: print("im blind") return addItemToQuickbar(typeid) search_market(itemname) cm.sleep(4) searchareacapturepos = cm.Area(thing.left, thing.top + 100, thing2.left - thing.left + 50, 400) for loopidx in range(20): ocr = cm.grabandocr(searchareacapturepos) ocrlines = ocr.splitlines() if loopidx == 10: search_market(itemname) cm.sleep(0.5) stringdict = {} curstring = "" for idx, s in enumerate(ocrlines): s = s.lower() if (len(s.split()) <= 11 or len(s.split()[-1]) < 2): if curstring: stringdict[curstring.strip()] = idx - 1 curstring = "" else: curstring += s.split()[-1] + " " if (idx == len(ocrlines) - 1): stringdict[curstring.strip()] = idx - 1 highestsim = -1 bestidx = 0 for s in stringdict: cursim = cm.similar(itemname.lower(), s) if cursim > highestsim: highestsim = cursim bestidx = stringdict[s] if (highestsim > 0.8): s = ocrlines[bestidx] print("found item in search results: " + s) offsetpos = searchareacapturepos mousex = offsetpos.x + int(s.split()[6]) / 4 + 5 mousey = offsetpos.y + int(s.split()[7]) / 4 + 5 cm.clickxy(mousex, mousey) cm.sleep(1.5) thing = pyautogui.locateOnScreen('imgs/search.png', confidence=0.9) marketnamearea = cm.Area(thing.left + 158, thing.top + 14, 375, 30) ocr = cm.grabandocr(marketnamearea) marketname = "" for line in ocr.splitlines(): if len(line.split()) > 11: marketname += line.split()[-1] + ' ' #strips marketname of whitespace and the list 4 characters, which should be: " i ©" marketname = marketname.strip()[:-4] print("read marketname while adding item: " + marketname) #marketname is the ocr result, itemname is the actual item were trying to add if (cm.similar(marketname.lower(), itemname.lower()) < 0.75): print("clicked wrong item while adding, retrying") return addItemToQuickbar(typeid) cm.clickxy(mousex, mousey, right=True) cm.sleep(0.2) cm.clickxy(mousex + 52, mousey + 29) print("old itemlist:") print(itemlist) if itemname not in itemlist: itemlist.append(itemname) itemlist.sort(key=str.lower) print("new itemlist:") print(itemlist) return if loopidx > 12: #we only get here if it didnt find an item: the item must have been in a collapsed category for s in ocr.splitlines(): if (len(s.split()) > 11 and len(s.split()[-1]) > 3): #we do NOT want to open the blueprint category if not "prints" in s and not "react" in s: offsetpos = searchareacapturepos mousex = offsetpos.x + int(s.split()[6]) / 4 + 5 mousey = offsetpos.y + int(s.split()[7]) / 4 + 5 cm.clickxy(mousex, mousey) break cm.sleep(0.5) print("looped through item adding a lot without success, aborting") sys.exit()
def wait(self, time): common.sleep(time * 1000)
def cancelOrder(order): if (order is None or order.finished or not order.canChange()): print("Invalid cancel, ignoring") return refreshOrderList() refreshAllOrders() position, itemsinlist = getOrderPosition(order) print("cancelling buyorder: " + api.getNameFromID(order.typeid)) if order.bid: actingPoint, listheight = variables.bidaplh else: actingPoint, listheight = variables.sellaplh pyautogui.moveTo(actingPoint.x, actingPoint.y) cm.sleep(0.2) #this scrolls so the order is visible, and adjusts the position itemsfitinlist = math.ceil(listheight / 20) if (position >= itemsfitinlist): pagescrollcount = math.floor(position / itemsfitinlist) position -= (itemsinlist % itemsfitinlist) pyautogui.scroll(int(-130 * itemsfitinlist * pagescrollcount)) pyautogui.move(0, 20 * position) pyautogui.click(button='right', clicks=1) cm.sleep(0.2) #clicking market details on order and checking if we clicked the right order pyautogui.move(40, 68) pyautogui.click() cm.sleep(0.5) quickbar.dontShow() cm.sleep(0.2) thing = pyautogui.locateOnScreen('imgs/search.png', confidence=0.9) marketnamearea = cm.Area(thing.left + 158, thing.top + 14, 375, 30) ocr = cm.grabandocr(marketnamearea) marketname = "" for line in ocr.splitlines(): if len(line.split()) > 11: marketname += line.split()[-1] + ' ' marketname = marketname.strip() print("read marketname while cancelling order: " + marketname) if (cm.similar(marketname.lower(), api.getNameFromID(order.typeid).lower()) < 0.5): print("clicked wrong order while cancelling, retrying") return cancelOrder(order) pyautogui.moveTo(actingPoint.x, actingPoint.y) cm.sleep(0.2) if (position >= itemsfitinlist): pagescrollcount = math.floor(position / itemsfitinlist) position -= (itemsinlist % itemsfitinlist) pyautogui.scroll(int(-130 * itemsfitinlist * pagescrollcount)) pyautogui.move(0, 20 * position) pyautogui.click(button='right', clicks=1) cm.sleep(0.2) pyautogui.move(40, 115) pyautogui.click() for ih in variables.itemhandlerlist: if order.bid: if areOrdersTheSame(ih.buyorder, order): ih.buyorder = None else: for so in ih.sellorderlist: if areOrdersTheSame(so, order): so = None print("successfully cancelled order")