def __check_go(self, chessboard): try: timeout(1)(self.agent.go)(np.copy(chessboard)) except Exception: self.errormsg = "Error:" + traceback.format_exc() return False return True
def check_code(self): # check if contains forbidden library try: if self.__check_forbidden_import() == False: return False except Exception: self.errormsg = self.errormsg + traceback.format_exc() return False # check initialization try: timeout(self.time_out)(self.time_out_init)() # self.time_out_init() except Exception: self.errormsg = "Your code fail to init." + traceback.format_exc() return False # check simple condition if not self.__check_simple_chessboard(): self.errormsg = "Your code can not pass usability test." + self.errormsg return False # check advance condition, online test contain more test case than this demo if not self.__check_advance_chessboard(): self.errormsg = "Your code is too weak, fail to pass advance test." + self.errormsg return False return True
def update(self, color): agent = self.white if color == 1 else self.black try: timeout(self.time_out)(agent.go)( np.copy(self.chessboard) ) # timeout(god.time_out)(self.white.go)(self.last_pos)#-------------------------------------------------------- except MemoryError: memory_error = traceback.format_exc() self.memory_fail(memory_error) return '' except timeout_decorator.timeout_decorator.TimeoutError: pass except Exception: self.fail_step(color=color) god.error = str(self.color_user_map[color] ) + ' error.' + traceback.format_exc() return tem_list = agent.candidate_list if len(tem_list) > 0: pos = tem_list[-1] self.check_chess(pos, color) if not self.finish: self.last_pos = pos assert self.chessboard[pos[0], pos[1]] == 0 self.chessboard[pos[0], pos[1]] = color self.check_chess_board(pos, color) else: self.winner = -color else: self.error = self.error + "Dear " + str( self.color_user_map[color] ) + ' : your candidate list of chess is empty.\n' self.fail_step(color=color)
def SetJointPose_click(self, pose): """ 指定された作業座標系にアームの先端を移動させる関数 関節座標系で移動 Returns ------- response : int 0 : 応答なし 1 : 応答あり 2 : 姿勢が保存されていない """ response = 0 # Dobotからの応答 1:あり, 0:なし if self.connection == 0 or self.DOBOT_err == 1: self.DOBOT_err = 1 return response elif self.CurrentPose is None: response = 2 return response timeout(5) try: dType.SetPTPCmd(self.api, dType.PTPMode.PTPMOVJANGLEMode, self.CurrentPose[4], self.CurrentPose[5], self.CurrentPose[6], self.CurrentPose[7], self.queue_index) except TimeoutError: self.DOBOT_err = 1 return response response = 1 return response
def SetCoordinatePose_click(self, pose): """ 指定された作業座標系にアームの先端を移動させる関数 デカルト座標系で移動 Parameters ---------- pose : list デカルト座標系もしくは関節座標系での移動先を示したリスト パラメータ数4個 Returns ------- response : int 0 : 応答なし 1 : 応答あり 2 : 姿勢が保存されていない """ response = 0 # Dobotからの応答 1:あり, 0:なし if self.connection == 0 or self.DOBOT_err == 1: self.DOBOT_err = 1 return response timeout(5) try: dType.SetPTPCmd(self.api, dType.PTPMode.PTPMOVJXYZMode, pose[0], pose[1], pose[2], pose[3], self.queue_index) except TimeoutError: self.DOBOT_err = 1 return response response = 1 return response
def SetCoordinatePose_click(self): """ 指定された作業座標系にアームの先端を移動させる関数 デカルト座標系で移動 Returns ------- response : int 0 : 応答なし 1 : 応答あり 2 : 姿勢が保存されていない """ response = 0 # Dobotからの応答 1:あり, 0:なし if self.connection == 0 or self.DOBOT_err == 1: self.DOBOT_err = 1 return response elif self.CurrentPose is None: response = 2 return response timeout(5) try: dType.SetPTPCmd(self.api, dType.PTPMode.PTPMOVJXYZMode, self.CurrentPose[0], self.CurrentPose[1], self.CurrentPose[2], self.CurrentPose[3], self.queue_index) except TimeoutError: self.DOBOT_err = 1 return response response = 1 return response
def GetPose_click(self): """ デカルト座標系と関節座標系でのDobotの姿勢を返す関数 Returns ------- response : int 0 : 応答なし 1 : 応答あり PoseParams : list Dobotの姿勢を格納したリスト """ response = 0 # Dobotからの応答 1:あり, 0:なし if self.connection == 0: self.DOBOT_err = 1 return response timeout(5) try: pose = dType.GetPose(self.api) except TimeoutError: self.DOBOT_err = 1 return response response = 1 self.CurrentPose = pose # 現在の姿勢をグローバル変数に保存 return response, pose
def grabDanshuang(S, T, MODE): c = danshuangTransfer(S, T, MODE) Res = set() def F(): count = 0 for i in c: if count > 400 or len(Res) > 30: break count += 1 Ans = "/".join( list( map( lambda y: "/".join( list(map(lambda z: " %s => %s " % (z[1], z[0]), y))), i))) if Ans not in Res: print(Ans) Res.add(Ans) try: timeout_decorator.timeout(10)(F)() except timeout_decorator.TimeoutError: WARN = "【警告】- 执行超时,数据可能不足\n" WARN += "\n===================================================================\n" except: WARN = "【错误】- 发生其他错误,调用信息:\n" import traceback WARN += traceback.format_exc() WARN += "\n===================================================================\n" else: WARN = "" return WARN, Res
def __check_go(self, chessboard): self.agent = imp.load_source('AI', self.script_file_path).AI( self.chessboard_size, -1, self.time_out) try: timeout(self.time_out)(self.agent.go)(np.copy(chessboard)) except Exception: self.errormsg = "Error:" + traceback.format_exc() return False return True
def __check_go(self, chessboard): self.agent = imp.load_source('AI', self.script_file_path).AI( self.chessboard_size, -1, self.time_out) try: # self.agent.go(np.copy(chessboard)) timeout(self.time_out)(self.agent.go)(np.copy(chessboard)) except Exception: if len(self.agent.candidate_list) == 0: self.errormsg = "Error: Time out and candidate list empty." + traceback.format_exc( ) return False return True
def __game_over_player(self, player, message): """ Notify player of game over with message. :param player: Player, player to notify :param message: string, message to send :raise BrokenPlayer: if player times out """ try: timeout(self.__time_limit)(player.game_over)(message) except TimeoutError: pass
def decorator(func: Callable): def register(*args) -> Callable: if len(args) > 0 and twitterAccount: args[0].twitterAccountName = twitterAccount return func(*args) if timeout and pluginType is not PluginType.Thread: if platform.system() != "Windows": import timeout_decorator register = timeout_decorator.timeout(timeout, timeout_exception=TimedOut)(register) else: logger.warning("Timeout feature is disabled in Windows.") setattr(register, "__meta__", { "type": pluginType, "priority": priority or 0, "ratio": ratio or 1, "hours": hours or [], "minutes": minutes or [], "multipleHour": multipleHour, "multipleMinute": multipleMinute, "permissions": permissions or [], "twitterAccountName": twitterAccount, "discordAccountName": discordAccount, "timeout": timeout, "validFrom": validFrom, "validUntil": validUntil, "function": func, "functionName": func.__name__, "doc": func.__doc__, "argumentsCount": func.__code__.co_argcount }) return register
def __prompt_act_raise(self, turn_phase, player, wid=None): """ Prompt player for action, make the action, and raise game over state if game is over after move. :param turn_phase: TurnPhase, the phase in the game :param player: Player, player to prompt :param wid: string, id of worker to place :raise BrokenPlayer: if player times out, makes an invalid move, or crashes :raise GameOver: if game is over after action :return: string, id of worker moved only if turn_phase is TurnPhase.MOVE """ try: # Get action from player and impose time out action = timeout(self.__time_limit)(self.__prompt)(turn_phase, player, wid) self.__act(turn_phase, player, action, wid) # Timeout error except TimeoutError: raise BrokenPlayer(player, GameOverCondition.Timeout) # Illegal action by player except IllegalActionException: raise BrokenPlayer(player, GameOverCondition.InvalidAction) # Player breaks in any way except: raise BrokenPlayer(player, GameOverCondition.Crash) self.__raise_game_over() return action
def process_task(self, task): """Load and execute the task""" if task.timeout is None: timeout = getattr(settings, 'TASKQ_TASK_TIMEOUT', TASKQ_DEFAULT_TASK_TIMEOUT) else: timeout = task.timeout if not task.retries: logger.info('%s : Started', task) else: nth = ordinal(task.retries) logger.info('%s : Started (%s retry)', task, nth) task.status = Task.STATUS_RUNNING task.save() def _execute_task(): function, args, kwargs = self.load_task(task) self.execute_task(function, args, kwargs) try: if timeout.total_seconds(): assert threading.current_thread() is threading.main_thread() timeout_decorator.timeout(seconds=timeout.total_seconds(), use_signals=True)(_execute_task)() else: _execute_task() except TaskFatalError as e: logger.info('%s : Fatal error', task) self.fail_task(task, e) except Cancel: logger.info('%s : Canceled', task) task.status = Task.STATUS_CANCELED except timeout_decorator.TimeoutError as e: logger.info('%s : Timed out', task) self.fail_task(task, e) except Exception as e: if task.retries < task.max_retries: logger.info('%s : Failed, will retry', task) self.retry_task_later(task) else: logger.info('%s : Failed, exceeded max retries', task) self.fail_task(task, e) else: logger.info('%s : Success', task) task.status = Task.STATUS_SUCCESS finally: task.save()
def decorator(func): """Decorator of function""" for decorator in [ timeout_decorator.timeout(seconds), pytest.mark.xfail( raises=timeout_decorator.timeout_decorator.TimeoutError)]: func = decorator(func) return func
def __init__(self, items, id=None): self.values = items self.timeout = items.get("timeout") self._timeout_wrap = timeout_decorator.timeout( self.timeout or self.BLOCKING_TIMEOUT) self._enabled = items.get( "enabled", self.DEFAULT_ENABLED ) if items is not None else self.DEFAULT_ENABLED
def wrapper(): try: _predicate = timeout_decorator.timeout( predicate_timeout, timeout_exception=PredicateTimeout)(predicate) return _predicate(*args, **kwargs) except expected_exceptions as e: raised_exceptions.append(e) return False
def pwn_all(self, name, exp): ip_list, port, flag_pattern = TargetsManager.get( name, 'ips', 'port', 'flag_pattern') port = int(port) keep_shell = TargetsManager.get(name, 'keep_shell') for ip in ip_list: exp_timeout = float(config.get('pwner', 'exp_timeout')) try: abortable_pwn_remote = timeout(exp_timeout, False)(exp.pwn_remote) flag, io = exp.pwn_remote(ip, port, keep_alive=keep_shell) self.flag_queue.put(flag) with_shell = 0 # with_shell: # 0 : no shell # 1 : new shell # 2 : override shell # 3 : ignored new shell # maintain the shell connection if keep_shell: shell_name = get_shell_name(name, ip, port) old_shell = self.shells.get(shell_name, None) if io and is_shell_ok(io): with_shell = 3 if old_shell and not is_shell_ok(old_shell): old_shell.close() self.shells[shell_name] = io with_shell = 2 elif not old_shell: self.shells[shell_name] = io with_shell = 1 else: io.close() if with_shell == 1: logger.info("[+] Pwn %s %s:%d ... [%s] with new shell", name, ip, port, flag) elif with_shell == 2: logger.info("[+] Pwn %s %s:%d ... [%s] override shell", name, ip, port, flag) elif with_shell == 3: logger.info("[+] Pwn %s %s:%d ... [%s] ignored shell", name, ip, port, flag) else: logger.info("[+] Pwn %s %s:%d ... [%s]", name, ip, port, flag) except KeyboardInterrupt: confirm_exit() except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logger.info("[-] Pwn %s %s:%d ... %s(%s) at %s:%d", name, ip, port, exc_type, ''.join(str(ex)), fname, exc_tb.tb_lineno)
def _run(): logger.debug('Start {0}'.format(self.uuid)) self.state = 'started' self._start = time.clock() return timeout_decorator.timeout( TIMEOUT * 60, use_signals=False )( ALGORITHMS[self._algorithm]['algorithm'] )( *resolve_args(self._algorithm, *self._args) )
def __init__(self, f=None, **kwds): self._kwds = kwds if f is not None: self.__name__ = f.__name__ self.__doc__ = f.__doc__ for key, val in kwds.items(): setattr(self, key, val) if self.timeout is None: self.f = f else: self.f = timeout(self.timeout)(f) else: self.f = None
def exec_with_timeout(secs, func, *args, **kwargs): """Wrap a function in a timeout. If the function takes longer than `secs` to complete, an exception will be raised. Args: secs (int): Max time until process completion func *args **kwargs Returns: None """ return timeout_decorator.timeout(secs, use_signals=False)(func)(*args)
def cli(self, mock_stdout, mock_formatter, mock_run, mock_chdir, args=[], stdin=None): def to_mock(): return StringIO(stdin or '') with patch('yapf_diff.sys.stdin', new_callable=to_mock): exit = timeout(1)(lambda: main(['yapf-diff', *args]))() mock_chdir.assert_called_with('/path/to/git/dir') return exit, mock_formatter, mock_stdout, mock_run
def send_clicked(self, btn: Button) -> None: "Callback to be called when the Send button is clicked." btn.button_style = 'info' btn.disabled = True self.logger.logger.info('clicked') url = self.url_txt.value method = self.method_ddn.value headers_text = self.req_pane.get_child_named('Headers').value headers = json.loads(headers_text) if headers_text.strip() else {} data_text = self.req_pane.get_child_named('Data').value data = json.loads(data_text) if data_text.strip() else {} args = [url, method] kwargs = dict(headers=headers, cassette_path=self.cassette_path, logger=self.logger) if data: kwargs['json'] = data self.logger.logger.info('vcr request {} {}'.format(args, kwargs)) if 1: timeout_execute_request = timeout_decorator.timeout(self.timeout)( self.execute_request) try: self.logger.logger.info('callign timeout_execute_request') self.resp, is_cached = timeout_execute_request(*args, **kwargs) self.logger.logger.info('result request {}'.format(self.resp)) except timeout_decorator.TimeoutError: self.logger.logger.info('timed out') self.resp_htm = HBox([ HTML('Response'), HTML('Status: Timed out after {:.3f} secs.'.format( self.timeout)) ], layout=Layout( width='100%', justify_content='space-between')) raise else: self.resp, is_cached = self.execute_request(*args, **kwargs) self.logger.logger.info(self.resp.content) if self.post_process_resp: self.post_process_resp(self.resp) btn.button_style = 'primary' self.show_response(self.resp, is_cached) btn.disabled = False
def run_tests(local=True, notebook_file="set_2_answers.ipynb", test_output_file="test_results.json"): os.system("rm -f %s" % test_output_file) os.system("rm -f /tmp/set_2.py /tmp/set_2.pyc") os.system( "jupyter nbconvert --ExecutePreprocessor.timeout=60 --output-dir /tmp --output set_2 --to python %s" % notebook_file) with open("/tmp/set_2.py") as f: content = f.readlines() filtered_content = [] for i in content: if "matplotlib notebook" not in i: if "plt.show()" not in i: if 'test_set_2' not in i: filtered_content.append(i) os.system("rm -f /tmp/set_2_for_testing.py /tmp/set_2_for_testing.pyc") os.system("touch /tmp/set_2_for_testing.py") with open('/tmp/set_2_for_testing.py', 'a') as the_file: for j in filtered_content: the_file.write(j + '\n') # Import this so it's in scope down the road... try: set_2_for_testing = timeout_decorator.timeout(60)( lambda: imp.load_source('set_2_for_testing', '/tmp/set_2_for_testing.py'))() do_testing = True except timeout_decorator.timeout_decorator.TimeoutError: global_fail_with_error_message("Timed out importing your notebook.", test_output_file) do_testing = False if do_testing: test_cases = [TestSetTwo] suite = unittest.TestSuite() for test_class in test_cases: tests = unittest.defaultTestLoader.loadTestsFromTestCase( test_class) suite.addTests(tests) with open(test_output_file, "w") as f: JSONTestRunner(stream=f).run(suite) os.system("rm -f /tmp/set_2_for_testing.py /tmp/set_2_for_testing.pyc") os.system("rm -f /tmp/set_2.py /tmp/set_2.pyc")
def semantic_search(): queue_exchange.delete('input') queue_exchange.delete('output') query = request.args.get('q', '') print('Search term: ', query) if not query: return "Please provide query param `q` for example /search/?q=load+data+from+files", 400 queue_exchange.write('input', query) results = timeout_decorator.timeout(10, use_signals=False)(fetch_result)(query) results = json.loads(results) for result in results: result['file'] = '/'.join(request.url.split('/', maxsplit=3)[:-1]) +\ url_for('browse') +\ result['file'].split(app.config['UPLOAD_FOLDER'], maxsplit=1)[1].lstrip('/') queue_exchange.delete('output', query) return jsonify(results), 200
def wrapper(*args, **kwargs): timeout_time = current_app.config[config_key] use_signals = current_app.config.get('USE_SIGNALS_ON_TIMEOUT', True) return timeout(timeout_time, use_signals=use_signals)(func)(*args, **kwargs)
def wrapper(*args, **kwargs): timeout_time = current_app.config[config_key] return timeout(timeout_time)(func)(*args, **kwargs)
def get_fit_single_group_with_timeout(timeout=60): # timeout in seconds return timeout_decorator.timeout(timeout)(fit_single_group_without_timeout)
def ratio_timeout(self, ratio=0.5): return timeout_decorator.timeout( ratio * self.time_budget - (time.time() - self.start_time) )
import unittest import sys sys.path.insert(0, "/usr/lib/python3.6/code_kombat_test_frameworks") from code_kombat_test_frameworks import CodeKombatTestRunner import timeout_decorator def load_tests(loader, tests, pattern): return loader.discover(".") GLOBAL_TIMEOUT = 3 timeout_decorator.timeout(GLOBAL_TIMEOUT)( unittest.main)(testRunner=CodeKombatTestRunner())
import logging import signal from timeout_decorator import timeout import os import multiprocessing from util import get_memory # Global Vars TIME_LIMIT = 600 PATH_TO_OUTPUT = "/home/featurize/work/newMCP/output/greedy/8000/" FILE_OUTPUT = "celf_all.csv" DS = [2, 3] KS = [2**n for n in range(10)] repeat = 1 bfs = timeout(seconds=TIME_LIMIT)(bfs) greedy = timeout(seconds=TIME_LIMIT)(greedy) def integrated_celf(x): graph_name, graph, is_directed = x graph_name = os.path.splitext(graph_name)[0] # Config Loggers DATE = time.strftime('%m-%d', time.localtime()) TIME = time.strftime('%H.%M.%S', time.localtime()) Path(f"log/{DATE}").mkdir(parents=True, exist_ok=True) logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[
def run_tests(local = True, notebook_path = "./", test_output_file = "test_results.json"): try: # Check for existence of the expected files expected_files = [ "set_3.ipynb", "inertial_wheel_pendulum.py", "inertial_wheel_pendulum_visualizer.py" ] print notebook_path for file in expected_files: if not os.path.isfile(os.path.join(notebook_path, file)): raise ValueError("Couldn't find an expected file: %s" % file) os.system("rm -f %s" % test_output_file) os.system("rm -f /tmp/set_3.py /tmp/set_3.pyc") os.system("jupyter nbconvert --ExecutePreprocessor.timeout=60 --output-dir /tmp --output set_3 --to python %s" % notebook_path + "set_3.ipynb") with open("/tmp/set_3.py") as f: content = f.readlines() filtered_content = [] string_exclude_list = [ "%matplotlib", "plt.show()", "test_set_3", "get_ipython" ] for i in content: if not any([s in i for s in string_exclude_list]): filtered_content.append(i) os.system("rm -f /tmp/set_3_for_testing.py /tmp/set_3_for_testing.pyc") os.system("touch /tmp/set_3_for_testing.py") with open('/tmp/set_3_for_testing.py', 'a') as the_file: for j in filtered_content: the_file.write(j+'\n') # Import the user support files inertial_wheel_pendulum = timeout_decorator.timeout(60)( lambda: imp.load_source('inertial_wheel_pendulum', os.path.join(notebook_path, 'inertial_wheel_pendulum.py')))() inertial_wheel_pendulum_visualizer = timeout_decorator.timeout(60)( lambda: imp.load_source('inertial_wheel_pendulum_visualizer', os.path.join(notebook_path, 'inertial_wheel_pendulum_visualizer.py')))() # And import the notebook itself, so we can grab everything it defines. # (This runs the entire notebook, as it has been compiled to be a giant script.) set_3_for_testing = timeout_decorator.timeout(60)( lambda: imp.load_source('set_3_for_testing', '/tmp/set_3_for_testing.py'))() do_testing = True except timeout_decorator.timeout_decorator.TimeoutError: global_fail_with_error_message("Timed out importing your files.", test_output_file) do_testing = False except Exception as e: import traceback global_fail_with_error_message("Unknown exception while setting up: " + traceback.format_exc(1), test_output_file) do_testing = False if do_testing: test_cases = [TestSetThree_ProblemTwo, TestSetThree_ProblemThree] suite = unittest.TestSuite() for test_class in test_cases: tests = unittest.defaultTestLoader.loadTestsFromTestCase(test_class) suite.addTests(tests) with open(test_output_file, "w") as f: JSONTestRunner(stream=f).run(suite) os.system("rm -f /tmp/set_3_for_testing.py /tmp/set_3_for_testing.pyc") os.system("rm -f /tmp/set_3.py /tmp/set_3.pyc")