def validMoves(self, config): self.player_pieces_pos = config.getPlayerPositions(self.color) self.enemy_pieces_pos = config.getEnemyPositions(self.color) valid_moves = [] x,y = self.pos # +2, +1 | +2, -1 | -2 + 1 | -2, -1 | +1,+2 | +1, -2| -1, +2| -1,-2 incx = 1 incy = 2 for i in range(4): for j in range(2): if util.isNotOutofBounds(x+incx, y+incy): valid_moves.append((x+incx, y+incy)) incx = -1 * incx incy = -1 * incy if i == 1: incx, incy = incy, incx # Check for collisions for (newx,newy) in valid_moves: action = Action(self, (newx,newy), config) if not action.isValid(): valid_moves.remove((newx,newy)) return valid_moves
def inIgnoreIPList(self, ip): for i in self.__ignoreIpList: # An empty string is always false if i == "": continue s = i.split('/', 1) # IP address without CIDR mask if len(s) == 1: s.insert(1, '32') elif "." in s[1]: # 255.255.255.0 style mask s[1] = len(re.search( "(?<=b)1+", bin(DNSUtils.addr2bin(s[1]))).group()) s[1] = long(s[1]) try: a = DNSUtils.cidr(s[0], s[1]) b = DNSUtils.cidr(ip, s[1]) except Exception: # Check if IP in DNS ips = DNSUtils.dnsToIp(i) if ip in ips: return True else: continue if a == b: return True if self.__ignoreCommand: command = Action.replaceTag(self.__ignoreCommand, { 'ip': ip } ) logSys.debug('ignore command: ' + command) return Action.executeCmd(command) return False
def run_test(self): """" Use selenium to open the proper form and start entering the data. Note: This function is called by every child class. @TODO: improve exception handling for longitudinal projects """ try: # self.goto_form() self.goto_form_longitudinal() stat = ActionStatistic(self.get_class_name()) # for every field enter data as needed... for action_data in self.data: action = Action(self.driver, action_data) success = action.execute() stat.update(action, success) #time.sleep(0.5) # uncomment for debugging in the browser logger.warning(stat.to_string()) self.save_form() # for every field check if the value was saved properly... if self.do_check: logger.info("""\n# Perform data integrity check for form: {}""".format(self.get_display_name())) for action_data in self.data: action = Action(self.driver, action_data) action.check_result() except UnexpectedAlertPresentException: alert = self.driver.switch_to_alert() alert.accept() logger.warning("skip UnexpectedAlertPresentException {} for {}".format(alert.text, type(self)))
def _initToolboxButtons(self): """ Sets up and connects buttons related to the toolbox """ self._selectAction = Action(text=u"Select", icon="gui/icons/select_instance.png", checkable=True) self._drawAction = Action(text=u"Draw", icon="gui/icons/add_instance.png", checkable=True) self._removeAction = Action(text=u"Remove", icon="gui/icons/erase_instance.png", checkable=True) self._moveAction = Action(text=u"Move", icon="gui/icons/move_instance.png", checkable=True) self._objectpickerAction = Action(text=u"Pick object", icon="gui/icons/objectpicker.png", checkable=True) self._selectAction.helptext = u"Select cells on layer (S)" self._moveAction.helptext = u"Moves instances (M)" self._drawAction.helptext = u"Adds new instances based on currently selected object (I)" self._removeAction.helptext = u"Deletes instances (R)" self._objectpickerAction.helptext = u"Click an instance to set the current object to the one used by instance" action.toggled.connect(self._buttonToggled, sender=self._selectAction) action.toggled.connect(self._buttonToggled, sender=self._moveAction) action.toggled.connect(self._buttonToggled, sender=self._drawAction) action.toggled.connect(self._buttonToggled, sender=self._removeAction) action.toggled.connect(self._buttonToggled, sender=self._objectpickerAction) self._toolgroup = ActionGroup(exclusive=True, name=u"Tool group") self._toolgroup.addAction(self._selectAction) self._toolgroup.addAction(self._moveAction) self._toolgroup.addAction(self._drawAction) self._toolgroup.addAction(self._removeAction) self._toolgroup.addAction(self._objectpickerAction) self._toolbox.addAction(self._toolgroup) self._toolbox.adaptLayout() self._editor._edit_menu.addAction(self._toolgroup)
def test_starts_actions_and_adds_back_to_queue(self): # given start_time = 0 deadline = 10 action_to_start = Action(start_time, deadline+1) action_to_start.agent = Mock(name="agent") action_to_start.is_applicable = Mock(return_val=True) action_to_start.apply = Mock(name="apply") model = Mock(name="model") execution_queue = PriorityQueue() execution_queue.put(ActionState(action_to_start, start_time, ExecutionState.pre_start)) # when actual, _stalled = simulator.execute_action_queue(model, execution_queue, break_on_new_knowledge=False, deadline=deadline) # then assert_that(execution_queue.queue, has_length(1)) time, state, action = execution_queue.queue[0] assert_that(time, equal_to(action_to_start.end_time)) assert_that(state, equal_to(ExecutionState.executing)) assert_that(action, equal_to(action_to_start)) assert_that(actual.executed, is_(empty())) assert_that(is_not(action_to_start.apply.called)) assert_that(actual.simulation_time, equal_to(start_time))
def parseATCommand(self, rawATCommand): action = Action() #We don't know yet if we have parser implemented for this AT command, #set error state for now action.noCommand = True if not isinstance(rawATCommand, str): action.isInErrorState = True return action if rawATCommand[:4] == "RING": action.incomingCall = True action.isInErrorState = False action.noCommand = False self.log.pushLogMsg("Incoming call") if rawATCommand[:10] == "NO CARRIER" or rawATCommand[:9] == "NO ANSWER": action.incomingCall = False action.isInErrorState = False action.noCommand = False action.callDisconnected = True self.log.pushLogMsg("Call disconnected") if action.noCommand == True: self.log.pushLogMsg(("AT parser failed to parse the AT command: " + rawATCommand)) #rawATCommand.toString())) return action
def __init__(self, key, desc, rev_key): Action.__init__(self, (key, desc), self, TARGET_MSG_CLASS) self.key = key self.desc = desc self.rev_key = rev_key Direction.actions.add(self) Direction.ref_map[key] = self
def run(self): printer = ActionPrinter() loader = Loader(self.logger) for json_text in loader.load_func(): self.logger.trello_json(json_text) json_dict = json.loads(json_text) actions = [] if 'boards' in json_dict: boards = json_dict['boards'] for b in boards: actions += b['actions'] elif 'actions' in json_dict: actions += json_dict['actions'] else: stderr('Unknown input format') sys.exit(1) actions.sort(lambda x,y: cmp(x['date'], y['date'])) for a in actions: action = Action(a) loader.saw_action(action) msg = printer.get_message(action) if msg is None: continue self.logger.zulip_msg(msg.replace('\n', '\t')) post_params = { 'type' : 'stream', 'to' : CONFIG.zulip_stream(), 'subject' : action.derive_subject(), 'content' : msg } if not ARGS.no_post: r = requests.post(ZULIP_URL, auth=CONFIG.zulip_auth(), data=post_params) if r.status_code != 200: stderr('Error %d POSTing to Zulip: %s' % (r.status_code, r.text)) sys.stdout.flush()
def __init__(self, cb, logger): Action.__init__(self, cb, logger) self.stopped = False self.bolo = {} self.bolo_domains = set() self.bolo_searches = [] self.bolo_lock = threading.Lock() threading.Thread.__init__(self)
def validMoves(self, config): self.player_pieces_pos = config.getPlayerPositions(self.color) self.enemy_pieces_pos = config.getEnemyPositions(self.color) x,y = self.pos valid_moves = [] # left bottom - right top diagonal for i in range(8): if util.isNotOutofBounds(x+i, y+i): # restricting movement because of other player pieces if (x+i,y+i) in self.player_pieces_pos: break valid_moves.append((x+i,y+i)) # restricting movement because of enemy pieces if (x+i,y+i) in self.enemy_pieces_pos: break for i in range(8): if util.isNotOutofBounds(x-i, y-i): # restricting movement because of other player pieces if (x-i,y-i) in self.player_pieces_pos: break valid_moves.append((x-i, y-i)) # restricting movement because of enemy pieces if (x+i,y+i) in self.enemy_pieces_pos: break # right botom - left top diagonal for i in range(8): if util.isNotOutofBounds(x-i, y+i): # restricting movement because of other player pieces if (x-i,y+i) in self.player_pieces_pos: break valid_moves.append((x-i,y+i)) # restricting movement because of enemy pieces if (x-i,y+i) in self.enemy_pieces_pos: break for i in range(8): if util.isNotOutofBounds(x+i, y-i): # restricting movement because of other player pieces if (x+i,y-i) in self.player_pieces_pos: break valid_moves.append((x+i, y-i)) # restricting movement because of enemy pieces if (x+i,y-i) in self.enemy_pieces_pos: break for (x,y) in valid_moves: # Check for collisions action = Action(self, (x,y), config) if not action.isValid(): valid_moves.remove((x,y)) return valid_moves
def __init__(self,action_id,ports_id,mode=1): Action.__init__(self,action_id) # print "creo setteraction %s" % str(ports_id) self.inverted_ports = {} if type(ports_id) == dict : self.involved_ports_id = ports_id.keys() self.inverted_ports = [ k for k,v in ports_id.items() if v ] else: self.involved_ports_id = ports_id self.mode = mode
def _process(self): self.msg = self._receive(True, 10) content = None if self.msg is not None: t.log.info("msg recived") content = self.msg.getContent() t.log.info(content) act = Action(content) res = act.execute() reply = self.msg.createReply() d = {'action':'reply', 'data':res} reply.setContent(d) self.myAgent.send(reply)
def main(): """! @brief Main of the software""" ## Qt Application app = QtGui.QApplication(sys.argv) app.setOrganizationName('Digiclever') app.setApplicationName('NFC Golf Ball Dispenser') ## Frame instance frame = Frame() frame.show() ## PiFaceControl instance piface = PiFaceControl() ## Action instance action = Action(piface) ## CardReader instance cardReader = CardReader(action) # connect signals to slots frame.b1.clicked.connect(cardReader.someBalls) frame.b2.clicked.connect(cardReader.manyBalls) frame.transaction.clicked.connect(lambda: action.getLastTransactions(cardReader.cardUid)) frame.admin.clicked.connect(frame.toggleAdminView) frame.log.clicked.connect(lambda: frame.displayAdmin(frame.adminUsername.text(), frame.adminPassword.text())) frame.bRecharge.clicked.connect(lambda: cardReader.recharge(frame.moneyBox.value())) frame.bCreateAccount.clicked.connect(lambda: action.addUser(frame.username.text(), frame.name.text(), frame.surname.text())) frame.bAddDevice.clicked.connect(lambda: action.addDevice(frame.username2.text(), cardReader.cardUid, cardReader.ATR)) action.status.connect(frame.displayStatus) action.transactionsLoaded.connect(frame.displayTransactions) frame.connect(frame.warningTimer, SIGNAL("timeout()"), cardReader.start) frame.connect(frame.releaseCardTimer, SIGNAL("timeout()"), cardReader.start) cardReader.connect(cardReader.timer, SIGNAL("timeout()"), cardReader.waitForCard) cardReader.updateWaiting.connect(frame.update) cardReader.cardDetected.connect(frame.displayCard) cardReader.warning.connect(frame.displayWarning) frame.activateButton.connect(piface.activateButtonListener) frame.deactivateButton.connect(piface.deactivateButtonListener) piface.b1.connect(cardReader.someBalls) piface.b2.connect(cardReader.manyBalls) piface.b3.connect(lambda: action.getLastTransactions(cardReader.cardUid)) piface.b4.connect(frame.toggleAdminView) cardReader.start() sys.exit(app.exec_())
def test_pin_full_example(self): p = Pin() action = Action() action.launch_code = 13 action.title = 'Open in Watchapp' action.type = 'openWatchApp' self.assertDoesNotRaise(ValidationException, action.validate) p.add_action(action) reminder = Reminder() reminder.time = '2015-08-04T20:00:00+00:00Z' reminder.layout.backgroundColor = '#FFFFFF' reminder.layout.body = 'Drama about a police unit...' reminder.layout.foregroundColor = '#000000' reminder.layout.largeIcon = 'system://images/TV_SHOW' reminder.layout.smallIcon = 'system://images/TV_SHOW' reminder.layout.tinyIcon = 'system://images/TV_SHOW' reminder.layout.subtitle = 'New Tricks' reminder.layout.title = 'Last Man Standing' reminder.layout.type = 'genericReminder' self.assertDoesNotRaise(ValidationException, reminder.validate) p.add_reminder(reminder) p.layout.backgroundColor = '#FFFFFF' p.layout.foregroundColor = '#000000' p.layout.tinyIcon = 'system://images/TV_SHOW' p.layout.title = 'Last Man Standing' p.layout.subtitle = 'New Tricks' p.layout.type = 'genericPin' p.layout.shortTitle = 'Last Man Standing' p.layout.body = 'Drama about a police unit...' p.layout.add_section('Series', 'New Tricks') self.assertDoesNotRaise(ValidationException, p.layout.validate) p.duration = 60 p.id = '101' p.time = '2015-08-04T20:00:00+00:00Z' self.assertDoesNotRaise(ValidationException, p.validate) p.time = '' self.assertRaises(ValidationException, p.validate)
def __init__(self, action_command, bodyfilter=None, auth_sender=None, quoted_firstline_re=None, quoted_actiontoken_re=None): Action.__init__(self, action_command, bodyfilter) if quoted_firstline_re is None: quoted_firstline_re = self.DEFAULT_QUOTED_FIRSTLINE_RE if quoted_actiontoken_re is None: quoted_actiontoken_re = self.DEFAULT_QUOTED_ACTIONTOKEN_RE self.quoted_firstline_re = quoted_firstline_re self.quoted_actiontoken_re = quoted_actiontoken_re self.auth_sender = auth_sender
def play(self, trick: Trick, wish=None): combination_to_play = self.get_combination_to_play(trick, wish) if combination_to_play is not None: self.hand -= combination_to_play self.hand_size -= combination_to_play.size if Mahjong() in combination_to_play.cards: return Action.play(player=self, combination=combination_to_play, wish=self.wish) else: return Action.play(player=self, combination=combination_to_play) else: # Empty action means passing return Action.passes(player=self)
def validMoves(self, config): valid_moves = [] x,y = self.pos final_pos = [(x+1,y),(x,y+1),(x+1,y+1),(x-1,y),(x,y-1),(x-1,y-1),(x+1,y-1),(x-1,y+1)] for posx,posy in final_pos: if util.isNotOutofBounds(posx, posy): action = Action(self, (posx, posy), config) if action.isValid(): valid_moves.append((posx,posy)) # Castling ? return valid_moves
def __init__(self): self.status = Status.uninitialized self.start_time = None self.state = StateChange() self.changes = ChangeStore() self.action = Action() self.device_info = device.info
def putAction(self, user, actionDict): assert isinstance(user, User) if 'userID' not in actionDict or 'no' not in actionDict or 'act' not in actionDict or 'data' not in actionDict or 'comment' not in actionDict or 'time' not in actionDict or 'parent' not in actionDict or 'root' not in actionDict or 'sign' not in actionDict: raise InvalidActionDictionary() if actionDict['parent'] is not None and actionDict['parent'] not in self.actions: raise NoParent() action = Action.newFromDict(self.getID(), user, **actionDict) if action.ID() in self.actions: raise ActionExists() self.actions[action.ID()] = action if self.versions[user.ID()] < actionDict['no']: self.versions[user.ID()] = actionDict['no'] if action.act == Action.Insert: self.latests[action.ID()] = [action] else: latests = self.latests[action.root] parent = self.get(action.parent) for i in range(len(latests)): if latests[i] == parent: latests.pop(i) latests.insert(0, action) latests.sort(key=lambda x: x.time, reverse=True) self._save() return action.ID()
def update(self, user, data, parent, comment = None): """parent is a action that will be updated""" assert isinstance(user, User) assert isinstance(data, int) or isinstance(data, float) or isinstance(data, str) or isinstance(data, tuple) or isinstance(data, list) or isinstance(data, dict) or isinstance(data, set) assert isinstance(parent, tuple) or isinstance(parent, Action) assert comment is None or isinstance(comment, str) if not self.isMember(user): raise NonMember() if isinstance(parent, tuple): parent = self.get(parent) self.versions[user.ID()] += 1 no = self.versions[user.ID()] sign = user.encrypt(str(data)) action = Action.new(self.getID(), user, no, Action.Update, data, comment, parent) self.actions[action.ID()] = action latests = self.latests[action.root] for i in range(len(latests)): if latests[i] == parent: latests.pop(i) latests.insert(0, action) latests.sort(key=lambda x: x.time, reverse=True) self._save() return action.ID()
def update(self, action: Action, out=False): self.actions.append(action) if action.has_passed(): self.ongoing_passes += 1 else: self.points += action.combination.get_points() if out: self.players -= 1
def __parse(self): actions = [] with open(self.file_name, 'r') as log_file: serp_page_num = None for line in log_file: parsed_line = _parse_line(line) condition = self.condition timestamp = _parse_datetime(parsed_line['date'], parsed_line['time']) action = Action(timestamp=timestamp, session=self.session, condition=condition, action_type=parsed_line['action'], query=self.query, serp_page_num=serp_page_num, action_parameters=parsed_line.get('action_parameters', None)) if action.is_serp_switch_event(): serp_page_num = int(action.result_page) actions.append(action) return sorted(actions, key=lambda action: action.timestamp)
def __str__(self): s = "%s %i\n"%(col("Unique ID"), self.ID) s += "%s %i, %i\n"%(col("Start"), self.startX, self.startY) s += "%s %i, %i\n"%(col("Location"), self.X, self.Y) s += "%s %s\n"%(col("Facing"), Action.toStr(self.facing)) t = "active" if self.active else "inactive" s += "%s %s\n"%(col("Status"), t) return s
def read_action(self, line): groups = self.match_regexp(self.action_re, line) name = groups[0] energy = int(groups[1]) range = (int(groups[2]), int(groups[3])) position = (int(groups[4]), int(groups[5])) action = groups[6] target = (int(groups[7]), int(groups[8])) soldier = Soldier(name, energy, range, position) return Action.from_string(action).for_soldier(soldier).on(target)
def put(self, user, data, comment = None): if not self.isMember(user): raise NonMember() self.versions[user.ID()] += 1 no = self.versions[user.ID()] sign = user.encrypt(str(data)) action = Action.new(self.getID(), user, no, Action.Insert, data, comment) self.actions[action.ID()] = action self.latests[action.ID()] = [action] self._save() return action.ID()
def __init__(self): """ Configuration """ # Camera settings self.FRAME_WIDTH = 341 self.FRAME_HEIGHT = 256 self.flip_camera = True # Mirror image self.camera = cv2.VideoCapture(1) # ...you can also use a test video for input #video = "/Users/matthiasendler/Code/snippets/python/tracker/final/assets/test_video/10.mov" #self.camera = cv2.VideoCapture(video) #self.skip_input(400) # Skip to an interesting part of the video if not self.camera.isOpened(): print "couldn't load webcam" return #self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, self.FRAME_WIDTH) #self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, self.FRAME_HEIGHT) self.filters_dir = "filters/" # Filter settings in trackbar self.filters_file = "filters_default" # Load filter settings current_config = self.filters_dir + self.filters_file self.filters = Filters(current_config) # No actions will be triggered in test mode # (can be used to adjust settings at runtime) self.test_mode = False # Create a hand detector # In fact, this is a wrapper for many detectors # to increase detection confidence self.detector = Detector(self.filters.config) # Knowledge base for all detectors self.kb = KB() # Create gesture recognizer. # A gesture consists of a motion and a hand state. self.gesture = Gesture() # The action module executes keyboard and mouse commands self.action = Action() # Show output of detectors self.output = Output() self.run()
def endLine(self, x, y): '''Saves the end of a stroke to the current layer''' if(self.currentLayer.visible): while(len(self.pointQueue) > 0): curPoint = self.pointQueue.popleft() self.drawPoint(curPoint[0], curPoint[1]) self.curStroke.append(curPoint) #Add the current stroke to the history and the layer newAction = Action() newAction.name = 'Stroke' finalStroke = Stroke(self.curStroke,255) if(not self.eraserMode): self.currentLayer.addStroke(finalStroke,self.brush) else: self.currentLayer.addStroke(finalStroke,self.eraser) newAction.stroke = finalStroke self.his.addAction(newAction) #Clear the canvas and the temporary stroke self.swap.colors = [255,255,255]*self.width*self.height self.swap.vertices = [0,0]*self.width*self.height self.curStroke = []
def __init__(self, rule_id, from_json=None): self.id = rule_id if from_json is None: from_json = {} self.scope = from_json.get('scope') self.name = from_json.get('name') self.description = from_json.get('description') self.references = from_json.get('references', []) cond_dict = from_json.get('condition') self.condition = Condition(cond_dict) if 'subject' in cond_dict else ConditionSet(cond_dict) action_dict = from_json.get('actions') self.actions = Action.from_array(action_dict) self.last_results = None
def __init__(self, port): #initiate a localhost server #TODO refactor for deployment on different IPs self.ip_address = '127.0.0.1' self.port = port self.sock = None self.resource = {"available": True, "amount": 100} self.myselfAsComputer = Computer(self.ip_address, self.port) self.known_computers = {} # {'<ip>_<port>':<Computer>} self.crack_tasks = {} # {'crack_task_id':<CrackTask>} self.connection = None self.resource_responded_task_ids = set() # {'<task_id>'} # Commands: resource[GET], resourcereply[POST], checkmd5[POST], answermd5[POST], crack[GET] # Action handlers. Usage: self.handle.<command>(params) self.handle = Action() self.addComputersFromMachinesTxt()
def move(self, direction): if direction != Action.Wait: dx,dy=Action.nextStep(direction) nx,ny=self.x+dx,self.y+dy if nx<0 or nx>=Level.__LEVEL_SIZE[0] or ny<0 or ny>=Level.__LEVEL_SIZE[1]: error('chip tried to step out side of bounds') return if not self.top_layer[ny][nx].canChipStep(): error('chip tried to step on something he cant') return status = self.top_layer[ny][nx].effect() self.top_layer[ny][nx] = self.top_layer[self.y][self.x] self.top_layer[self.y][self.x] = Empty(self.x, self.y) self.x=nx self.y=ny return status
def apply(self, action: Action, entity: Actor) -> None: if not entity.fighter: return fighter = entity.fighter fighter.hp = min(fighter.hp + self.amount, fighter.max_hp) action.report(f"{fighter.name} heal {self.amount} hp.")
} relayEvents[relay.get("key", relay_index)] = relayState rw = RelayWorker(relay, main_thread_running, system_ready, relayState['available'], relayState['active']) workers.append(rw) # Make the relays available, this event is toggled off elsewhere if we need to disable relays relayState['available'].set() relay_index +=1 except KeyError: Logger.log(LOG_LEVEL["info"], 'Relays Workers...\t\t\033[1;31m Disabled\033[0;0m') # Load in Actions try: if len(CONFIGS["actions"]) > 0: for action in CONFIGS["actions"]: action["redis"] = r a = Action(action) a.init_action() actions[a.key] = a Logger.log(LOG_LEVEL["info"], '{0} Actions...\t\t\t\t\033[1;32m Initializing\033[0;0m'.format(len(CONFIGS['actions']))) except KeyError: Logger.log(LOG_LEVEL["info"], 'Actions...\t\t\t\033[1;31m Disabled\033[0;0m') # Worker for Sequences try: if len(CONFIGS["sequences"]) > 0: for sequence in CONFIGS["sequences"]: sequence["redis"] = r sequenceState = { "available": threading.Event(), # Event to allow sequence to activate "active": threading.Event() # Event to signal sequence to open/close }
def __init__(self, state, player): Action.__init__(self, state, player, HARVEST_ACTION)
def test_try_action_fail2(self): # Tests a failing try_action due to action being invalid (not accessible via a straight # line path) with self.assertRaises(InvalidActionException): GameTree.try_action(GameTree(self.__state2), Action(Position(3, 0), Position(0, 0)))
def test_empty() -> None: perform = _wrap_performer(3, 5) assert (3, 0) == perform(Action(BaseAction.Empty, Target.Right), (3, 5)) assert (0, 5) == perform(Action(BaseAction.Empty, Target.Left), (3, 5))
def getAction(self): return [Action(damage=5)]
def __init__(self, object_name): self.object_name_ = object_name resource_name = 'object_' + object_name Action.__init__(self, 'point_at_' + resource_name, [resource_name], {resource_name: True}, {resource_name: True})
def __init__(self, name): Action.__init__(self, name) self.cmd_vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)
def decode_action(self, action: json) -> Action: if not len(action) == 2: raise JsonDecodeException('Tried to decode invalid action.') return Action(self.decode_position(action[0]), self.decode_position(action[1]))
def add_todo(text): global next_todo_id action = Action('ADD_TODO', t_id=next_todo_id, text=text) next_todo_id += 1 return action
def toggle_todo(t_id): return Action('TOGGLE_TODO', t_id=t_id)
def set_visibility_filter(vis_filter): return Action('SET_VISIBILITY_FILTER', vis_filter=vis_filter)
def addAction(self, name): action = Action(name) self.__actions.append(action)
elif actionType == 2: if needLog: log.append((str(stateStack), str(nodeStack), "ACCEPTED")) break else: assert False # print(stateStack, nodeStack, tokenType, actionType, nextState) # print(nodeStack) if needLog: return ParseTree(nodeStack[-1]), log return ParseTree(nodeStack[-1]) if __name__ == "__main__": typedef = TypeDefinition.load(FOLDER + "typedef") cfg = ContextFreeGrammar.load(typedef, FOLDER + "simpleJavaCFG") # action.save(FOLDER + "simpleJavaAction") # goto.save(FOLDER + "simpleJavaGoto") # exit() action = Action.load(cfg, FOLDER + "simpleJavaAction") goto = Goto.load(cfg, FOLDER + "simpleJavaGoto") with open(FOLDER + "test.sjava", "r") as f: src = f.read() tokenList = scanner.parse(typedef, src, ['line_comment', 'block_comment', 'space']) print(tokenList) pt = parse(tokenList, typedef, cfg, action, goto) print(pt)
def genActionGoto(typedef, cfg, needItemToID=False): cfgForFirst = cfg.removeLeftRecursion() if cfg.isLeftRecursive() else cfg firstDict = first(cfgForFirst) initProdID = cfg.nonTerminalToProdIDs[cfg.startSymbol][0] initItem = LRItem(cfg, initProdID, 0, {"$"}) initItemSet = LRItemSet(cfg) initItemSet.addItem(initItem) initItemSet = initItemSet.calcClosure(firstDict) que = deque([initItemSet]) edges = {} itemToID = {} coreToClosure = { } # calculate closure is time-costing. Thus use a dict to accelerate. while que: cur = que.popleft() if cur not in itemToID: itemToID[cur] = len(itemToID) for step in cur.getNext(): nextItemSetCore = cur.goto(step) # get the core first if nextItemSetCore not in coreToClosure: coreToClosure[nextItemSetCore] = nextItemSetCore.calcClosure( firstDict) nextItemSet = coreToClosure[nextItemSetCore] if nextItemSet not in itemToID: itemToID[nextItemSet] = len(itemToID) que.append(nextItemSet) edges.setdefault(itemToID[cur], []).append( (step, itemToID[nextItemSet])) # for k, v in itemToID.items(): # print(v) # print(toStr(typedef, k)) # TODO delete this after debug IDToItem = {v: k for k, v in itemToID.items()} action, goto = Action(cfg, len(itemToID)), Goto(cfg, len(itemToID)) for src, v in edges.items(): for step, dst in v: # src, step, dst forms a full edge. note that src and dst are int. # print("%d -> %d via %r" % (src, dst, step)) if cfg.isTerminal(step): if action[src][step] is not None: debug(src, step, dst, action, "action", (0, dst), typedef, IDToItem, cfg) else: action[src][step] = (0, dst) # 0 means Shift elif cfg.isNonTerminal(step): if goto[src][step] is not None: debug(src, step, dst, goto, "goto", dst, typedef, IDToItem, cfg) else: goto[src][step] = dst for k, v in itemToID.items(): for item in k.items: # print(toStr(typedef, item), item.atEnd()) if item.atEnd(): for sym in item.lookForward: if action[v][sym] is not None: debug(v, sym, None, action, "action", (1, item.productionID), typedef, IDToItem, cfg) else: if item.productionID: action[v][sym] = (1, item.productionID ) # 1 means Reduce else: action[v][sym] = (2, None) # 2 means Accept if needItemToID: return action, goto, itemToID else: return action, goto
def insertSeparator(self, separator=None, position=0, before=None): if separator == None: separator = Action(separator=True) self.insertAction(separator, position, before)
def __init__(self, ID, path): Thing.__init__(self, ID, path) self.set_description('metal sink', "This is an old metal sink, probably from the 1960's, and nothing seems wrong with it.") self.fix_in_place("You can't take the sink!") self.actions.append(Action(self.fill_container, ["fill"], True, False)) self.actions.append(Action(self.pour_out_in_sink, ['pour'], True, False))
def test_try_action_fail4(self): # Tests a failing try_action due to action involves moving thru another character with self.assertRaises(InvalidActionException): GameTree.try_action(GameTree(self.__state2), Action(Position(4, 0), Position(2, 1)))
def get_action(self, state: State) -> Action: # Determine where we are pos = state.placements[state.current_player][0] # Move in-place return Action(pos, pos)
def fill_possible_moves(self, player, rolls, current_move, possible_moves): """ Populates the possible_moves dict with possible moves. :param player: WHITE (0) or BLACK (1). :param rolls: List of integers between 1 and 6 inclusive. The rolls remaining. :param current_move: Tuple of Actions. The actions making up the move so far (i.e. from the previous rolls) :param possible_moves: Dict of features (tuple) mapping to moves (tuples of Actions). See get_possible_moves """ if not rolls: if current_move: # If all rolls have been played a move exists, apply the move and get the features from the opponent's # perspective. features = self.get_features(not player) possible_moves[features] = current_move return roll = rolls[0] # Range of points where the player can potentially move checkers to given the dice roll and the bar state. possible_ends = range(24 - roll, 25 - roll) if self.bar[player] > 0 else range( 0, 24 - roll) for end in possible_ends: # Cannot move checkers to a point with 2 or more opposing checkers. if self.points[not player][23 - end] >= 2: continue # Must move checkers from bar if there are checkers on the bar. if self.bar[player] > 0: action = Action(player, Action.BAR, end, roll) else: start = end + roll if self.points[player][start] <= 0: continue action = Action(player, start, end, roll) # Check if the action knocks off an opponent's checker. action.bars = self.points[not player][23 - end] == 1 # Apply the action and recurse and then undo the action to revert board state. self.apply_action(action) self.fill_possible_moves(player, rolls[1:], current_move + (action, ), possible_moves) self.apply_action(action, undo=True) # Check if bearing off is possible and attempt it if self.homed[player] == 15: if self.points[player][roll - 1] > 0: action = Action(player, roll - 1, Action.OFF_BOARD, roll) else: if sum(self.points[player][roll:6]) == 0: flag = False for i in range(roll - 2, -1, -1): if self.points[player][i] > 0: action = Action(player, i, Action.OFF_BOARD, roll) flag = True break if not flag: return else: return self.apply_action(action) self.fill_possible_moves(player, rolls[1:], current_move + (action, ), possible_moves) self.apply_action(action, undo=True)
def test_fill() -> None: perform = _wrap_performer(3, 5) assert (0, 5) == perform(Action(BaseAction.Fill, Target.Right), (0, 0)) assert (3, 0) == perform(Action(BaseAction.Fill, Target.Left), (0, 0)) assert (3, 1) == perform(Action(BaseAction.Fill, Target.Left), (1, 1))
def main(): session = Session() open_up_bets = Action(session.open_bet_screen, session.is_start_screen_open, gta=session.gta) find_odds = Action(session.determine_odds, session.is_bet_screen_open, gta=session.gta) place_bet = Action(session.place_bet, session.is_bet_screen_open, gta=session.gta) go_back_to_start = Action(session.go_back_to_beginning, session.is_end_screen_open, gta=session.gta) end_iter_tab = False while True: if not end_iter_tab: initial_tab = open_up_bets.act(tab=None, go_back=False) else: initial_tab = open_up_bets.act(tab=end_iter_tab, go_back=False) find_odds.act(tab=initial_tab, go_back=False) place_bet.act(tab=initial_tab, go_back=True) time.sleep(37) # Sleeps the duration of the "race" end_iter_tab = go_back_to_start.act(tab=None, go_back=False)
def test_try_action_fail3(self): # Tests a failing try_action due to action being out of turn (it involves moving someone # else but the current player's avatar, despite otherwise being legal) with self.assertRaises(InvalidActionException): GameTree.try_action(GameTree(self.__state2), Action(Position(0, 1), Position(2, 1)))
def __init__(self, thing, input_): Action.__init__(self, uuid.uuid4().hex, thing, 'fade', input_=input_)
def test_try_action_fail5(self): # Tests a failing try_action due to action involves moving to an already occupied tile with self.assertRaises(InvalidActionException): GameTree.try_action(GameTree(self.__state2), Action(Position(4, 0), Position(3, 0)))
def __init__(self): self.ui = UI() self.col = Collision(self.ui) self.act = Action(self.ui, self.col) self.act.start()
self.fnodes.append(n) def pop(self): return self.fnodes.pop() def isEmpty(self): return len(self.fnodes) == 0 def check(self, n): return n in self.fnodes def print(self): print("<Frontier>") for n in self.fnodes: n.print() print("</Frontier>") if __name__ == "__main__": f = Frontier() s = State("L", 3, 3, 0, 0) n = Node(None, s, None) f.add(n) f.print() f.add(Node(s, State("R", 2, 3, 1, 0), Action("R", 1, 0))) f.print() print(f.check(n)) f.pop() f.print()
def __init__(self, device, action, onDuration=100, offDuration=1500): Action.__init__(self) self.led = Led(device) self.action = action if not action in ['light', 'blink']: logger.error("Unhandeled action on led %s : %s", device, action)
def action(self): return Action(self.client)
def __init__(self, name, data): self.name = name self.actions = [] for a in data: self.actions.append(Action(a))