def test_remaining(timeout_checks): timeout_ms, first_check_s, second_check_s = timeout_checks t = Timeout(timeout_ms) time.sleep(first_check_s) assert t.remaining() > 0 time.sleep(second_check_s) assert t.remaining() < 0
def test_is_expired(timeout_checks): timeout_ms, first_check_s, second_check_s = timeout_checks t = Timeout(timeout_ms) time.sleep(first_check_s) assert t.is_expired() is False time.sleep(second_check_s) assert t.is_expired()
def get_static_text_content(url): """ scrap static content form url and preprocess it """ content = [] try: with Timeout(30): res = requests.get(url, headers=headers, verify=False, timeout=10) content.extend(processdata.preprocess(text_from_html(res.text))) if len(content) > 0 and content[0] == "invalidcontentfound": return content abt_url = get_about_url(res.text, url) if abt_url != None: res = requests.get(abt_url, headers=headers, verify=False, timeout=10) content.extend(processdata.preprocess(text_from_html( res.text))) return content except: return content return content
def schedule_downtime(self, client, filters, comment, author, duration): """ Schedule downtime for the provided filter """ try_count = 0 while try_count < 3: try: try_count = try_count + 1 now = time.time() end_time = now + duration results = [] with Timeout(20): host_task = client.actions.schedule_downtime( filters=filters, start_time=now, end_time=end_time, duration=duration, comment=comment, author=author) if len(host_task['results']) > 0: for result in host_task['results']: if result['code'] == 200.0: results.append(result['status']) return results else: return False except Timeout.Timeout: if try_count == 3: return 'Operation timed out'
def test_elapsed(more_ms): delay_s = more_ms / 1000 less_ms = more_ms + 5 t = Timeout(1000000) time.sleep(delay_s) elapsed = t.elapsed() assert elapsed >= more_ms and elapsed <= less_ms
def get_all_info(url, dynamic=False): """ Note -: keep dynamic = False, during multiprocessing return url, compressed_content, embedding and status use only in mass scrapping""" default = {'status': 'failed'} try: with Timeout(35): url_cont = get_url_and_content(url, dynamic) if len(url_cont['content'].split()) < SUFFICIENT: return default else: return { 'url': url_cont['url'], 'content': processdata.compress_sentence(url_cont['content']), 'embedding': processdata.stringify_sent_embedding(url_cont['content']), 'status': 'success' } except: return default return default
def run_cmd(self, cmd, timeout=None): cmd = 'adb -s ' + self.dev + ' ' + ' '.join(cmd.split(' ')[1:]) logging.debug(cmd) if timeout is not None: cmd = cmd.split(' ') timer = Timeout(timeout) child = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE) while child.poll() is None: if timer.expired(): logging.debug("adb.run_cmd expired") child.kill() child.wait() break logging.debug("adb.run_cmd over") if child is not None and child.stdout is not None: output = child.stdout.readlines() output = ''.join(output) logging.debug(output) return output ret = "Failed Unknown" logging.debug(ret) return ret else: # shell=False 不能使用 >> 等重定向命令 output = commands.getstatusoutput(cmd) logging.debug(output[1]) return output[1]
def put_file_info(self, sdfsfilename, requester_ip): # check when last time updated this file start_time = time.time() if self._sdfs_master.file_updated_recently(sdfsfilename): self._logger.info('Write conflict detected: {}s'.format( time.time() - start_time, )) # ask for confirmation try: with Timeout(30): if requester_ip == getfqdn(): command = input('This file was recently updated, are you sure you want to proceed? (yes/no) ') if command != 'yes': return False else: requester_handle = get_tcp_client_handle(requester_ip) if not requester_handle.confirmation_handler(): return False except Timeout.Timeout: # abadon operation return False # get 3 target node and send to them the file put_info = self._sdfs_master.handle_put_request(sdfsfilename) # return ack to requester return put_info
def put_file_info(sdfsfilename, requester_ip): # check when last time updated this file if sdfs_master.file_updated_recently(sdfsfilename): # ask for confirmation try: with Timeout(30): if requester_ip == getfqdn(): command = input('This file was recently updated, are you sure you want to proceed? (yes/no) ') if command != 'yes': return False else: requester_handle = get_tcp_client_handle(requester_ip) if not requester_handle.confirmation_handler(): return False except Timeout.Timeout: # abadon operation return False # get 3 target node and send to them the file print(requester_ip) put_info = sdfs_master.handle_put_request(sdfsfilename) print(requester_ip) # return ack to requester return put_info
def handle_message(event): profile = line_bot_api.get_profile(event.source.user_id) id = str(profile.user_id) if(id not in EnterInput.user_input): EnterInput.user_input[id]=[] if(id not in EnterInput.input): EnterInput.input[id] = False if(EnterInput.input[id]): get_message = event.message.text case = get_message.split("\n") EnterInput.user_input[id] = case[:] EnterInput.input[id] = False reply_message = TextSendMessage(text="Now enter your program") else: def input(str="",*args,**kwargs): if(EnterInput.user_input): return EnterInput.user_input[id].pop(0) else: raise InputSection _restricted_modules = ['os','subprocess','requests','tkinter','Tkinter','environ','inspect','dotenv'] for i in _restricted_modules: sys.modules[i] = None get_message = event.message.text if(get_message == "/help"): reply_message = TextSendMessage(text="You can run simple python program just by write the code here. To add user input, type /input in this chat and enter the input.") elif(get_message == "/about"): reply_message = TextSendMessage(text="Lython v.0.2.1") elif(get_message == "/options"): reply_message = TemplateSendMessage(alt_text='Message not supported', template=ButtonsTemplate(title='Menu',text='Please select action', actions=[MessageTemplateAction(label='Help',text='/help'), MessageTemplateAction(label='About',text='/about'),MessageTemplateAction(label="Input",text='/input')])) elif(get_message == "/input"): reply_message = TextSendMessage(text="Enter your input") EnterInput.input[id] = True else: try: with stdoutIO() as s, Timeout(3): exec(get_message) message = s.getvalue() EnterInput.user_input[id] = [] if(len(message)>2000): reply_message = TextSendMessage(text="This bot cannot reply with more than 2000 characters yet :(") else: reply_message = TextSendMessage(text=message) except SystemExit: err = "Don't go :'(" reply_message = TextSendMessage(text=err) except InputSection: reply_message = TextSendMessage(text="Input are none or insuficcient. Use /input to add user input") except: err = "{} occurred".format(sys.exc_info()[0].__name__) reply_message = TextSendMessage(text=err) line_bot_api.reply_message(event.reply_token,reply_message)
def read(self, size: int = -1) -> bytes: if self.timeout: old_timeout = self.timeout self.timeout = Timeout(self.timeout) assert old_timeout._finish <= self.timeout._start return self.f.read(size) else: return None
def __init__(self, name: str, delay: Union[float, int]) -> None: self.name = name self.mode = "rb" self.timeout = Timeout(delay) self.f = io.FileIO(self.name, self.mode) assert isinstance(self.f, io.RawIOBase) assert not self.f.closed os.set_blocking(self.f.fileno(), False) assert not self.f.closed
def receive(sec): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: with Timeout(sec): sock.bind((UDP_IP, UDP_PORT)) data, addr = sock.recvfrom(1024) return data except Timeout.Timeout: return None
def get_status_code(url, default=0): """ return status code of url and 0 in case of exception """ try: with Timeout(10): res = requests.get(url, headers=headers, verify=False, timeout=3, stream=False) return res.status_code except: return default return default
def _external_request_with_timeout(self, buffers, timeout): """ The actual request with a timeout :param buffers: Image buffers :param timeout: specified timeout :return: query result """ timeout_function = Timeout(self._face_client.faces_recognize, timeout) return timeout_function(buffers)
def main(arguments): test_script = None arg_parser = ArgumentParser(description="Parse contents of test .py files") arg_parser.add_argument("test_script", action="store", type=test_script, help=("The test script to be parsed")) arg_parser.add_argument("--format", action="store", type=output_format, default="json", dest="output_format", help=("Format for output to be dumped")) args = arg_parser.parse_args(args=arguments) test_script = args.test_script out_fmt = args.output_format abs_path = os.path.abspath(test_script).split('/') keyword = 'halon-test' if 'halon-test' in abs_path else 'halon-src' rel_path = '/'.join(abs_path[abs_path.index(keyword):]) with open(test_script, 'r') as file_pointer: test_contents = file_pointer.read() with Timeout(20): output = parse_test_file(test_contents, os.path.dirname(test_script)) if out_fmt.lower() == 'json': print( json.dumps(output, sort_keys=True, indent=4, separators=(',', ': '))) elif out_fmt.lower() == 'csv': separator = '~' for def_test in output['test_funcs']: print( separator.join([ rel_path, def_test, '{name} - {email}'.format(**output['Author']), output['TestId'], output['Release'], output['TestName'], # repr(string)[1:-1] = raw version of string and strip '' repr(output['Objective'])[1:-1], repr(output['Requirements'])[1:-1], repr(output['TestDescription'])[1:-1], output['PlanPriority'], output['TestPassCriteria'], output['PlatformIndependent'], output['SubArea'], output['SupportedPlatforms'], output['test_marks'].get(def_test, ''), repr(output['Topology'])[1:-1] ])) pass
def __init__(self, sock, addr, handlers): self._sock = sock self._addr = addr self._handlers = handlers self._reqTimeout = Timeout(2000) self._mode = Request.MODE_GOT_CONNECTION self._buffer = b'' self.header = {} self.method = None self.reqPath = None self.query = None
def confirmation_handler(): try: with Timeout(30): command = input('This file was recently updated, are you sure you want to proceed? (yes/no) ') if command == 'yes': return True else: return False except Timeout.Timeout: return False
def _open(self, url, data=None, headers=None, timeout=None): timeout = self.global_timeout if timeout is None else timeout # mechanize calls open internally with request objects, just pass them through if this is # the case. if isinstance(url, mechanize.Request): request = url else: headers = dict() if headers is None else headers request = mechanize.Request(url, data=data, headers=headers, timeout=timeout) with Timeout(timeout): return mechanize.Browser.open(self, request)
def parse(self): analyzed = False with Timeout(Parser.MAX_ANALYZE_TIMEOUT): # stop if the analyze takes too long self.analyzer.analyze() analyzed = True if analyzed: for symbol in self.analyzer.symbols: if symbol.type == SymbolType.PLAIN_TEXT: self.extract_text(symbol.content) elif symbol.type == SymbolType.META: self.extract_meta(symbol) elif symbol.type == SymbolType.A_START: self.extract_link(symbol)
def from_accepted_trade(cls, accepted_trade, transaction_id): """ :param accepted_trade: The accepted trade to create the transaction for :param transaction_id: The transaction id to use for this transaction :type accepted_trade: AcceptedTrade :type transaction_id: TransactionId :return: The created transaction :rtype: Transaction """ assert isinstance(accepted_trade, AcceptedTrade), type(accepted_trade) assert isinstance(transaction_id, TransactionId), type(transaction_id) return cls(transaction_id, accepted_trade.recipient_order_id.trader_id, accepted_trade.price, accepted_trade.quantity, Timeout(float('inf')), accepted_trade.timestamp)
def _request_for_mine(self): Logger.info("TinyCoin._request_for_mine() - %s" % self.minerAddress) if self.mining: self.mine() else: maxMiningRequestNum = 2 mineNodes = copy.deepcopy(self.peerNodes) random.shuffle(mineNodes) mineNodes = mineNodes[:min(len(mineNodes), maxMiningRequestNum)] # 获得最后一个区块 lastBlock = self.blockchain[-1] if type(lastBlock) == type({}): lastProof = eval(lastBlock['data'])['proof-of-work'] else: lastProof = lastBlock.data['proof-of-work'] # 通过异步调用 执行 asyncPow = [] for i in range(len(mineNodes)): mineNode = mineNodes[i] powRequest = { 'proof-from': self.minerAddress, 'last-proof': lastProof } def local_post(): return requests.post(mineNode + "/pow", json=powRequest) asyncPow.append(Timeout()) asyncPow[i].set(local_post, 0) asyncPow[i].start() powRes = None foundPow = False while not foundPow: for i in range(len(asyncPow)): if asyncPow[i].result != None: foundPow = True print(asyncPow[i].result.content.decode()) powRes = json.loads( asyncPow[i].result.content.decode()) break time.sleep(0.005) self._keep_account(lastBlock, powRes['proof-of-work'], powRes['proof-by'])
def __init__(self, brute_force, logger): self.logger = logger if USE_INTERRUPT: global LED_WAIT_TIME LED_WAIT_TIME = 1 gpio.setwarnings(False) gpio.setmode(gpio.BCM) gpio.setup(INTERRUPT_GPIO, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.add_event_detect(INTERRUPT_GPIO, gpio.FALLING, callback=self.interrupt_line_active, bouncetime=200) self.bus = BusAccessor() self.brute = brute_force self.led_timer = Timeout(LED_WAIT_TIME) self.led_timer.elapsed.bind(self.led_timer_elapsed) self.led_wait_time_done = False self.led_waiter = threading.Event() self._do_loop = True
def test_upload_submission(self): metapy.log_to_stderr() """ This is the unit test that actually submits the results to the leaderboard. If there is an error (on either end of the submission), the unit test is failed, and the failure string is also reproduced on the leaderboard. """ req = { 'token': os.environ.get('GITLAB_API_TOKEN'), 'alias': os.environ.get('COMPETITION_ALIAS') or 'Anonymous', 'results': [] } for cfg_file in self.cfgs: res = {'error': None} with open(cfg_file, 'r') as fin: cfg_d = pytoml.load(fin) res['dataset'] = cfg_d['dataset'] print("\nRunning on {}...".format(res['dataset'])) timeout_len = cfg_d['timeout'] try: with Timeout(timeout_len): res['results'] = self.get_results(cfg_file) except Timeout.Timeout: error_msg = "Timeout error: {}s".format(timeout_len) res['error'] = error_msg res['results'] = [] req['results'].append(res) response = requests.post(self.submission_url, json=req) jdata = response.json() print(jdata) self.assertTrue(jdata['submission_success'])
def _request_with_timeout(self, img_msg, timeout): timeout_function = Timeout(self._request, timeout) return timeout_function(img_msg)
def test_elapsed_type(timeout_ms): t = Timeout(timeout_ms) assert type(t.elapsed()) is int
def test_remaining_type(timeout_ms): t = Timeout(timeout_ms) assert type(t.remaining()) is int
def test_init(wrong_timeout): with pytest.raises(TypeError): Timeout(wrong_timeout)
def _external_request_with_timeout(buffers): timeout_duration = 60 rospy.loginfo("Trying external API request for %d seconds", timeout_duration) timeout_function = Timeout(face_client.faces_recognize, timeout_duration) return timeout_function(buffers)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from killable import KillableThread import re from select import select from sys import platform from time import sleep from timeout import Timeout keythread = None keys = '' keytimeout = Timeout() keysleep = Timeout() oldtcs = None iswin = 'win' in platform last_key = None esc_char = '' try: from msvcrt import getch as ms_getch def getch(): global last_key if last_key is not None: key, last_key = last_key, None return key key = ms_getch() if key == b'\xe0': last_key = ms_getch() # clear horrid follow-up zero else: