def dungeon_controller(): scene_start() opening_dialog_two() while global_game_states.current_scene == 'dungeon': received = input() if received.startswith('input Look_in_DirtPile'): received = received.split(' ') container = received[2] look_inside_nonfurniture_action(container) elif ((global_game_states.acquired_CellDoorKey) and (['Cell Door Key', 'Cell Door Key'] in global_game_states.player_inventory)): action('EnableIcon(UsePrisonDoor, door, Prison.CellDoor, Open, true)') global_game_states.acquired_CellDoorKey = False elif received.startswith('input Look_Inside_Chest'): received = received.split(' ') container = received[2] look_inside_furniture_action(container) elif received.startswith('input UsePrisonDoor'): received = received.split(' ') door = received[2] use_PrisonDoor_action(door) elif received.startswith('input Read '): book = received[11:] read_book(book) elif received.startswith('input Leave'): received = received.split(' ') exit_door = received[2] leave_action(exit_door) elif received.startswith('input CheckBody'): midscene_narration('Guard Lyra is unconscious but still breathing. She will live.') elif received.startswith('input ChangeClothes'): change_clothes_action() else: check_master_actions(received)
def city_setup(): # Set Day action('SetDay()') # Play Music action('PlaySound(Town_Day, City, true)')
def controls(cmd): if globalConfig.dir != cmd: globalConfig.dir = cmd print("_____cmd:" + cmd) action.action(cmd) return ''
def __init__(self): super(ActThree, self).__init__('data/levels/act_three.json') # create player self.player_character = character.GirlCharacter(Vector(32 * 10, 32 * 10)) self.player_character.ability_one = None self.player_character.ability_two = None self.add_updatable(self.player_character) self.set_camera(camera.VerticalPanningCamera(self.player_character, 32 * 10, # center x 32 * 20, # width 32 * 7)) # min_y #self.add_blocking_event(updatable.fade_from_black(1.0)) self.boss = character.ChieftainBoss(Vector(random.uniform(32*5,32*15), 32 * 20), self.player_character) self.add_updatable(self.boss) self.add_updatable(updatable.Spike(Vector(32 * 7, 32 * 18))) self.add_updatable(updatable.Spike(Vector(32 *14, 32 * 26))) self.add_updatable(updatable.Spike(Vector(32 * 5, 32 * 32))) self.add_updatable(updatable.Spike(Vector(32 *15, 32 * 30))) self.add_updatable(updatable.Spike(Vector(32 *17, 32 * 20))) self.play_dialog('data/dialog/act_three_chieftan_1.json') self.add_updatables(self.create_wave(Vector(32 * 5, 32 * 10), character.SpearEnemy, 4, 64)) self.add_updatables(self.create_wave(Vector(32 * 16, 32 * 16), character.SpearEnemy, 3, 64)) # lose when the player dies self.add_trigger( trigger.trigger(self, 'is_player_dead'), action.action_list( [ action.action(self, 'play_dialog', 'data/dialog/death_dialog.json'), action.action(self, 'end_with', game.SceneState.failed, updatable.fade_to_black(0.5)) ] ) ) # self.add_trigger( # trigger.trigger(self, 'should_spawn_wave'), # action.add_updatables(self.create_wave(Vector( # random.uniform(5*32,15*32), # random.uniform(5*32,25*32)), character.SpearEnemy, 4, 64)), True) self.add_trigger( trigger.trigger(self, 'should_do_dialog_one'), action.action(self, 'dialog_one')) self.add_trigger( trigger.trigger(self, 'should_do_dialog_two'), action.action(self, 'dialog_two')) self.add_trigger( trigger.trigger(self, 'should_do_dialog_final'), action.action(self, 'dialog_final'))
def __init__(self): super(ActTwo, self).__init__('data/levels/act_two.json') self.hermited = False # create player self.player_character = character.GirlCharacter(Vector(32 * 20, 32 * 10)) self.player_character.ability_one = None self.add_updatable(self.player_character) self.hermit = character.HermitCharacter(Vector(32 * 18 + 16, 32 * 52)) self.add_updatable(self.hermit) self.hermit.facing = character.Facing.left # set camera self.set_camera(camera.PlayerCamera(self.player_character, 32 * 20)) # create some enemies self.add_updatables(self.create_wave(Vector(32 * 13, 32 * 18), character.BombEnemy, 3, 96)) self.add_updatables(self.create_wave(Vector(32 * 27, 32 * 18), character.BombEnemy, 3, 96)) # start by fading from black self.add_updatable(updatable.fade_from_black(1.0)) # set up some triggers # lose when the player dies self.add_trigger( trigger.trigger(self, 'is_player_dead'), action.action_list( [ action.action(self, 'play_dialog', 'data/dialog/death_dialog.json'), action.action(self, 'end_with', game.SceneState.failed, updatable.fade_to_black(0.5)) ] ) ) self.add_trigger( trigger.trigger(self, 'should_start_hermit'), action.action_list([ action.add_updatables(self.create_wave(Vector(32 * 25, 32 * 40), character.BombEnemy, 2, 48)), action.add_updatables(self.create_wave(Vector(32 * 15, 32 * 40), character.BombEnemy, 2, 48)), action.action(self, 'do_hermit')])) self.add_trigger( trigger.trigger(self, 'should_spawn_wave'), action.action_list([ action.add_updatables(self.create_wave(Vector(32 * 25, 32 * 30), character.BombEnemy, 2, 48)), action.add_updatables(self.create_wave(Vector(32 * 15, 32 * 30), character.BombEnemy, 2, 48)) ])) self.add_trigger( trigger.trigger(self, 'victory'), action.action(self, 'do_victory'))
def alchemist_shop_convo(person): player_response = 'input Selected Menu' if person == 'Alchemist Henry': if global_game_states.blind_bandit_clue_aquired and (not global_game_states.alchemist_is_paranoid): player_response = set_dialog('Welcome! \\n[Menu | I had a few questions about the store...] \\n[Conspire | I may have overheard that a group of people conspired to kill the Queen] \\n[Next | Still looking around]', ['Menu', 'Conspire', 'Next']) if player_response == 'input Selected Menu': if global_game_states.found_poison_purchase == True: if global_game_states.found_poison == False: if global_game_states.identified_poison == False: player_response = set_dialog('Find anything you like? \\n[Purchase | Who is Tiana?] \\n[Next | Still looking around]', ['Purchase', 'Next']) else: player_response = set_dialog('Find anything you like? \\n[Purchase | Who is Tiana?] \\n[About | About that rat poison...] \\n[Next | Still looking around]', ['Purchase', 'About', 'Next']) else: if global_game_states.identified_poison == False: player_response = set_dialog('Need help with anything else? \\n[Purchase | Who is Tiana?] \\n[Free | Are you sure I can have this?] \\n[Next | No, thanks]', ['Purchase', 'Free', 'Next']) else: player_response = set_dialog('Need help with anything else? \\n[Purchase | Who is Tiana?] \\n[Free | Are you sure I can have this?] \\n[About | About that rat poison...] \\n[Next | No, thanks]', ['Purchase', 'Free', 'About', 'Next']) else: if global_game_states.found_poison == False: if global_game_states.identified_poison == False: player_response = set_dialog('Feel free to look around. \\n[Next | Thanks]') else: player_response = set_dialog('Find anything you like? \\n[About | About that rat poison...] \\n[Next | Still looking around]', ['About', 'Next']) else: if global_game_states.identified_poison == False: player_response = set_dialog('Need help with anything else? \\n[Free | Are you sure I can have this?] \\n[Next | No, thanks]', ['Free', 'Next']) else: player_response = set_dialog('Need help with anything else? \\n[Free | Are you sure I can have this?] \\n[About | About that rat poison...] \\n[Next| No, thanks]', ['About','Next']) elif player_response == 'input Selected Conspire': player_response = set_dialog('Did you? I-I-I wouldn\'t know anything about that. A travesty, yes. Her death was a travesty. \\n[DirectLie | I know you poisoned the Queen (lie)] \\n[DirectTruth | I know you poisoned the Queen] \\n[Indirect | I heard an alchemist brewed the Queen\'s last drink] \\n[Relent | I guess so]', ['DirectLie', 'DirectTruth', 'Indirect', 'Relent']) if player_response == 'input Selected DirectLie': set_dialog('Please, I didn\'t mean to! I only... I only sold the poison! I thought they were going to kill rats with it! You gotta believe me! \\n[Next | We\'ll see about that]') add_clue('The Alchemist confessed to selling poison to the murderers', 'Alchemist Testimonial') global_game_states.alchemist_is_paranoid = True elif player_response == 'input Selected DirectTruth': set_dialog('You know no such thing! I should call the guard on you, but you are lucky I feel generous today! \\n[Next | We\'ll see about that]') add_clue('The Alchemist became very defensive about the death of the Queen, but did not seem to want guards involved', 'Alchemist Testimonial') global_game_states.alchemist_is_paranoid = True elif player_response == 'input Selected Indirect': set_dialog('I see how it is. I will say only this. An alchemist brewing a Queen\'s drink would be very unlikely. However, someone the Queen trusted could gain access to the Queen\'s cup after it had been prepared and no one would think to check the contents. \\n[Next | We\'ll see about that]') add_clue('The Alchemist claimed innocence and blamed a mysterious trusted advisor of the Queen', 'Alchemist Testimonial') global_game_states.alchemist_is_paranoid = True if player_response == 'input Selected Purchase': player_response = set_dialog('Oh, Tiana? She\'s the Queen\'s sister. She recently bought some giant rat poison to help clear the sewers. \\n[Menu| Thanks]', ['Menu']) elif player_response == 'input Selected Free': player_response = set_dialog('If you\'re investigating for the king, take it! Quickly now! \\n[Menu| Okay...]', ['Menu']) elif player_response == 'input Selected About' and global_game_states.found_poison == False: player_response = set_dialog('Oh, the giant rat poison? I usually don\'t sell it to civilians. \\n[About2 | The king asked me]', ['About2']) if player_response == 'input Selected About2': player_response = set_dialog('You\'re investigating for the king? Take the display bottle. It\'s one of the purple ones, with a skull and crossbones. \\n[Menu | Thanks]', ['Menu']) action('EnableIcon(TakeLeft, hand, Poison, Take Giant Rat Poison, false)') add_clue('Giant rat poison was sold by Alchemist Henry', 'Found Poison') global_game_states.found_poison = True elif player_response == 'input Selected About' and global_game_states.found_poison == True: player_response = set_dialog('The giant rat poison? Didn\'t you already grab it? \\n[Menu | Yeah...]', ['Menu']) action('HideDialog()')
def Recognize(filename): import run_sarmata import action result = run_sarmata.RunSarmata(filename) if result: if len(result) > 1: action.action(result) else: Dictation(filename) else: Dictation(filename)
def enter_building(door): action('PlaySound(OpenDoor)') # Enter the tavern if door == 'City.GreenHouseDoor': global_game_states.prev_scene = 'city' global_game_states.current_scene = 'tavern' # Enter the alchemist shop elif door == 'City.BrownHouseDoor': global_game_states.prev_scene = 'city' global_game_states.current_scene = 'alchemist_shop' action('Exit(John, ' + door + ', true)')
def take_leftitem_action(item): # If the item was not already in inventory, pick it up and add it if [item, item] not in global_game_states.player_inventory: global_game_states.player_inventory.append([item, item]) remove_item(item) action('HideList()') action('Pickup(John, ' + item + ')') else: # If it was in inventory, take it out action('Unpocket(John, ' + item + ')') # Switch enabled icons action('DisableIcon(TakeLeft, ' + item + ')') action('EnableIcon(StowLeft, hand, ' + item + ', Stow, true)')
def buildasttable(self): opener = [ 'Hold .7', 'GCD', 'Play', 'oGCD', 'GCD', 'Draw', 'Sleeve Draw', 'GCD', 'Play', 'Draw', 'Redraw', 'GCD', 'Redraw', 'Redraw', 'Play', 'GCD', 'Divination' ] actiontable = [] astrecast = self.gcd for i in opener: self.clock = round(self.clock, 2) if i.split()[0] == 'Hold': actiontable.append(action(19, 'Hold', self.clock)) self.clock = self.clock + float(i.split()[1]) elif i.split()[0] == 'GCD': if self.nextgcd > self.clock: self.clock = round(self.nextgcd, 2) if self.nextaction > self.clock: self.clock = round(self.nextaction, 2) actiontable.append(action(100, 'GCD', self.clock)) self.nextgcd = round(self.clock + astrecast, 2) self.nextaction = round(self.clock + self.abilitydelay, 2) self.clock = round(self.clock + self.abilitydelay, 2) elif i.split()[0] == 'Play': actiontable.append(action(100, 'Play', self.clock)) self.nextaction = round(self.clock + self.abilitydelay, 2) self.clock = round(self.clock + self.abilitydelay, 2) elif i.split()[0] == 'oGCD': actiontable.append(action(100, 'oGCD', self.clock)) self.nextaction = round(self.clock + self.abilitydelay, 2) self.clock = round(self.clock + self.abilitydelay, 2) elif i.split()[0] == 'Draw': actiontable.append(action(100, 'Draw', self.clock)) self.nextaction = round(self.clock + self.abilitydelay, 2) self.clock = round(self.clock + self.abilitydelay, 2) elif i.split()[0] == 'Sleeve': actiontable.append(action(100, 'Sleeve Draw', self.clock)) self.nextaction = round(self.clock + self.abilitydelay, 2) self.clock = round(self.clock + self.abilitydelay, 2) elif i.split()[0] == 'Redraw': actiontable.append(action(100, 'Redraw', self.clock)) self.nextaction = round(self.clock + self.abilitydelay, 2) self.clock = round(self.clock + self.abilitydelay, 2) elif i.split()[0] == 'Divination': actiontable.append(action(100, 'Divination', self.clock)) self.nextaction = round(self.clock + self.abilitydelay, 2) self.clock = round(self.clock + self.abilitydelay, 2) elif i.split()[0] == 'Minor': actiontable.append(action(100, 'Minor Arcana', self.clock)) self.action = actiontable self.nextaction = 0 self.next = 0 self.clock = 0
def take_action(self, state): if state.last_move == 0: empty = [ pos for pos, tile in [(i, state.state[i]) for i in [12, 13, 14, 15]] if not tile ] elif state.last_move == 1: empty = [ pos for pos, tile in [(i, state.state[i]) for i in [0, 4, 8, 12]] if not tile ] elif state.last_move == 2: empty = [ pos for pos, tile in [(i, state.state[i]) for i in [0, 1, 2, 3]] if not tile ] elif state.last_move == 3: empty = [ pos for pos, tile in [(i, state.state[i]) for i in [3, 7, 11, 15]] if not tile ] else: empty = [pos for pos, tile in enumerate(state.state) if not tile] if empty: pos = self.choice(empty) if len(self.tile_bag) == 0: self.init_tile_bag() tile = self.choice(self.tile_bag) self.tile_bag.remove(tile) return action.place(pos, tile) else: return action()
def random_action(self, fac, size): decidors = list() decidors_size = 2 + (random.random() < (self.length_change * 2)) * (random.random() * 4 - 2) for j in range(decidors_size): decidors.append(self.random_decision(fac)) decisions = dict([(i, decidors[i]) for i in range(decidors)]) action_types = [fac.__class__] action_dict = dict([(f, fac.__class__) for f in fac.possible_actions]) for e in decidors: alist = dict([(a, e.obj_type.__class__) for a in e.obj_type.possible_actions]) action_dict.update(alist) action_types.append(e.obj_type.__class__) actions = list() args = list() size = size + (random.random() < (self.length_change * 2)) * int(random.random() * 4 - 2) size = min(size, 1) for j in range(size): try: act, arg = self.random_action(action_dict, action_types) actions.append(act) args.append(arg) except: break act_index = decidors_size actions = dict([(i + act_index, actions[i]) for i in range(len(actions))]) return action.action(decisions, actions, args)
def recordPress(key): if (key == pynput.keyboard.Key.esc): print("escape") return False de = getDelay() print("{0}".format(("key", (str(key), True, de)))) actions.append(action.action("key", (str(key), True), de) )
def run(): options = ChromeOptions() options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") chrome = webdriver.Remote( command_executor='http://172.28.0.13:5555/wd/hub', desired_capabilities=DesiredCapabilities.CHROME, options=options) logger = Log() my_act = action(chrome) p_price = Process(target=collect_price, args=( my_act, 'EURUSD', logger, )) # p_prof_loss = Process(target=collect_prof_loss, args=(my_act, logger, )) my_act.login() p_price.start() time.sleep(5) # p_prof_loss.start() p_price.join() # p_prof_loss.join() """
def take_action(self, state): legal = [op for op in range(4) if board(state).slide(op) != -1] if legal: op = self.choice(legal) return action.slide(op) else: return action()
def onRun(self,event): min_t = 0 i = 0 while True: i += 1 yes,num = self.nodes[0].getPacStat() if num != 0: energy = self.nodes[0].getEnergyStat() energy /= 10 # /1000*100 delay = self.nodes[0].getDelayStat() rate = str(yes/float(num)*100) #self.timer.Start(500) self.displayText[0].SetLabel(str(min_t*4/float(250000))) self.displayText[1].SetLabel(str(delay*4/float(250))) self.displayText[2].SetLabel(rate) self.displayText[3].SetLabel(str(energy)) wx.Yield() #self.timer.Start(100) if not self.eventList: break elif min_t > self.nodes[0].getPacInterval()*200: break else: min_index, min_t = min(enumerate(e.time for e in self.eventList),key=operator.itemgetter(1)) newList = action(self.eventList[min_index],self.nodes) self.eventList.pop(min_index) for n in newList: self.eventList.append(n) print 'Run'
def keyParse(data): key = None if data[KEY + 1] == "Key.up": key = pynput.keyboard.Key.up elif data[KEY + 1] == "Key.right": key = pynput.keyboard.Key.right elif data[KEY + 1] == "Key.down": key = pynput.keyboard.Key.down elif data[KEY + 1] == "Key.left": key = pynput.keyboard.Key.left elif data[KEY + 1] == "Key.backspace": key = pynput.keyboard.Key.backspace elif data[KEY + 1] == "Key.ctrl": key = pynput.keyboard.Key.ctrl elif data[KEY + 1] == "Key.shift": key = pynput.keyboard.Key.shift elif data[KEY + 1] == "Key.alt": key = pynput.keyboard.Key.alt elif data[KEY + 1] == "Key.tab": key = pynput.keyboard.Key.tab elif data[KEY + 1] == "Key.enter": key = pynput.keyboard.Key.enter else: key = data[KEY + 1][1] return action.action(data[0], (key, data[KEYSTATE + 1] == "True"), float(data[KEYLEN + 1]))
def handle(self): """ Handles all clients requests Input: Nothing Returns: Nothing """ import isockdata isock_data = isockdata.ISockData() try: isock_data.from_string(self.receive()); except base.ISockBaseException as error: isock_data.setException(error) else: try: action = self.server.findAction(isock_data.getActionClass()) except ServerException as error: isock_data.setException(error) else: try: isock_data.setOutputData(action.action(isock_data.getInputData())) except Exception as error: isock_data.setException(error) isock_data.setInputData(None) # Don't send client data back to client. try: self.send(isock_data.to_string()) except base.ISockBaseException as error: pass
def onRun(self, event): min_t = 0 i = 0 while True: i += 1 yes, num = self.nodes[0].getPacStat() if num != 0: energy = self.nodes[0].getEnergyStat() energy /= 10 # /1000*100 delay = self.nodes[0].getDelayStat() rate = str(yes / float(num) * 100) #self.timer.Start(500) self.displayText[0].SetLabel(str(min_t * 4 / float(250000))) self.displayText[1].SetLabel(str(delay * 4 / float(250))) self.displayText[2].SetLabel(rate) self.displayText[3].SetLabel(str(energy)) wx.Yield() #self.timer.Start(100) if not self.eventList: break elif min_t > self.nodes[0].getPacInterval() * 200: break else: min_index, min_t = min(enumerate(e.time for e in self.eventList), key=operator.itemgetter(1)) newList = action(self.eventList[min_index], self.nodes) self.eventList.pop(min_index) for n in newList: self.eventList.append(n) print 'Run'
def take_action(self, state,a,b,c,slideway): if slideway==10: empty = [pos for pos, tile in enumerate(state.state) if not tile] #print (state.state) elif slideway==0: empty = [pos for pos, tile in enumerate(state.state[12:16]) if not tile] empty=[i+12 for i in empty] #print (state.state[12:16]) elif slideway==1: empty = [pos for pos, tile in enumerate(state.state[0:4]) if not tile] #print (state.state[0:4]) elif slideway==2: empty = [pos for pos, tile in enumerate(state.state[3::4]) if not tile] empty=[i*4+3 for i in empty] #print (state.state[3::4]) elif slideway==3: empty = [pos for pos, tile in enumerate(state.state[0::4]) if not tile] empty=[i*4 for i in empty] #print (state.state[0::4]) if empty: pos = self.choice(empty) tile = self.choice(a*[1]+b*[2]+c*[3]) return action.place(pos, tile) else: return action()
def _test(self, test_data): for problem_set in test_data: total_cycletime = 0.0 sht = problem_set.shuttleNum clm = problem_set.columnNum flr = problem_set.floorNum rack = problem_set.rack.status rack_resized = state.get_storage_binary(rack) rack_resized = self.change_to_two_dimension(rack_resized, clm, flr) rack_resized = np.array(rack_resized) # scale down game image rack_resized = cv2.resize(rack_resized, (self.RESIZED_SCREEN_X, self.RESIZED_SCREEN_Y)) # first frame must be handled differently self._last_state = np.stack(tuple(rack_resized for _ in range(self.STATE_FRAMES)), axis=2) cycleNum = problem_set.requestLength / sht for order_idx in range(cycleNum): input = problem_set.input[order_idx * sht:order_idx * sht + sht] output = problem_set.output[order_idx * sht:order_idx * sht + sht] self._last_action = self._choose_next_action() for i in range(len(self._last_action)): if self._last_action[i] == 1: action_chosen = i break at = action.action() sol, cyc = at.dijk(rack, clm, flr, input, output) atg = actiongenerator.ActionGenerator() solution, cycletime = atg.generating_idx(rack, clm, flr, sol, action_chosen) sim = nextstate.simul() rack = sim.change_rs(rack, clm, flr, solution) rack_resized = state.get_storage_binary(rack) rack_resized = self.change_to_two_dimension(rack_resized, clm, flr) rack_resized = np.array(rack_resized) # scale down game image rack_resized = cv2.resize(rack_resized, (self.RESIZED_SCREEN_X, self.RESIZED_SCREEN_Y)) rack_resized = np.reshape(rack_resized, (self.RESIZED_SCREEN_X, self.RESIZED_SCREEN_Y, 1)) current_state = np.append(rack_resized, self._last_state[:, :, 1:], axis=2) # update the old values self._last_state = current_state total_cycletime += cycletime print total_cycletime
def take_action(self, before): best_v = float('-inf') best_a = None best_op = None for op in range(4): after = board(before) reward = after.slide(op) if reward != -1: tmp_v = reward + self.evaluate(after) if tmp_v > best_v: best_v = tmp_v best_a = action.slide(op) best_op = op if not self.isFirst: if best_v != float('-inf'): self.update(self.last_state, best_v) else: self.update(self.last_state, 0) self.last_state = board(before) self.last_state.slide(best_op) self.last_value = self.evaluate(self.last_state) self.isFirst = False if best_a == None: return action() else: return best_a
def take_action(self, state): empty = [pos for pos, tile in enumerate(state.state) if not tile] if empty: pos = self.choice(empty) tile = self.choice([1] * 9 + [2]) return False, action.place(pos, tile) else: return True, action()
def castle_postdeath(person): if person == 'King Phillip': action('PlaySound(Cry2)') set_dialog('My Margerie...what has happened to you! Please find out what has happened. \\n[Next| I\'m so sorry Phillip, let me look around]') if person == 'Tiana': set_dialog('I mean I never preferred my sister, but I would never have wished this upon her. \\n[Next| Why exactly did you two not get along?]') set_dialog('Father always favored her since she was in line for the throne. But again, I would never kill her because of it. \\n[Next| I think the whole kingdom will feel the gravity of this loss]') if person == 'Maester Purcell': set_dialog('Margerie was never supposed to go before this old coot. Whoever did this has pure malice in their heart. \\n[Next| We will bring them to justice]') if person == 'Noble Jeremy' or person == 'Noble Cecilia' or person == 'Merchant Bert': set_dialog('Oh how horrible! \\n[Next| Did you see anything?]') set_dialog('I\'m sorry I didn\'t see anything. \\n[Next| Okay let me know if you think of anything]') if person == 'Chamber Maid Scarlet': set_dialog('How can I help? \\n[Next| You served the drink did you notice anything unusual?]') set_dialog('No, I poured the wine straight out of the bottle when I was setting up earlier. Everyone\'s cups were filled from the same bottle. \\n[Next| Where did you get the wine?]') set_dialog('Where we always get it, the local tavern. \\n[Next| Where was the taste tester?]') set_dialog('Errrm....I think he was off today because of the Queen\'s birthday \\n[Next| Thanks for your time]')
def take_action(self, state): scores = [board(state).slide(op) for op in range(4)] max_value = max(scores) if max_value != -1: max_index = scores.index(max_value) return action.slide(max_index) else: return action()
def solvable(self, goal): # Check if the state has no empty slot x,y = np.where(goal == 0) if not list(x): return [] start_shape = goal.shape[0] search_history = [] possible_moves = action(goal) done = False search_history.extend(possible_moves) # Store visited states as a set of keys to reduce time complexity explored_lookup = set() for move in possible_moves: explored_lookup.add(self._matrix_to_string_key(move)) # Get all solveable states while not done: new_states = [] # search one layer while search_history: curr = search_history.pop(0) # check possible actions for unvisited state for step in action(curr): str_id = self._matrix_to_string_key(step) if str_id not in explored_lookup: explored_lookup.add(str_id) new_states.append(step) if not new_states: done = True else: # begin new layer of searching search_history.extend(new_states) # decompress back from string to numpy matrix explored = [] for key in explored_lookup: explored.append(self._string_key_to_matrix(key, start_shape)) return explored
def res_config(): text = field.get() action_res = action(text) folder, answers = action_res result.configure( text="""Answers:{}\nDetailed information is in folder {!r}.""".format( _TABLE02.format( *["•" if n in answers else " " for n in range(1, 10)]), folder))
def __init__(self): super(Title, self).__init__(None) self.add_updatable(updatable.Title()) self.add_trigger(trigger.key_pressed, action.action(self, 'end_with', game.SceneState.succeeded, updatable.fade_to_black(0.1))) # bogus self.set_camera(camera.PlayerCamera(None, 32 * 20))
def _check_keyboard_buffer(self, interrupt=False): if interrupt==True or ((self._last_typed > 0) and (time.time() - self._last_typed) >= 2): if self._keyboard_buffer != '': # [Action for Keyboard takes x,y of last click and keyboard_buffer]: act = action(state='keyboard', coords_list={'x': self._last_int_x, 'y': self._last_int_y}, keyboard_buffer=self._keyboard_buffer, stage=self._stage) self._stage._append(act) self._keyboard_buffer='' self._last_typed=0
def talk_action(person): # Set left and right character set_left_right('John', person) action('ShowDialog()') # Determine which dialog sequence to check depending on the current scene if not global_game_states.queen_death: castle_predeath(person) elif global_game_states.queen_death and global_game_states.current_scene == 'castle': castle_postdeath(person) elif global_game_states.current_scene == 'dungeon': dungeon_convo(person) elif global_game_states.current_scene == 'city': city_convo(person) elif global_game_states.current_scene == 'alchemist_shop': alchemist_shop_convo(person) elif global_game_states.current_scene == 'tavern': tavern_convo(person) action('HideDialog()')
def dungeon_convo(person): if person == 'Guard Lyra': action('SetExpression(Guard Lyra, surprised)') received = set_dialog('Wait, how did you open the cell... \\n[Attack | I need to escape, for the King! (Attack)] \\n[Talk | Listen, the King told me to escape. (Persuade)]', ['Attack', 'Talk'], True) if received == 'input Selected Talk': action('SetExpression(Guard Lyra, angry)') received = set_dialog('You expect me to believe that? I\'m calling the other guards. \\n[Attack | I can\'t let you do that! (Attack)] \\n[Show | I have a letter from the King! (Persuade)]', ['Attack', 'Show']) if received == 'input Selected Show': action('SetExpression(Guard Lyra, neutral)') set_dialog('That has the King\'s official seal on it... Fine, I\'ll let you go, but get out of here before I change my mind. \\n[Next | Next]') global_game_states.dungeon_guard_lives = True action('HideDialog()')
def record(filename): q2 = queue.Queue() def callback2(indata, frames, time, status): if status: print(status, file=sys.stderr) q2.put(indata) silence = 0 with sf.SoundFile(filename, mode='x', samplerate=44100, channels=1, subtype='PCM_16') as file: with sd.InputStream(device='pulse', channels=1, callback=callback2, blocksize=44100, samplerate=44100, dtype="int16"): file.write(audio_data) counter = 0 while True: counter +=1 data2 = q2.get() file.write(data2) try: if int(10 * np.log10(np.sqrt(np.mean((data2 / 65535) ** 2)))) < -15: print("stoprecording: " + filename) one = state.state.getInstance() one.state = False break except: None if counter < 5: result = run_sarmata.RunSarmata(filename) action.action(result) else: args = DictationArgs(filename) args.mic = True if args.wave is not None or args.mic: with create_audio_stream(args) as stream: settings = DictationSettings(args) recognizer = StreamingRecognizer(args.address, settings) print('Recognizing...') results = recognizer.recognize(stream) print_results(results) import pyautogui pyautogui.typewrite((str(results[0]['transcript'])))
def runSimulation(number): numOfNodes = number + 1 nodes = [] for i in range(numOfNodes): # initialize nodes argv = {} argv['ID'] = i argv['src'] = i argv['des'] = numOfNodes - 1 n = Source(argv) nodes.append(n) eventList = [] #for i in range(numOfNodes-1): # nodes[i].setPacInterval(dataRate) for i in range(numOfNodes - 1): t = random.randint(20, 150) * 20 e = initialization(t, i, numOfNodes) eventList.append(e) min_t = 0 flag = True timer = 20 data = [] while True: if not eventList: break elif min_t > fromSecondToSlot(5): # 6250000 # *4/250000 break else: min_index, min_t = min(enumerate(e.time for e in eventList), key=operator.itemgetter(1)) newList = action(eventList[min_index], nodes, 'normal') eventList.pop(min_index) for n in newList: eventList.append(n) if min_t > fromSecondToSlot(timer): # perform the collection temp = [] for i in range(numOfNodes - 1): temp.append(nodes[i].getChannelIndicators(450, 160)) data.append(temp) # and set the condition timer += 10 writer = csv.writer(open('data3.csv', 'w')) for eachData in data: writer.writerow([eachData[0][0], 1.0 - eachData[0][1]]) return
def recordClick(x, y, button, pressed): if action.mouse.position == (0,0): return False de = getDelay() if pressed: print("{0}".format((x, y, button, de))) actions.append(action.action("click", (x, y, button, pressed), de))
def add_clue(clue, clue_item): # If clue was already added, do not add again if [clue_item, clue] not in global_game_states.current_clues: # Append the clue to the clue list global_game_states.current_clues.append([clue_item, clue]) action('EnableIcon(ClueRead, Book, ' + clue_item + ', Read Clue, true)') # Depending on the current scene, add the clue to the appropriate clue scene list if global_game_states.current_scene == 'castle': global_game_states.castle_clues.append([clue_item, clue]) elif global_game_states.current_scene == 'dungeon': global_game_states.dungeon_clues.append([clue_item, clue]) elif global_game_states.current_scene == 'city': global_game_states.city_clues.append([clue_item, clue]) elif global_game_states.current_scene == 'alchemist_shop': global_game_states.alchemist_shop_clues.append([clue_item, clue]) elif global_game_states.current_scene == 'tavern': global_game_states.tavern_clues.append([clue_item, clue])
def runSimulation(number): numOfNodes = number+1 nodes = [] for i in range(numOfNodes): # initialize nodes argv = {} argv['ID'] = i argv['src'] = i argv['des'] = numOfNodes - 1 n = Source(argv) nodes.append(n) eventList = [] #for i in range(numOfNodes-1): # nodes[i].setPacInterval(dataRate) for i in range(numOfNodes-1): t = random.randint(20, 150)*20 e = initialization(t, i, numOfNodes) eventList.append(e) min_t = 0 flag = True timer = 20 data = [] while True: if not eventList: break elif min_t > fromSecondToSlot(5): # 6250000 # *4/250000 break else: min_index, min_t = min(enumerate(e.time for e in eventList),key=operator.itemgetter(1)) newList = action(eventList[min_index], nodes, 'normal') eventList.pop(min_index) for n in newList: eventList.append(n) if min_t > fromSecondToSlot(timer): # perform the collection temp = [] for i in range(numOfNodes-1): temp.append(nodes[i].getChannelIndicators(450, 160)) data.append(temp) # and set the condition timer += 10 writer = csv.writer(open('data3.csv', 'w')) for eachData in data: writer.writerow([eachData[0][0], 1.0-eachData[0][1]]) return
def insert_ob_exercise(self, tidx, percent): per = [] for a in range(len(percent)-1): for b in range(percent[a+1]): per.append(a + 1) tablename = 'exercise' + str(percent[0]) con = MySQLdb.connect(self.DBAdress, self.DBID, self.DBPassward, self.DBName) cur = con.cursor() simul = nextstate.simul() acg = actiongenerator.ActionGenerator() rw = reward.reward() ac = action.action() for pidx in range(1, 21): print pidx test = problemreader.ProblemReader(tidx) rs = test.get_problem(pidx).rack.status column = test.get_problem(pidx).rack.column floor = test.get_problem(pidx).rack.floor input = test.get_problem(pidx).input output = test.get_problem(pidx).output rs1 = test.get_problem(pidx).rack.status cum_cycletime = 0 for j in range(len(input) / 2): k = j + 1 inputs = input[(k * 2 - 2):k * 2] outputs = output[(k * 2 - 2):k * 2] i = random.randrange(0, 100) sol, cycletime = ac.dijk(rs1, column, floor, inputs, outputs) selected_action = per[i] new_sol = acg.action_fixed_action(rs1, column, floor, sol, selected_action) cycletime = rw.get_cycletime(new_sol) cum_cycletime += cycletime # rs2 = simul.change_rs(rs1, column, floor, new_sol) if j == ((len(input) / 2) - 1): cur.execute("""INSERT INTO """ + """%s""" % ( tablename) + """ (pidx,rs,act,inp,outp,reward,cum_reward,rsprime,terminal) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'O')""", (pidx, str(rs1), selected_action, str(inputs), str(outputs), cycletime, cum_cycletime, str(simul.change_rs(rs1, column, floor, new_sol)))) con.commit() else: cur.execute("""INSERT INTO """ + """%s""" % ( tablename) + """ (pidx,rs,act,inp,outp,reward,cum_reward,rsprime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)""", (pidx, str(rs1), selected_action, str(inputs), str(outputs), cycletime, cum_cycletime, str(simul.change_rs(rs1, column, floor, new_sol)))) con.commit() rs1 = simul.change_rs(rs1, column, floor, new_sol)
def __init__(self): super(Title, self).__init__(None) self.add_updatable(updatable.Title()) self.add_trigger( trigger.key_pressed, action.action(self, 'end_with', game.SceneState.succeeded, updatable.fade_to_black(0.1))) # bogus self.set_camera(camera.PlayerCamera(None, 32 * 20))
def tavern_controller(): scene_start() # Start Background noises for tavern action('StopSound()') action('PlaySound(Tavern, Tavern, true)') action('PlaySound(Fireplace, Tavern.Fireplace, true)') # Begin entry to tavern tavern_setup() action('SetPosition(John, Tavern.Door)') action('FadeIn()') # Endless loop until John leaves the tavern while global_game_states.current_scene == 'tavern' and global_game_states.accused == '': received = input() if received.startswith('input Enter'): global_game_states.current_scene = 'city' global_game_states.prev_scene = 'tavern' else: check_master_actions(received)
def registerObserver(self, target): pub.dbg(6, 'reg {2:>10} {1:>10} <--- {0}'.format(target.get('name') ,self.get('name'), target.get('type'))) if target.get('type')=='action': super(node, self).registerObserver( target) self.get('scripts').append(target) return 0 if target.get('type')=='route': super(node, self).registerObserver( target) this_action = action.action(node=self, target=target) this_action.register(self) return 0 assert() # no more type allowed
def validation_without_update(self, validation_data, p_idx, itr): training_data = copy.deepcopy(validation_data) sht = training_data.shuttleNum clm = training_data.columnNum flr = training_data.floorNum rack = training_data.rack.status[:] total_cycletime = 0.0 total_action = [0 for _ in range(self.ACTIONS_COUNT)] convertedrack = self.convert_rack(rack, itr) leftrack = self.change_to_two_dimension(convertedrack[:clm * flr], clm, flr) rightrack = self.change_to_two_dimension(convertedrack[clm * flr:], clm, flr) last_state = np.append(leftrack, rightrack, axis=2) cycleNum = training_data.requestLength / sht for order_idx in range(cycleNum): input = training_data.input[order_idx * sht:order_idx * sht + sht] output = training_data.output[order_idx * sht:order_idx * sht + sht] # choose an action given our last state readout_t = self._session.run(self._output_layer, feed_dict={self._input_layer: [last_state]})[0] action_chosen = np.argmax(readout_t) total_action[action_chosen] += 1 at = action.action() solution, cycletime = at.dijk_srsr_with_abc_idx(rack, clm, flr, input, output, action_chosen) sim = nextstate.simul() rack = sim.change_rs(rack, clm, flr, solution) convertedrack = self.convert_rack(rack, itr) leftrack = self.change_to_two_dimension(convertedrack[:clm * flr], clm, flr) rightrack = self.change_to_two_dimension(convertedrack[clm * flr:], clm, flr) current_state = np.append(leftrack, rightrack, axis=2) # update the old values last_state = current_state total_cycletime += cycletime print 'p_idx: %s cycletime: %s action: %s' % (p_idx + 1, int(total_cycletime), total_action)
def prepare(path, event, isdir, config, debug): """ Prepare everything: - Check what rule has to be applied - Check if the file is excluded """ if debug: if isdir: logpath = path + "/" else: logpath = path if not event == "RESTORE": print >> sys.stderr, ("[debug] %s %s event to process: %s, %s" % (time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()), "%.20f" % time.time(), event, logpath)) ruledir = None dirhighest = 0 for nr, item in enumerate(config.path): tempdirhighest = 0 if not path.startswith(item): continue for count, thing in enumerate(path.split('/')): try: item.split('/')[count] except IndexError: break if thing == item.split('/')[count]: tempdirhighest = tempdirhighest + 1 if tempdirhighest > dirhighest: if not is_excluded(path, config.excludepath[nr], config.excluderegex[nr]): dirhighest = tempdirhighest ruledir = nr if not ruledir == None: action(path, event, isdir, config, ruledir, debug)
def __init__(self, fac): self.build_city = lambda reward, resource: action.action( { "to_city" : decision.decision( fac.potential_cities, "area.potential." + resource, decision.decision.maximum ), "from_city" : decision.decision( fac.cities, "area.potential." + resource, decision.decision.minimum ) }, [ action.evaluator( "from_city", city.change, { "population": action.evaluator( "from_city", "population") - 10, "military": action.evaluator( "from_city", "military") - 5 } ), action.evaluator( "to_city", city.change, { "faction_ident": fac.ident, "population": 10, "military": 5 } ) ], { "citizen" : lambda city: create_citizen( fac, city ), "move" : lambda obj, city: action.movement( obj, city.pos, reward=reward), "action" : lambda obj, act: obj.give_action( act ) }, [ ["from_city"], ["citizen", "to_city"], ["citizen", "move"] ] )
def unregisterObserver(self, target): pub.dbg( 6, 'reg {2:>10} {1:>10} <-/- {0}'.format(target.get('name') ,self.get('name'), target.get('type'))) if target.get('type')=='action': super(node, self).unregisterObserver( target) assert(target in self.get('scripts')) self.get('scripts').remove(target) if target.get('applied'): this_action = action.action(node=self, target=target) this_action.register(self) return 0 if target.get('type')=='route': super(node, self).unregisterObserver( target) related_action_list = self.queryList_mc({'type':['action'], 'target':[target]}) for x in related_action_list: x.unregister(self) return 0 assert() # no more type allowed
def __init__(self, toklist): # Check toklist for valid tokens if len(toklist) < 2: # need at least 2 tokens raise ParseFailure, "Directive expected at least 3 tokens, found %d" % len(toklist) if toklist[-1] != ':': # last token should be a ':' raise ParseFailure, "Directive expected ':' but didn't find one" self.basetype = 'Directive' # the object can know its own basetype self.type = toklist[0] # the directive type of this instance self.Action = action.action() # create new action instance self.Action.varDict = {} # dictionary of variables used for emails etc self.actionList = [] # each directive will have a list of actions # Set up informational variables - these are common to all Directives # %h = hostname self.Action.varDict['h'] = log.hostname # %sys = command from a system() action # TODO self.Action.varDict['sys'] = '[sys not yet defined]' # %act = show list of actions taken preceded by "The following actions # were taken:" if any were taken self.Action.varDict['act'] = '[act not yet defined]' # %actnm = show list of actions taken (excluding email()'s) preceded by # "The following actions were taken:" if any were taken self.Action.varDict['actnm'] = '[actnm not yet defined]' # each directive has a unique ID self.ID = None # directives keep state information about themselves self.lastfailtime = None # last time a failure was detected self.faildetecttime = None # first time failure was detected for current problem self.ack = ack.ack() # ack object to track acknowledgements self.status = "ok" # status of most recent check: "ok" or "fail"
rack_size_h = column rack_size_v = floor for action in range(len(sol.loc)): loca = (rack_size_h * rack_size_v * sol.loc[action][0]) + (rack_size_v * sol.loc[action][1]) + \ sol.loc[action][2] if sol.oper[action] == 'S': rs2.insert(loca,sol.type[action]) rs2.pop(loca+1) elif sol.oper[action] == 'R': rs2.insert(loca, -1) rs2.pop(loca + 1) return rs2 if __name__ == '__main__': test = problemreader.ProblemReader(20) rs = test.get_problem(1).rack.status column = test.get_problem(1).rack.column floor = test.get_problem(1).rack.floor input = test.get_problem(1).input output = test.get_problem(1).output solu,ct = action.action().dijk(rs,column,floor,input[0:2],output[0:2])
def _train(self, training_data): for problem_set in training_data: sht = problem_set.shuttleNum clm = problem_set.columnNum flr = problem_set.floorNum rack = problem_set.rack.status rack_resized = state.get_storage_binary(rack) rack_resized = self.change_to_two_dimension(rack_resized, clm, flr) rack_resized = np.array(rack_resized) # scale down game image rack_resized = cv2.resize(rack_resized, (self.RESIZED_SCREEN_X, self.RESIZED_SCREEN_Y)) # first frame must be handled differently self._last_state = np.stack(tuple(rack_resized for _ in range(self.STATE_FRAMES)), axis=2) cycleNum = problem_set.requestLength / sht for order_idx in range(cycleNum): input = problem_set.input[order_idx * sht:order_idx * sht + sht] output = problem_set.output[order_idx * sht:order_idx * sht + sht] self._last_action = self._choose_next_action() for i in range(len(self._last_action)): if self._last_action[i] == 1: action_chosen = i break at = action.action() sol, cyc = at.dijk(rack, clm, flr, input, output) atg = actiongenerator.ActionGenerator() solution, cycletime = atg.generating_idx(rack, clm, flr, sol, action_chosen) sim = nextstate.simul() rack = sim.change_rs(rack, clm, flr, solution) rack_resized = state.get_storage_binary(rack) rack_resized = self.change_to_two_dimension(rack_resized, clm, flr) rack_resized = np.array(rack_resized) # scale down game image rack_resized = cv2.resize(rack_resized, (self.RESIZED_SCREEN_X, self.RESIZED_SCREEN_Y)) rack_resized = np.reshape(rack_resized, (self.RESIZED_SCREEN_X, self.RESIZED_SCREEN_Y, 1)) current_state = np.append(rack_resized, self._last_state[:, :, 1:], axis=2) if order_idx == cycleNum-1: terminal = True else: terminal = False # store the transition in previous_observations self._observations.append((self._last_state, self._last_action, cycletime/reward.reward().get_maxtime(clm, flr, sht), current_state, terminal)) if len(self._observations) > self.MEMORY_SIZE: self._observations.popleft() # only train if done observing if len(self._observations) > self.OBSERVATION_STEPS: # sample a mini_batch to train on mini_batch = random.sample(self._observations, self.MINI_BATCH_SIZE) # get the batch variables previous_states = [d[self.OBS_LAST_STATE_INDEX] for d in mini_batch] actions = [d[self.OBS_ACTION_INDEX] for d in mini_batch] rewards = [d[self.OBS_REWARD_INDEX] for d in mini_batch] current_states = [d[self.OBS_CURRENT_STATE_INDEX] for d in mini_batch] agents_expected_reward = [] # this gives us the agents expected reward for each action we might agents_reward_per_action = self._session.run(self._output_layer, feed_dict={self._input_layer: current_states}) for i in range(len(mini_batch)): if mini_batch[i][self.OBS_TERMINAL_INDEX]: # this was a terminal frame so need so scale future reward... agents_expected_reward.append(rewards[i]) else: agents_expected_reward.append( rewards[i] + self.FUTURE_REWARD_DISCOUNT * np.max(agents_reward_per_action[i])) # learn that these actions in these states lead to this reward self._session.run(self._train_operation, feed_dict={ self._input_layer: previous_states, self._action: actions, self._target: agents_expected_reward}) # update the old values self._last_state = current_state # gradually reduce the probability of a random actionself. if self._probability_of_random_action > self.FINAL_RANDOM_ACTION_PROB \ and len(self._observations) > self.OBSERVATION_STEPS: self._probability_of_random_action -= \ (self.INITIAL_RANDOM_ACTION_PROB - self.FINAL_RANDOM_ACTION_PROB) / self.EXPLORE_STEPS return self._input_layer, self._output_layer
def cycle_gragh(self): return if __name__ == '__main__': probnum = 28 pronum = 1 test = problemreader.ProblemReader(probnum) rs = test.get_problem(pronum).rack.status column = test.get_problem(pronum).rack.column floor = test.get_problem(pronum).rack.floor input = test.get_problem(pronum).input output = test.get_problem(pronum).output ts = action.action() ka = ksp_action.KSP_ACTION() sm = nextstate.simul() # size = len(input) / 2 size = 500 fig = plt.figure() ax = fig.add_subplot(111) axes = plt.gca() axes.set_xlim([0, 500]) axes.set_ylim([0, 4000]) # size = 200 # fig = plt.figure() # ax = fig.add_subplot(111) # axes = plt.gca() # axes.set_xlim([0, 200])
def generate(self,widget,evnmt,data=None): """ Do the work """ tmp_configfile="/tmp/inforevealer_tmp.conf" #tmp configuration file (substitute) self.verbosity = self.verbose_button.get_active() action.action(self.category,self.dumpfile,self.configfile,tmp_configfile,self.verbosity,gui=True) TextViewer(self.dumpfile)#open a new window with the result.
def main(argv): try: import getopt import sys #set default dumpfile='/tmp/inforevealer' tmp_configfile="/tmp/inforevealer_tmp.conf" #tmp configuration file (substitute) verbosity=False category="" runfile=None #option only for internal use, see above gui=False #run the GUI defaultPB = "http://pastebin.com" #Default pastebin website = defaultPB pastebin_choice=False ##################### # GETOPT ##################### try: options, remainder = getopt.gnu_getopt(sys.argv[1:], 'hlc:vf:pw:', ['help', 'list', 'category=', 'verbose', 'file=', 'pastebin', 'website', 'runfile=', 'gui' ]) except getopt.GetoptError: sys.stderr.write(_("Invalid arguments.")) io.usage() sys.exit(1) for opt, arg in options: if opt in ('-h', '--help'): io.usage() sys.exit() elif opt in ('-l', '--list'): #find categories.conf filename=readconf.find_categories_conf() #find validator.conf spec_filename=readconf.find_validator_conf() #open categories.conf with validator.conf configfile=readconf.open_config_file(filename,spec_filename) # load the list of categories list_category=readconf.LoadCategoryList(configfile) io.list(list_category) sys.exit() elif opt in ('-c', '--category'): category=arg elif opt in ('-v','--verbose'): verbosity=True elif opt in ('-f','--file'): dumpfile=arg elif opt in ('-p','--pastebin'): pastebin_choice=True elif opt in ('-w','--website'): website=arg if not website.endswith("/"): website += "/" elif opt in ('--runfile'): runfile=arg elif opt in ('--gui'): gui=True #First to do: runfile (internal use) if runfile != None: readconf.ReadAndMakeInternalDesire(tmp_configfile) sys.exit() else: #find categories.conf filename=readconf.find_categories_conf() #find validator.conf spec_filename=readconf.find_validator_conf() #open categories.conf with validator.conf configfile=readconf.open_config_file(filename,spec_filename) # load the list of categories list_category=readconf.LoadCategoryList(configfile) if gui==True: import gui gui.main(configfile,list_category) #check if category is ok elif category in list_category: action.action(category,dumpfile,configfile,tmp_configfile,verbosity) sendFileContent(dumpfile,title=category,website=website,version=None) else: sys.stderr.write(_('Error: Wrong category')) io.usage() sys.exit(1) except KeyboardInterrupt: sys.exit("KeyboardInterrupt caught.")
def _train(self, training_set, validation_set): iter = 0 print "obs with random action generating..." p_idx = 0 iter_validation = 0 while iter < self.ITERATION: iter += 1 training_data = copy.deepcopy(training_set[p_idx]) itr = training_data.itemTypeRate sht = training_data.shuttleNum clm = training_data.columnNum flr = training_data.floorNum rack = training_data.rack.status[:] total_cycletime = 0.0 total_action = [0 for _ in range(self.ACTIONS_COUNT)] convertedrack = self.convert_rack(rack, itr) leftrack = self.change_to_two_dimension(convertedrack[:clm * flr], clm, flr) rightrack = self.change_to_two_dimension(convertedrack[clm * flr:], clm, flr) self._last_state = np.append(leftrack, rightrack, axis=2) cycleNum = training_data.requestLength / sht for order_idx in range(cycleNum): input = training_data.input[order_idx * sht:order_idx * sht + sht] output = training_data.output[order_idx * sht:order_idx * sht + sht] self._last_action = self._choose_next_action() for i in range(len(self._last_action)): if self._last_action[i] == 1: action_chosen = i break total_action[action_chosen] += 1 at = action.action() solution, cycletime = at.dijk_srsr_with_abc_idx(rack, clm, flr, input, output, action_chosen) sim = nextstate.simul() rack = sim.change_rs(rack, clm, flr, solution) convertedrack = self.convert_rack(rack, itr) leftrack = self.change_to_two_dimension(convertedrack[:clm * flr], clm, flr) rightrack = self.change_to_two_dimension(convertedrack[clm * flr:], clm, flr) current_state = np.append(leftrack, rightrack, axis=2) if order_idx == cycleNum-1: terminal = True else: terminal = False # store the transition in previous_observations self._observations.append((self._last_state, self._last_action, - cycletime/reward.reward().get_maxtime\ (clm, flr, sht), current_state, terminal)) if len(self._observations) > self.MEMORY_SIZE: self._observations.popleft() # only train if done observing if len(self._observations) > self.OBSERVATION_STEPS: # sample a mini_batch to train on mini_batch = random.sample(self._observations, self.MINI_BATCH_SIZE) # get the batch variables previous_states = [d[self.OBS_LAST_STATE_INDEX] for d in mini_batch] actions = [d[self.OBS_ACTION_INDEX] for d in mini_batch] rewards = [d[self.OBS_REWARD_INDEX] for d in mini_batch] current_states = [d[self.OBS_CURRENT_STATE_INDEX] for d in mini_batch] agents_expected_reward = [] # this gives us the agents expected reward for each action we might agents_reward_per_action = self._session.run(self._output_layer, feed_dict={self._input_layer: current_states}) for i in range(len(mini_batch)): if mini_batch[i][self.OBS_TERMINAL_INDEX]: # this was a terminal frame so need so scale future reward... agents_expected_reward.append(rewards[i]) else: agents_expected_reward.append( rewards[i] + self.FUTURE_REWARD_DISCOUNT * np.max(agents_reward_per_action[i])) # learn that these actions in these states lead to this reward self._session.run(self._train_operation, feed_dict={ self._input_layer: previous_states, self._action: actions, self._target: agents_expected_reward}) # update the old values self._last_state = current_state # gradually reduce the probability of a random actionself. if self._probability_of_random_action > self.FINAL_RANDOM_ACTION_PROB and len(self._observations) > self.OBSERVATION_STEPS: self._probability_of_random_action -= \ (self.INITIAL_RANDOM_ACTION_PROB - self.FINAL_RANDOM_ACTION_PROB) / self.EXPLORE_STEPS total_cycletime += cycletime p_idx += 1 if p_idx == len(training_set): p_idx = 0 if self._probability_of_random_action > self.FINAL_RANDOM_ACTION_PROB: print 'training with random action probability:', self._probability_of_random_action else: iter_validation += 1 print 'validation', iter_validation for i in range(len(validation_set)): self.validation_without_update(validation_set[i], i, itr)
actiontype.carryout = func return func return register def report(actiontype): def register(func): actiontype.report = func return func return register localhost = Host(state, "localhost", "127.0.0.1") state.localhost = localhost state.current = localhost connect = action("connect", Host) disconnect = action("disconnect", Host) @prompt def defaultprompt(): output.addmsg("{}@{} >".format(state.current.name, state.current.address)) @oninput def getline(): return output.getline() @parse def defaultparse(argv): if argv[0] not in state.actions: output.addmsg("Error: command {} not found".format(argv[0])) return None
def run(self): # extracting list of indicator to be treated for the used paas crObj=TransformXmlToCr() crObj.readXml('listCRs.xml') crList=crObj.getcr() # for each indicator, a thread will be executed and run in order to extract his result crTh=[] i=0 for cr in crList: crTh.append(threadCR(self.host,cr)) crTh[i].start() i=i+1 # waiting for all threads to be completed for th in crTh: th.join() f=open('content.log','r') fileContent=f.readlines() print fileContent f.close() f=open('content.log','w') f.write('') f.close() #browsing all decisions and choosing action to execute compactList=[] extendList=[] testAdd=False testRem=False testExt=False testCmpt=False for ind in fileContent: d=ind.split(',') if 'add' in d[1]: # adding vm testAdd=True break elif 'rem' in d[1]: # removing vm testRem=True break elif 'ext' in d[1]: # indicator will be extended testExt=True extendList.append(d[0]) elif 'cmpt' in d[1]: testCmpt=True # indicator will be compacted.append(d[0]) compactList.append(d[0]) # choosing action to optimize # choosing vm to edit if removing or modifying number=len(self.listVMs) #choosing the last vm to edit choice=action(self.listVMs[number-1]) if testAdd: # addingVM choice.add_vm() elif testRem: # removing VM choice.remove_vm() elif testExt: # extending VM choice.extend_vm(extendList) elif testCmpt: # compacting vm choice.compact_vm(compactList)
def parse(self, model, root_node, fields, notebook=None, paned=None): dict_widget = {} saw_list = [] # state aware widget list attrs = tools.node_attributes(root_node) on_write = attrs.get('on_write', '') container = _container() container.new(col=int(attrs.get('col', 4))) self.container = container if not self.title: attrs = tools.node_attributes(root_node) self.title = attrs.get('string', 'Unknown') for node in root_node: attrs = tools.node_attributes(node) if node.tag=='image': icon = gtk.Image() icon.set_from_stock(attrs['name'], gtk.ICON_SIZE_DIALOG) container.wid_add(icon,colspan=int(attrs.get('colspan',1)),expand=int(attrs.get('expand',0)), ypadding=10, fill=int(attrs.get('fill', 0))) elif node.tag=='separator': orientation = attrs.get('orientation', 'horizontal') if orientation == 'vertical': vbox = gtk.HBox(homogeneous=False, spacing=0) else: vbox = gtk.VBox() if 'string' in attrs: text = attrs.get('string', 'No String Attr.') l = gtk.Label('<b>'+(text.replace('&','&').replace('<','<').replace('>','>'))+'</b>') l.set_use_markup(True) l.set_alignment(0.0, 0.5) eb = gtk.EventBox() eb.set_events(gtk.gdk.BUTTON_PRESS_MASK) eb.add(l) container.trans_box_label.append((eb, text, None)) vbox.pack_start(eb) if orientation == 'vertical': vsep = gtk.VSeparator() rowspan = int(attrs.get('rowspan', '1')) vsep.set_size_request(1, 20*rowspan) vbox.pack_start(vsep, False, False, 5) xoptions = gtk.SHRINK else: xoptions = False vbox.pack_start(gtk.HSeparator()) container.wid_add(vbox,colspan=int(attrs.get('colspan',1)), xoptions=xoptions,expand=int(attrs.get('expand',0)), ypadding=10, fill=int(attrs.get('fill', 0))) elif node.tag=='label': text = attrs.get('string', '') if not text: for node in node: text += node.text align = float(attrs.get('align', 0)) eb = container.create_label(text, markup=True, align=align, width=int(attrs.get('width', -1)), angle=attrs.get('angle'), wrap=attrs.get('wrap', True), help=attrs.get('help')) container.trans_box_label.append((eb, text, None)) container.wid_add( eb, colspan=int(attrs.get('colspan', 1)), expand=False, fill=int(attrs.get('fill', 0)) ) elif node.tag=='newline': container.newline() elif node.tag=='button': if attrs.get('invisible', False): visval = eval(attrs['invisible'], {'context':self.screen.context}) if visval: continue if 'default_focus' in attrs and not self.default_focus_button: attrs['focus_button'] = attrs['default_focus'] self.default_focus_button = True button = Button(attrs) states = [e for e in attrs.get('states','').split(',') if e] saw_list.append(StateAwareWidget(button, states=states)) container.wid_add(button.widget, colspan=int(attrs.get('colspan', 1))) elif node.tag=='notebook': if attrs.get('invisible', False): visval = eval(attrs['invisible'], {'context':self.screen.context}) if visval: continue nb = gtk.Notebook() if attrs and 'tabpos' in attrs: pos = {'up':gtk.POS_TOP, 'down':gtk.POS_BOTTOM, 'left':gtk.POS_LEFT, 'right':gtk.POS_RIGHT }[attrs['tabpos']] else: if options.options['client.form_tab'] == 'top': pos = gtk.POS_TOP elif options.options['client.form_tab'] == 'left': pos = gtk.POS_LEFT elif options.options['client.form_tab'] == 'right': pos = gtk.POS_RIGHT elif options.options['client.form_tab'] == 'bottom': pos = gtk.POS_BOTTOM nb.set_tab_pos(pos) nb.set_border_width(3) container.wid_add(nb, colspan=attrs.get('colspan', 3), expand=True, fill=True ) _, widgets, saws, on_write = self.parse(model, node, fields, nb) saw_list += saws dict_widget.update(widgets) elif node.tag=='page': if attrs.get('invisible', False): visval = eval(attrs['invisible'], {'context':self.screen.context}) if visval: continue if attrs and 'angle' in attrs: angle = int(attrs['angle']) else: angle = int(options.options['client.form_tab_orientation']) l = gtk.Label(attrs.get('string','No String Attr.')) l.attrs=attrs.copy() l.set_angle(angle) widget, widgets, saws, on_write = self.parse(model, node, fields, notebook) saw_list += saws dict_widget.update(widgets) notebook.append_page(widget, l) elif node.tag =='field': name = str(attrs['name']) del attrs['name'] name = unicode(name) type = attrs.get('widget', fields[name]['type']) if 'selection' in attrs: attrs['selection'] = fields[name]['selection'] fields[name].update(attrs) fields[name]['model'] = model if not type in widgets_type: continue fields[name]['name'] = name if 'saves' in attrs: fields[name]['saves'] = attrs['saves'] if 'filename' in attrs: fields[name]['filename'] = attrs['filename'] if 'default_focus' in attrs and not self.default_focus_field: fields[name]['focus_field'] = attrs['default_focus'] self.default_focus_field = True widget_act = widgets_type[type][0](self.window, self.parent, model, fields[name]) self.widget_id += 1 widget_act.position = self.widget_id label = None if not int(attrs.get('nolabel', 0)): # TODO space before ':' depends of lang (ex: english no space) if gtk.widget_get_default_direction() == gtk.TEXT_DIR_RTL: label = ': '+fields[name]['string'] else: label = fields[name]['string']+' :' dict_widget[name] = widget_act size = int(attrs.get('colspan', widgets_type[ type ][1])) expand = widgets_type[ type ][2] fill = widgets_type[ type ][3] hlp = fields[name].get('help', attrs.get('help', False)) if attrs.get('height', False) or attrs.get('width', False): widget_act.widget.set_size_request( int(attrs.get('width', -1)), int(attrs.get('height', -1))) if attrs.get('invisible', False): visval = eval(attrs['invisible'], {'context':self.screen.context}) if visval: continue translate = fields[name]['string'] if fields[name].get('translate') else None detail_tooltip = False if options.options['debug_mode_tooltips']: detail_tooltip = self.create_detail_tooltip(name, fields[name]) widget_label = container.create_label(label, help=hlp, fname=name, detail_tooltip=detail_tooltip) if label else None if attrs.get('attrs'): saw_list.append(StateAwareWidget(widget_act, widget_label)) container.wid_add(widget=widget_act.widget, label=widget_label, expand=expand, translate=translate, colspan=size, fname=name, fill=fill) elif node.tag =='group': frame = gtk.Frame(attrs.get('string', None)) frame.attrs=attrs frame.set_border_width(0) states = [e for e in attrs.get('states','').split(',') if e] if attrs.get('invisible', False): visval = eval(attrs['invisible'], {'context':self.screen.context}) if visval: continue state_aware = StateAwareWidget(frame, states=states) saw_list.append(state_aware) if attrs.get("width",False) or attrs.get("height"): frame.set_size_request(int(attrs.get('width', -1)) ,int(attrs.get('height', -1))) hbox = gtk.HBox(homogeneous=False, spacing=0) hbox.pack_start(frame, expand=False, fill=False, padding=0) group_wid = hbox else: group_wid = frame container.wid_add(group_wid, colspan=int(attrs.get('colspan', 1)), expand=int(attrs.get('expand',0)), rowspan=int(attrs.get('rowspan', 1)), ypadding=0, fill=int(attrs.get('fill', 1))) container.new(int(attrs.get('col',4))) widget, widgets, saws, on_write = self.parse(model, node, fields) state_aware.frame_child.update(widgets) dict_widget.update(widgets) saw_list += saws frame.add(widget) if not attrs.get('string', None): frame.set_shadow_type(gtk.SHADOW_NONE) container.get().set_border_width(0) container.pop() elif node.tag =='hpaned': hp = gtk.HPaned() container.wid_add(hp, colspan=int(attrs.get('colspan', 4)), expand=True, fill=True) _, widgets, saws, on_write = self.parse(model, node, fields, paned=hp) saw_list += saws dict_widget.update(widgets) #if 'position' in attrs: # hp.set_position(int(attrs['position'])) elif node.tag =='vpaned': hp = gtk.VPaned() container.wid_add(hp, colspan=int(attrs.get('colspan', 4)), expand=True, fill=True) _, widgets, saws, on_write = self.parse(model, node, fields, paned=hp) saw_list += saws dict_widget.update(widgets) if 'position' in attrs: hp.set_position(int(attrs['position'])) elif node.tag =='child1': widget, widgets, saws, on_write = self.parse(model, node, fields, paned=paned) saw_list += saws dict_widget.update(widgets) paned.pack1(widget, resize=True, shrink=True) elif node.tag =='child2': widget, widgets, saws, on_write = self.parse(model, node, fields, paned=paned) saw_list += saws dict_widget.update(widgets) paned.pack2(widget, resize=True, shrink=True) elif node.tag =='action': from action import action name = str(attrs['name']) widget_act = action(self.window, self.parent, model, attrs) dict_widget[name] = widget_act container.wid_add(widget_act.widget, colspan=int(attrs.get('colspan', 3)), expand=True, fill=True) for (ebox,src,name,widget) in container.trans_box: ebox.connect('button_press_event',self.translate, model, name, src, widget, self.screen, self.window) for (ebox,src,name) in container.trans_box_label: ebox.connect('button_press_event', self.translate_label, model, name, src, self.window) return container.pop(), dict_widget, saw_list, on_write
def runSimulation(dataRate): numOfNodes = 41 nodes = [] for i in range(numOfNodes): # initialize nodes argv = {} argv['ID'] = i argv['src'] = i argv['des'] = numOfNodes - 1 n = source(argv) nodes.append(n) eventList = [] #for i in range(numOfNodes-1): # nodes[i].setPacInterval(dataRate) ''' for i in range(numOfNodes-1): # the last node as the sink if i < 5: for t in pacGenerator(math.ceil(nodes[i].getPacInterval()),1,2000): print t e = initPacket(t,i,numOfNodes) eventList.append(e) else: for t in pacGenerator(math.ceil(nodes[i].getPacInterval()),1,21000,20000): print t e = initPacket(t,i,numOfNodes) eventList.append(e) ''' for i in range(numOfNodes-1): if i < 10: t = random.randint(1800,2200) else: t = random.randint(300000,310000) e = initPacket(t,i,numOfNodes) eventList.append(e) min_t = 0 data = [] for i in range(numOfNodes): dataEach = [] data.append(dataEach) time = [] while True: #print min_t if min_t%100 < 0.15: print min_t time.append(min_t) for i in range(numOfNodes-1): data[i].append(nodes[i].getPacInterval()) if not eventList: break elif min_t > nodes[0].getPacInterval()*200: break else: min_index, min_t = min(enumerate(e.time for e in eventList),key=operator.itemgetter(1)) newList = action(eventList[min_index],nodes) eventList.pop(min_index) for n in newList: eventList.append(n) #for d in data: # writeResult(d,'result.csv') statSuc = [] statAll = [] statDelay = [] statEnergy = [] aveH = [] #print 'Average Packet Delay for each node. (Unit: ms).' for i in range(numOfNodes-1): #nodes[i].setPacInterval((60+j*20)*20) # For Figure 1 yes,num = nodes[i].getPacStat() statSuc.append(yes) statAll.append(num) statDelay.append(nodes[i].getDelayStat()) statEnergy.append(nodes[i].getEnergyStat()) # End # For Figure 2 d = data e = time # End #print nodes[i].getDelayStat()*4/250000.0*1000 #nodes[i].printEnergyStat() #print nodes[i].getChannelIndicators() #print nodes[i].getPacInterval() #print nodes[1].getPacInterval() #print sum(statSuc)/float(sum(statAll)) #h = float(nodes[i].getPacInterval())/20.0 #aveH.append(h) #print h #print 'Average Packet Sucessful Rate for each node. (%)' #for i in range(numOfNodes-1): # yes,num = nodes[i].getPacStat() # print yes/float(num)*100 #print numpy.mean(aveH) #print nodes[1].getDelayStat() #print sum(statSuc)/float(sum(statAll))/(nodes[1].getEnergyStat()/h)**8/h # 10000 is just to amplify the num # the following are for Figure 1 a = sum(statSuc)/float(sum(statAll))/nodes[1].getPacInterval() b = sum(statDelay)/float(numOfNodes-1) c = sum(statEnergy)/float(numOfNodes-1) # End # the following are for Figure 2 # End return d,e
def __init__(self): super(ActOne, self).__init__('data/levels/act_one.json') # create player self.player_character = character.GirlCharacter(Vector(32 * 10, 32 * 3)) self.player_character.facing = character.Facing.top self.add_updatable(self.player_character) # set camera self.set_camera(camera.VerticalPanningCamera(self.player_character, 32 * 11, # center x 32 * 20, # width 32 * 8)) # min_y # create some enemies self.add_updatables(self.create_wave(Vector(4 * 32, 8 * 32), character.MeleeEnemy, 2, 48)) self.add_updatables(self.create_wave(Vector(13 * 32, 9 * 32), character.MeleeEnemy, 3, 48)) # fade from black self.add_blocking_event(updatable.fade_from_black(1.0)) # play some dialog self.play_dialog('data/dialog/act_one_intro.json') # set up some triggers # lose when the player dies self.add_trigger( trigger.trigger(self, 'is_player_dead'), action.action_list( [ action.action(self, 'play_dialog', 'data/dialog/death_dialog.json'), action.action(self, 'end_with', game.SceneState.failed, updatable.fade_to_black(0.5)) ] ) ) # enemy waves self.add_trigger( trigger.trigger(self, 'should_spawn_wave_2'), action.action_list( [ action.add_updatables(self.create_wave(Vector(3 * 32, 21 * 32), character.MeleeEnemy, 4, 48)), action.add_updatables(self.create_wave(Vector(17 * 32, 24 * 32), character.MeleeEnemy, 3, 48)) ] ) ) self.add_trigger( trigger.trigger(self, 'should_spawn_wave_3'), action.action_list( [ action.add_updatables(self.create_wave(Vector(2 * 32, 33 * 32), character.MeleeEnemy, 4, 48)), action.add_updatables(self.create_wave(Vector(12 * 32, 36 * 32), character.MeleeEnemy, 5, 64)) ] ) ) # boss, dialog, win when all enemies are dead self.add_trigger( trigger.trigger(self, 'should_spawn_boss'), action.action_list( [ action.add_updatable(character.WarlordBoss(Vector(random.uniform(32*5,32*15), 32 * 48 - 8), self.player_character)), action.add_trigger( self, trigger.trigger(self, 'all_enemies_dead'), action.action_list( [ action.action(self, 'play_dialog', 'data/dialog/act_one_warlord_1.json'), action.action(self, 'girl_points'), action.action(self, 'play_dialog', 'data/dialog/act_one_warlord_2.json'), action.action(self, 'end_with', game.SceneState.succeeded, updatable.fade_to_black(0.5)) ] ) ) ] ) )
def _train(self, problem): iter = 0 training_data = copy.deepcopy(problem) sht = training_data.shuttleNum clm = training_data.columnNum flr = training_data.floorNum best_cycletime = 1000000. while iter < self.ITERATION: rack = training_data.rack.status[:] total_cycletime = 0.0 total_action = [0 for _ in range(self.ACTIONS_COUNT)] input = training_data.input[0:0 + sht] output = training_data.output[0:0 + sht] foe = state.get_rack_full_or_empty(rack) foe = self.change_to_two_dimension(foe, clm, flr) son_in = state.get_rack_same_or_not(rack, input) son_out = state.get_rack_same_or_not(rack, output) for i in range(len(son_in)): foe = np.append(foe, self.change_to_two_dimension(son_in[i], clm, flr), axis=2) for i in range(len(son_out)): foe = np.append(foe, self.change_to_two_dimension(son_out[i], clm, flr), axis=2) self._last_state = foe[:, :, :] cycleNum = training_data.requestLength / sht for order_idx in range(cycleNum): input = training_data.input[order_idx * sht:order_idx * sht + sht] output = training_data.output[order_idx * sht:order_idx * sht + sht] self._last_action = self._choose_next_action() for i in range(len(self._last_action)): if self._last_action[i] == 1: action_chosen = i break total_action[action_chosen] += 1 at = action.action() solution, cycletime = at.dijk_density(rack, clm, flr, input, output, action_chosen) sim = nextstate.simul() rack = sim.change_rs(rack, clm, flr, solution) input = training_data.input[order_idx * sht:order_idx * sht + sht] output = training_data.output[order_idx * sht:order_idx * sht + sht] foe = state.get_rack_full_or_empty(rack) foe = self.change_to_two_dimension(foe, clm, flr) son_in = state.get_rack_same_or_not(rack, input) son_out = state.get_rack_same_or_not(rack, output) for i in range(len(son_in)): foe = np.append(foe, self.change_to_two_dimension(son_in[i], clm, flr), axis=2) for i in range(len(son_out)): foe = np.append(foe, self.change_to_two_dimension(son_out[i], clm, flr), axis=2) current_state = foe[:, :, :] if order_idx == cycleNum-1: terminal = True else: terminal = False # store the transition in previous_observations self._observations.append((self._last_state, self._last_action, - cycletime/reward.reward().get_maxtime\ (clm, flr, sht), current_state, terminal)) self._observations.popleft() # sample a mini_batch to train on mini_batch = random.sample(self._observations, self.MINI_BATCH_SIZE) # get the batch variables previous_states = [d[self.OBS_LAST_STATE_INDEX] for d in mini_batch] actions = [d[self.OBS_ACTION_INDEX] for d in mini_batch] rewards = [d[self.OBS_REWARD_INDEX] for d in mini_batch] current_states = [d[self.OBS_CURRENT_STATE_INDEX] for d in mini_batch] agents_expected_reward = [] # this gives us the agents expected reward for each action we might agents_reward_per_action = self._session.run(self._output_layer, feed_dict={self._input_layer: current_states}) for i in range(len(mini_batch)): if mini_batch[i][self.OBS_TERMINAL_INDEX]: # this was a terminal frame so need so scale future reward... agents_expected_reward.append(rewards[i]) else: agents_expected_reward.append( rewards[i] + self.FUTURE_REWARD_DISCOUNT * np.max(agents_reward_per_action[i])) # learn that these actions in these states lead to this reward self._session.run(self._train_operation, feed_dict={ self._input_layer: previous_states, self._action: actions, self._target: agents_expected_reward}) # update the old values self._last_state = current_state # gradually reduce the probability of a random actionself. if self._probability_of_random_action > self.FINAL_RANDOM_ACTION_PROB: self._probability_of_random_action -= \ (self.INITIAL_RANDOM_ACTION_PROB - self.FINAL_RANDOM_ACTION_PROB) / self.EXPLORE_STEPS total_cycletime += cycletime if best_cycletime > total_cycletime: best_cycletime = total_cycletime iter += 1 print iter, self._probability_of_random_action, best_cycletime, total_cycletime, total_action
def __init__(self, toklist): # Check toklist for valid tokens if len(toklist) < 2: # need at least 2 tokens raise ParseFailure, "Directive expected at least 2 tokens, found %d" % len(toklist) if len(toklist) > 3: # no more than 3 tokens raise ParseFailure, "Directive expected no more than 3 tokens, found %d" % len(toklist) if toklist[-1] != ':': # last token should be a ':' raise ParseFailure, "Directive expected ':' but didn't find one" self.ID = None # No ID by default if len(toklist) == 3: self.ID = utils.stripquote(toklist[1]) # grab ID if given self.basetype = 'Directive' # the object can know its own basetype self.type = toklist[0] # the directive type of this instance self.request_collector() # request data collector reference self.hastokenparser = 1 # tell parser this object has a separate tokenparser() self.Action = action.action() # create new action instance self.defaultVarDict = {} # dictionary of variables used by action strings self.args = Args() # Container for arguments #self.args.actionList = [] # each directive will have a list of actions #self.args.act2okList = [] # a list of actions for failed state changing to ok #self.args.actelseList = [] # a list of actions for state remaining ok # Set up informational variables - these are common to all Directives # %(hostname)s = hostname # %(h)s = hostname (shorthand for '%(hostname)s') self.defaultVarDict['hostname'] = log.hostname self.defaultVarDict['h'] = log.hostname # Create initial variable dictionary self.Action.varDict = {} # Set default output displayed on console connections self.console_output = '%(state)s' # List of directives this directive is dependent on self.actiondependson = [] # action dependencies self.checkdependson = [] # check dependencies # directives keep state information about themselves self.state = State(self) self.requeueTime = None # specific requeue time can be specified self.args.numchecks = 1 # perform only 1 check at a time by default self.args.checkwait = 0 # time to wait in between multiple checks self.args.template = None # no template by default self.args.disabled = False # default "disabled" state to not disabled self.current_actionperiod = 0 # reset the current actionperiod self.lastactiontime = 0 # time previous actions were called self.history_size = 0 # keep no history by default self.history = None # keep historical data for checks, if required self.excludehosts = [] # chris 2002-12-24: hosts to exclude from directive execution self.actionmaxcalls = None # chris 2002-12-24: can set limit on number of action calls self.performedactions = 0 # chris 2003-10-03: clear actions called flag