def get_data(): datax = [] datay = [] for i in tqdm(range(1, 60)): try: data_score = get_score(i)[0] data_state = get_state(i, 5) data_eeg = get_epoch_eeg(i).drop(["condition"], axis=1) if not (len(data_score) == len(data_eeg["epoch"].value_counts()) and len(data_score) == len( data_state[data_state["markerText"] == "ShotOps"])): continue print("yes") for shoot in range(len(data_score)): datax.append( get_aeraeeg_psd(data_eeg[data_eeg["epoch"] == i][-1000:])) datay.extend(data_score) """ data=get_raw_eeg(i) events,event_id=mne.events_from_annotations(data) epochs=mne.Epochs(data,events,event_id,tmin=-5,tmax=0,event_repeated='drop',preload=True) first,second=get_score(i+1) rest_eeg=epochs["s1001"][0] total_shot_num=len(first)+len(second) first_shoot_eeg=epochs["s1002"][-total_shot_num:-len(second)] first_shoot_eeg["s1002"][0].plot_psd(fmin=2., fmax=40., average=True, spatial_colors=False,picks=["Fz"]) plt.show() """ except Exception as e: traceback.print_exc() pass return datax, datay
def cmd_show_vm(message): logger.info("command show VM/server info", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) st = state.get_state(message.from_user.id) # it's block a code, need to for show status VM after action with VM try: # after migrate (for exemple) we set state in dict (id_vm = {}) # and command show will be return us state many times srv_id = state.get_id_vm(message.from_user.id) if len(srv_id) == 36: recording = 1 else: recording = 0 except: recording = 0 if recording == 1: answer = opstack.bot_show_vm(state.get_id_vm(message.from_user.id)) bot.send_message(message.chat.id, f"I remember you chose: <code>{srv_id}</code>", parse_mode="HTML") send_large_msg(message.chat.id, "".join(answer)) bot.send_message(message.chat.id, f"if you have to choose a new server /cancel or repeat /show", parse_mode="HTML") elif st == config.States.S_start.value or st is False: bot.send_message(message.chat.id, "Ok, i show it, give my ID VM") state.set_state(message.from_user.id, config.States.S_cmd_show_vm.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active command /cancel") else: logger.error("error in cmd_show_vm")
def one_step_lookahead(self, value, error_prob=0): new_policy_matrix = [[[None for y in xrange(self.length)] for x in xrange(self.width)] for h in xrange(self.num_headings)] for state in self.state_space.states: possible_states = self.state_space.get_adjacent_states(state) max_action_value = float("-inf") best_action = None for action_tuple in ac.action_space: action = ac.Action(action_tuple[0], action_tuple[1]) action_value = 0 for next_state in possible_states: x, y, h = next_state.get_state() action_value += self.transition_prob( error_prob, state, action, next_state) * value[h][x][y] # add all Psa(s')V(s') if action_value > max_action_value: max_action_value = action_value best_action = action x, y, h = state.get_state() new_policy_matrix[h][x][y] = best_action new_policy = pol.Policy(new_policy_matrix) return new_policy
def bmc_power_on(): r""" Power the Open BMC machine on and monitor status to verify. """ grp.rprint_timen("Refreshing state data.") state = state_mod.get_state() grp.rprint_var(state) match_state = state_mod.anchor_state(state) grp.rprintn() cmd_buf = ["Initiate Power On", "wait=${0}"] grp.rpissuing_keyword(cmd_buf) power = BuiltIn().run_keyword(*cmd_buf) state_change_timeout = BuiltIn().get_variable_value( "${STATE_CHANGE_TIMEOUT}", default="1 min") # Wait for the state to change in any way. state_mod.wait_state(match_state, wait_time=state_change_timeout, interval="3 seconds", invert=1) if state_mod.OBMC_STATES_VERSION == 0: cmd_buf = [ "Create Dictionary", "power=${1}", "bmc=HOST_BOOTED", "boot_progress=FW Progress, Starting OS" ] else: # TODO: Add back boot_progress when ipmi is enabled on Witherspoon. cmd_buf = [ "Create Dictionary", "chassis=On", "bmc=Ready", # "boot_progress=FW Progress, Starting OS", "host=Running" ] grp.rdpissuing_keyword(cmd_buf) final_state = BuiltIn().run_keyword(*cmd_buf) os_host = BuiltIn().get_variable_value("${OS_HOST}", default="") if os_host != "": final_state['os_ping'] = 1 final_state['os_login'] = 1 final_state['os_run_cmd'] = 1 final_state = state_mod.anchor_state(final_state) grp.rprintn() power_on_timeout = BuiltIn().get_variable_value("${POWER_ON_TIMEOUT}", default="14 mins") state_mod.wait_state(final_state, wait_time=power_on_timeout, interval="3 seconds")
def get_data(): datax = [] datay = [] high, low = 0, 0 for i in tqdm(range(1, 60)): if i == 32: continue try: data_score = get_score(i)[0] data_state = get_state(i, 3) data_eeg = get_epoch_eeg(i).drop(["condition"], axis=1) data_aimtrack = get_aimtrack(i) data_aimtrack.drop( data_aimtrack[data_aimtrack["exp_num"] == 2].index, inplace=True) data_aimtrack.drop(["exp_num"], axis=1, inplace=True) """ extract aimtrack data """ if not (len(data_score) == len(data_eeg["epoch"].value_counts()) and len(data_score) == len( data_state[data_state["markerText"] == "ShotOps"]) and len(data_score) == len( data_aimtrack["shoot_num"].value_counts())): continue print("yes") for j in range(len(data_score)): if data_score[j] > 9.5: curaimtrackx = data_aimtrack[data_aimtrack["shoot_num"] == j + 1]["x"][-40:].tolist() curaimtracky = data_aimtrack[data_aimtrack["shoot_num"] == j + 1]["y"][-40:].tolist() if len(curaimtrackx) != 40 or len(curaimtracky) != 40: continue datax.append([curaimtrackx, curaimtracky]) datay.append(0) print(data_score[j]) high += 1 if data_score[j] < 7.5: curaimtrackx = data_aimtrack[data_aimtrack["shoot_num"] == j + 1]["x"][-40:].tolist() curaimtracky = data_aimtrack[data_aimtrack["shoot_num"] == j + 1]["y"][-40:].tolist() if len(curaimtrackx) != 40 or len(curaimtracky) != 40: continue datax.append([curaimtrackx, curaimtracky]) datay.append(1) low += 1 print(len(datay), len(datax)) #if len(datay)!=len(datax): # raise Exception("length not matched") except Exception as e: traceback.print_exc() pass print(low, high) return datax, datay
def get_data(): datax = [] datay = [] high, low = 0, 0 for i in tqdm(range(1, 60)): if i == 32: continue try: data_score = get_score(i)[0] data_state = get_state(i, 3) data_eeg = get_epoch_eeg(i).drop(["condition"], axis=1) if not (len(data_score) == len(data_eeg["epoch"].value_counts()) and len(data_score) == len( data_state[data_state["markerText"] == "ShotOps"])): continue print("yes") for j in range(len(data_score)): if data_score[j] > 9.5: datay.append(0) c6 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-3000:-2500]) c5 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-2500:-2000]) c4 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-2000:-1500]) c3 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-1500:-1000]) c2 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-1000:-500]) c1 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-500:]) datax.append([c6, c5, c4, c3, c2, c1]) high += 1 if data_score[j] < 7.5: datay.append(1) c6 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-3000:-2500]) c5 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-2500:-2000]) c4 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-2000:-1500]) c3 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-1500:-1000]) c2 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-1000:-500]) c1 = get_aeraeeg_corr( data_eeg[data_eeg["epoch"] == j][-500:]) datax.append([c6, c5, c4, c3, c2, c1]) low += 1 print(len(datay), len(datax)) #if len(datay)!=len(datax): # raise Exception("length not matched") except Exception as e: traceback.print_exc() pass print(low, high) return datax, datay
def server_list(message): logger.info("command list all server in tenant/projectd", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) st = state.get_state(message.from_user.id) if st == config.States.S_start.value or st is False: bot.send_message(message.chat.id, "Ok, send my <code>tenant/project name</code>", parse_mode="HTML") state.set_state(message.from_user.id, config.States.S_server_list.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active state /cancel") else: logger.error("error in cmd_show_vm")
def quota_show(message): logger.info("command show quota", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) st = state.get_state(message.from_user.id) if st == config.States.S_start.value or st is False: bot.send_message(message.chat.id, "Ok, send my <code>tenant name</code>", parse_mode="HTML") state.set_state(message.from_user.id, config.States.S_quota_show.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active state /cancel") else: logger.error("error in server_diagnostic")
def get_data(): datax=[] datay=[] high,low=0,0 for i in tqdm(range(1,60)): if i==32: continue try: data_score=get_score(i)[0] data_state=get_state(i,3) data_eeg=get_epoch_eeg(i).drop(["condition"],axis=1) if not (len(data_score)==len(data_eeg["epoch"].value_counts()) and len(data_score)==len(data_state[data_state["markerText"]=="ShotOps"])): continue print("yes") for j in range(len(data_score)): if data_score[j]>9.5: datay.append(0) high+=1 d6=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-3000:-2500]) d5=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-2500:-2000]) d4=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-2000:-1500]) d3=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-1500:-1000]) d2=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-1000:-500]) d1=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-500:]) datax.append([d6,d5,d4,d3,d2,d1]) if data_score[j]<7.5: datay.append(1) low+=1 d6=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-3000:-2500]) d5=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-2500:-2000]) d4=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-2000:-1500]) d3=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-1500:-1000]) d2=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-1000:-500]) d1=get_aeraeeg_psd(data_eeg[data_eeg["epoch"]==j][-500:]) datax.append([d6,d5,d4,d3,d2,d1]) print(len(datay),len(datax)) #if len(datay)!=len(datax): # raise Exception("length not matched") """ data=get_raw_eeg(i) events,event_id=mne.events_from_annotations(data) epochs=mne.Epochs(data,events,event_id,tmin=-5,tmax=0,event_repeated='drop',preload=True) first,second=get_score(i+1) rest_eeg=epochs["s1001"][0] total_shot_num=len(first)+len(second) first_shoot_eeg=epochs["s1002"][-total_shot_num:-len(second)] first_shoot_eeg["s1002"][0].plot_psd(fmin=2., fmax=40., average=True, spatial_colors=False,picks=["Fz"]) plt.show() """ except Exception as e: traceback.print_exc() pass print(low,high) return datax,datay
def discover_channel_psd_difference(): highscore_epoch, lowscore_epoch = None, None highscorenum, lowscorenum = 0, 0 for i in range(1, 60): try: data_score = get_score(i)[0] data_state = get_state(i, 3) data_eeg = get_epoch_eeg(i).drop(["condition"], axis=1) data_raw_eeg = get_raw_eeg(i) if not (len(data_score) == len(data_eeg["epoch"].value_counts()) and len(data_score) == len( data_state[data_state["markerText"] == "ShotOps"])): continue print("yes") events, event_id = mne.events_from_annotations(data_raw_eeg) epochs = mne.Epochs(data_raw_eeg, events, event_id, tmin=-3, tmax=0, event_repeated='drop', preload=True) first, second = get_score(i + 1) rest_eeg = epochs["s1001"][0] total_shot_num = len(first) + len(second) first_shoot_eeg = epochs["s1002"][-total_shot_num:-len(second)] for j in range(len(data_score)): if data_score[j] > 9: if highscore_epoch == None: highscore_epoch = first_shoot_eeg["s1002"][j] else: highscore_epoch = mne.concatenate_epochs( [highscore_epoch, first_shoot_eeg["s1002"][j]]) highscorenum += 1 if data_score[j] < 8: if lowscore_epoch == None: lowscore_epoch = first_shoot_eeg["s1002"][j] else: lowscore_epoch = mne.concatenate_epochs( [lowscore_epoch, first_shoot_eeg["s1002"][j]]) lowscorenum += 1 print(highscorenum) print(lowscorenum) except Exception as e: traceback.print_exc() channelnames = ["Fz", "F3", "F4", "P3", "Pz", "P4", "O1", "O2", "POz"] print("test") for channelname in channelnames: plot_channel_psd(highscore_epoch, channelname) for channelname in channelnames: plot_channel_psd(lowscore_epoch, channelname)
def cmd_tv(message): logger.info("command get console", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) # get state for check st = state.get_state(message.from_user.id) if st == config.States.S_start.value or st is False: bot.send_message(message.chat.id, "Send my *ID VM*", parse_mode="Markdown") # if state ok, push state in dict and start wrapper state.set_state(message.from_user.id, config.States.S_cmd_tv.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active command /cancel") else: # Exit to error logger.error("err in cmd_tv")
def bmc_power_on(): r""" Power the Open BMC machine on and monitor status to verify. """ grp.rprint_timen("Refreshing state data.") state = state_mod.get_state() grp.rprint_var(state) match_state = state_mod.anchor_state(state) grp.rprintn() cmd_buf = ["Initiate Power On", "wait=${0}"] grp.rpissuing_keyword(cmd_buf) power = BuiltIn().run_keyword(*cmd_buf) state_change_timeout = BuiltIn().get_variable_value( "${STATE_CHANGE_TIMEOUT}", default="1 min") # Wait for the state to change in any way. state_mod.wait_state(match_state, wait_time=state_change_timeout, interval="3 seconds", invert=1) if state_mod.OBMC_STATES_VERSION == 0: cmd_buf = ["Create Dictionary", "power=${1}", "bmc=HOST_BOOTED", "boot_progress=FW Progress, Starting OS"] else: # TODO: Add back boot_progress when ipmi is enabled on Witherspoon. cmd_buf = ["Create Dictionary", "chassis=On", "bmc=Ready", # "boot_progress=FW Progress, Starting OS", "host=Running"] grp.rdpissuing_keyword(cmd_buf) final_state = BuiltIn().run_keyword(*cmd_buf) os_host = BuiltIn().get_variable_value("${OS_HOST}", default="") if os_host != "": final_state['os_ping'] = 1 final_state['os_login'] = 1 final_state['os_run_cmd'] = 1 final_state = state_mod.anchor_state(final_state) grp.rprintn() power_on_timeout = BuiltIn().get_variable_value( "${POWER_ON_TIMEOUT}", default="14 mins") state_mod.wait_state(final_state, wait_time=power_on_timeout, interval="3 seconds")
def get_pre_reboot_state(): r""" Get and return a custom state which is comprised of the st.default_req_states plus epoch_seconds. """ global state req_states = ['epoch_seconds'] + st.default_req_states gp.qprint_timen("Get system state.") state = st.get_state(req_states=req_states, quiet=0) gp.qprint_var(state) return state
def bmc_power_off(): r""" Power the Open BMC machine off and monitor status to verify. """ grp.rprint_timen("Refreshing state data.") state = state_mod.get_state() grp.rprint_var(state) match_state = state_mod.anchor_state(state) grp.rprintn() cmd_buf = ["Initiate Power Off"] grp.rpissuing_keyword(cmd_buf) power = BuiltIn().run_keyword(*cmd_buf) state_change_timeout = BuiltIn().get_variable_value( "${STATE_CHANGE_TIMEOUT}", default="1 min") # Wait for the state to change in any way. state_mod.wait_state(match_state, wait_time=state_change_timeout, interval="3 seconds", invert=1) if state_mod.OBMC_STATES_VERSION == 0: cmd_buf = [ "Create Dictionary", "power=${0}", "bmc=HOST_POWERED_OFF", "boot_progress=Off" ] else: # TODO: Add back boot_progress when ipmi is enabled on Witherspoon. cmd_buf = [ "Create Dictionary", "chassis=Off", "bmc=Ready", # "boot_progress=Off", "host=Off" ] grp.rdpissuing_keyword(cmd_buf) final_state = BuiltIn().run_keyword(*cmd_buf) final_state = state_mod.anchor_state(final_state) grp.rprintn() power_off_timeout = BuiltIn().get_variable_value("${POWER_OFF_TIMEOUT}", default="2 mins") state_mod.wait_state(final_state, wait_time=power_off_timeout, interval="3 seconds")
def my_get_state(): r""" Get the system state plus a little bit of wrapping. """ global state req_states = ['epoch_seconds'] + st.default_req_states gp.qprint_timen("Getting system state.") if test_mode: state['epoch_seconds'] = int(time.time()) else: state = st.get_state(req_states=req_states, quiet=quiet) gp.qprint_var(state)
def get_id(message): logger.info("command create flavor", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) if state.check_admins_id(message.from_user.id): st = state.get_state(message.from_user.id) if st == config.States.S_start.value or st is False: send_large_msg(message.chat.id, f"get info about flavor, for exemple: i43,2,16") state.set_state(message.from_user.id, config.States.S_flavor_create.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active state /cancel") else: logger.error("error in get_id") else: bot.send_message(message.chat.id, "Access denied, if you need access /access") logger.warning(f"Access denied {message.from_user.id}", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}})
def cmd_hard_reboot_vm(message): logger.info("command reboot server", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) if state.check_admins_id(message.from_user.id): # Check access st = state.get_state(message.from_user.id) if st == config.States.S_start.value or st is False: bot.send_message(message.chat.id, "Ok, i do it, give my server ID") state.set_state(message.from_user.id, config.States.S_server_retart.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active command /cancel") else: logger.error("error in cmd_show_vm") else: bot.send_message(message.chat.id, "Access denied, if you need access /access") logger.warning(f"Access denied {message.from_user.id}", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}})
def cmd_server(message): logger.info("command server action", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) if state.check_admins_id(message.from_user.id): # Check access st = state.get_state(message.from_user.id) if st == config.States.S_start.value or st not in locals(): bot.send_message(message.chat.id, "Send me server ID") state.set_state(message.from_user.id, config.States.S_server.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active command /cancel") else: logger.error("error in cmd_server") else: bot.send_message(message.chat.id, "Access denied, if you need access /access") logger.warning(f"Access denied {message.from_user.id}", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}})
def cmd_live_migrate(message): if state.check_admins_id(message.from_user.id): # Check access logger.info("command live migrate", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) st = state.get_state(message.from_user.id) if st == config.States.S_start.value or st is False: bot.send_message(message.chat.id, "Ok, i show it, give my ID VM") state.set_state(message.from_user.id, config.States.S_live_migrate.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active command /cancel") else: logger.error("error in cmd_live_migrate") else: bot.send_message(message.chat.id, "Access denied, if you need access /access") logger.warning(f"Access denied {message.from_user.id}", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}})
def get_id(message): logger.info("command show tenant id", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) if state.check_admins_id(message.from_user.id): st = state.get_state(message.from_user.id) if st == config.States.S_start.value or st is False: bot.send_message(message.chat.id, "Ok, send my `tenant/project name`", parse_mode="Markdown") state.set_state(message.from_user.id, config.States.S_get_tenant_id.value) elif not st == config.States.S_start.value: bot.send_message(message.chat.id, "Complete previous action or reset active state /cancel") else: logger.error("error in get_id") else: bot.send_message(message.chat.id, "Access denied, if you need access /access") logger.warning(f"Access denied {message.from_user.id}", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}})
def bmc_power_off(): r""" Power the Open BMC machine off and monitor status to verify. """ grp.rprint_timen("Refreshing state data.") state = state_mod.get_state() grp.rprint_var(state) match_state = state_mod.anchor_state(state) grp.rprintn() cmd_buf = ["Initiate Power Off"] grp.rpissuing_keyword(cmd_buf) power = BuiltIn().run_keyword(*cmd_buf) state_change_timeout = BuiltIn().get_variable_value( "${STATE_CHANGE_TIMEOUT}", default="1 min") # Wait for the state to change in any way. state_mod.wait_state(match_state, wait_time=state_change_timeout, interval="3 seconds", invert=1) if state_mod.OBMC_STATES_VERSION == 0: cmd_buf = ["Create Dictionary", "power=${0}", "bmc=HOST_POWERED_OFF", "boot_progress=Off"] else: # TODO: Add back boot_progress when ipmi is enabled on Witherspoon. cmd_buf = ["Create Dictionary", "chassis=Off", "bmc=Ready", # "boot_progress=Off", "host=Off"] grp.rdpissuing_keyword(cmd_buf) final_state = BuiltIn().run_keyword(*cmd_buf) final_state = state_mod.anchor_state(final_state) grp.rprintn() power_off_timeout = BuiltIn().get_variable_value( "${POWER_OFF_TIMEOUT}", default="2 mins") state_mod.wait_state(final_state, wait_time=power_off_timeout, interval="3 seconds")
def run_all( self ): then = datetime.datetime.now() all_creds = twitter.get_all_creds() logging.debug( "RunHandler.run_all: queue up %d jobs" % len( all_creds ) ) for mm_twittercreds in all_creds: bot_state = state.get_state( mm_twittercreds ) bot_settings = settings.get_settings( mm_twittercreds ) lastrun = bot_state.last_run do_run = False if lastrun is None: do_run = True else: nextrun = lastrun + datetime.timedelta( hours=bot_settings.tweet_frequency ) if nextrun > then: logging.debug( "-> %s not due yet (due at %s)" % (mm_twittercreds.screen_name,nextrun) ) else: do_run = True if do_run: url = "/%s/run" % mm_twittercreds.screen_name logging.debug( "-> queue up job: %s" % url ) taskqueue.add( url=url )
def post_state(): msg = flask.request.get_json() state = get_state(parse_dt(msg['time'])) return flask.jsonify(state)
import time from state import get_state from threat_space_search import tss_board, win_variations, animate_variation from board import point_to_algebraic from consts import BLACK # state = get_state(["a1", "a2", "a3", "a13", "a14", "a15", "b1", "b15", "c1", "c15", # "f14", "g13", "i9", "i10", "m1", "m15", "n1", "n15", "o1", "o2", # "o3", "o13", "o14", "o15"], # ["i6", "i13", "j10"], # BLACK, # False) state = get_state( ["f5", "g5", "h5", "g6", "g7", "h7", "i7", "h8", "h9", "g9", "i9"], ["g4", "e5", "f6", "h6", "j6", "f7", "j7", "f8", "g8", "i8", "f9"], BLACK, True) # state = get_state(["g10", "h8", "i7", "j7", "j9"], # ["g7", "g8", "g9", "i9", "k8"], # BLACK, # True) # state = get_state(["f6", "h6", "g7", "h7", "h8", "g11"], # ["e5", "h5", "g6", "l6", "f7", "g8"], # BLACK, # True) # state = get_state(["j5", "j6", "i10", "i11"], # [], # BLACK,
######################################################################################################################## @dataclass class MyState: flag_todo: bool flag_rerunMap: bool flag_rareComplete: bool def setup() -> MyState: return MyState(flag_todo=False, flag_rerunMap=False, flag_rareComplete=False) state = get_state(setup) ######################################################################################################################## def button_resetAllStates(k, place): if place.button("reset", key=k): reset_allStates() rerun() ######################################################################################################################## def reset_allStates(): state.flag_todo = False state.flag_rerunMap = False state.flag_rareComplete = False
def run( creds, force_tweet=False, debug=False ): if not debug: try: debug = config.DEBUG_MODE except AttributeError: pass if debug: force_tweet = True logging.debug( "brains.run(), force_tweet is %s, debug is %s" % (force_tweet, debug) ) then = datetime.datetime.now() bot_settings = settings.get_settings( creds ) bot_state = state.get_state( creds ) bot_state.last_run = then bot_state.put() deadline = then + TIME_LIMIT learning_style = bot_settings.learning_style api = twitter.get_api( creds ) statuses_digested = 0 namespace_manager.set_namespace( creds.screen_name ) logging.debug( "brains.run(): learning_style is: %s" % learning_style ) worker = verbivorejr.VerbivoreWorker( api, bot_settings ) worker.deadline = deadline if learning_style == constants.learning_style_oneuser: # learn from one user guru_name = bot_settings.learning_guru guru = twitter.get_user( screen_name=guru_name ) statuses_digested = worker.digest_user( guru ) elif learning_style == constants.learning_style_following: guru_ids = api.friends_ids( stringify_ids=True ) statuses_digested = worker.digest_ids( guru_ids ) elif learning_style == constants.learning_style_followers: guru_ids = api.followers_ids( stringify_ids=True ) statuses_digested = worker.digest_ids( guru_ids ) worker.put() logging.debug( "brains.run(): digested %d new statuses" % statuses_digested ) # only continue if chance is met if bot_settings.tweet_chance < random.random() and force_tweet is False: logging.debug( "brains.run(): didn't meet tweet_chance of %2.1f" % bot_settings.tweet_chance ) return do_tweet = False if force_tweet: logging.debug( "brains.run(): force_tweet is set" ) do_tweet = True elif bot_settings.locquacity_onschedule: logging.debug( "brains.run(): will tweet on schedule" ) do_tweet = True elif bot_settings.locquacity_speakonnew and statuses_digested > 0 : logging.debug( "brains.run(): locquacity_speakonnew, statuses_digested: %s" % statuses_digested ) do_tweet = True # check deadline, defer tweeting if necessary if datetime.datetime.now() >= deadline: logging.debug( "brains.run(): aborted after put()'ing worker, deadline is looming." ) taskqueue.add( url="/%s/run" % api.me().screen_name ) return queen = verbivorejr.VerbivoreQueen() queen.deadline = deadline if do_tweet: tweet = None safety = 10 while tweet is None and safety > 0: tweet = queen.secrete( 130 ) safety = safety - 1 if tweet is not None: tweet = verbivorejr.uc_first( tweet ) post_tweet( api, tweet, debug=debug ) replied_userids = [] if bot_settings.locquacity_reply: last_replied_id = bot_state.last_replied_id logging.debug( "brains.run(): last_replied_id is %s" % last_replied_id ) mentions = api.mentions( since_id=last_replied_id ) logging.debug( "-> %d mentions" % len(mentions) ) my_name = "@%s" % creds.screen_name last_timestamp = None for mention in mentions: if datetime.datetime.now() >= deadline: break # only reply when we've been directly addressed #if mention.text[:len(my_name)] != my_name: # break logging.debug( "-> reply to %s" % mention.author.screen_name ) reply = "@%s" % mention.author.screen_name tweet = None safety = 5 while tweet is None and safety > 0: logging.debug( "--> generate reply, safety=%d" % safety ) if datetime.datetime.now() >= deadline: break tweet = queen.secrete_reply( mention.text, 130 - len(reply) ) safety = safety -1 if tweet is not None: reply = "%s %s" % (reply, tweet) post_tweet( api, reply, in_reply_to_status_id=mention.id, debug=debug ) replied_userids.append( mention.author.id ) this_timestamp = mention.created_at if last_timestamp is None or this_timestamp > last_timestamp: last_replied_id = mention.id_str last_timestamp = this_timestamp bot_state.last_replied_id = last_replied_id bot_state.put() if bot_settings.locquacity_greetnew: if datetime.datetime.now() >= deadline: logging.debug( "brains.run(): aborted before greeting new followers, deadline is looming." ) return new_follower_ids = None stored_follower_ids = creds.follower_ids api_follower_ids = api.followers_ids() if stored_follower_ids is None: new_follower_ids = api_follower_ids else: new_follower_ids = [] for api_follower_id in api_follower_ids: if api_follower_id not in stored_follower_ids: new_follower_ids.append( api_follower_id ) if new_follower_ids is not None and len(new_follower_ids) > 0: logging.debug( "brains.run(): new_follower_ids: %s" % new_follower_ids ) for new_follower_id in new_follower_ids: if new_follower_id not in replied_userids: tw_user = api.get_user( user_id=new_follower_id ) screen_name = tw_user.screen_name safety = 5 greeting = None while greeting is None and safety > 0: greeting = queen.secrete_greeting( screen_name, 130 ) if greeting is not None: post_tweet( api, greeting, debug=debug ) else: logging.debug( "brains.run(): no new followers" ) creds.follower_ids = api_follower_ids creds.put() now = datetime.datetime.now() elapsed = now - then logging.debug( "brains.run(): completed in %d seconds" % elapsed.seconds )
def ffdc(ffdc_dir_path=None, ffdc_prefix=None, ffdc_function_list=""): r""" Gather First Failure Data Capture (FFDC). This includes: - Set global FFDC_TIME. - Create FFDC work space directory. - Write test info details. - Call BMC methods to write/collect FFDC data. Description of arguments: ffdc_dir_path The dir path where FFDC data should be put. ffdc_prefix The prefix to be given to each FFDC file name generated. ffdc_function_list A colon-delimited list of all the types of FFDC data you wish to have collected. A blank value means that all possible kinds of FFDC are to be collected. See FFDC_METHOD_CALL object in lib/openbmc_ffdc_list.py for possible choices. """ ffdc_file_list = [] # Check if Ping and SSH connection is alive OPENBMC_HOST = BuiltIn().get_variable_value("${OPENBMC_HOST}") state = st.get_state(req_states=['ping', 'uptime']) gp.qprint_var(state) if not int(state['ping']): gp.print_error("BMC is not ping-able. Terminating FFDC collection.\n") return ffdc_file_list if state['uptime'] == "": gp.print_error("BMC is not communicating. Terminating FFDC" + " collection.\n") return ffdc_file_list gp.qprint_timen("Collecting FFDC.") # Get default values for arguments. ffdc_dir_path, ffdc_prefix = set_ffdc_defaults(ffdc_dir_path, ffdc_prefix) gp.qprint_var(ffdc_dir_path) gp.qprint_var(ffdc_prefix) # LOG_PREFIX is used by subordinate functions. LOG_PREFIX = ffdc_dir_path + ffdc_prefix BuiltIn().set_global_variable("${LOG_PREFIX}", LOG_PREFIX) cmd_buf = ["Create Directory", ffdc_dir_path] grp.rqpissuing_keyword(cmd_buf) status, output = BuiltIn().run_keyword_and_ignore_error(*cmd_buf) if status != "PASS": error_message = grp.sprint_error_report("Create Directory failed" + " with the following" + " error:\n" + output) BuiltIn().fail(error_message) # FFDC_FILE_PATH is used by Header Message. FFDC_FILE_PATH = ffdc_dir_path + ffdc_prefix + "BMC_general.txt" BuiltIn().set_global_variable("${FFDC_FILE_PATH}", FFDC_FILE_PATH) status, ffdc_file_list = grk.run_key("Header Message") status, ffdc_file_sub_list = \ grk.run_key_u("Call FFDC Methods ffdc_function_list=" + ffdc_function_list) # Combine lists, remove duplicates and sort. ffdc_file_list = sorted(set(ffdc_file_list + ffdc_file_sub_list)) gp.qprint_timen("Finished collecting FFDC.") return ffdc_file_list
def ffdc(ffdc_dir_path=None, ffdc_prefix=None, ffdc_function_list=""): r""" Gather First Failure Data Capture (FFDC). This includes: - Set global FFDC_TIME. - Create FFDC work space directory. - Write test info details. - Call BMC methods to write/collect FFDC data. Description of arguments: ffdc_dir_path The dir path where FFDC data should be put. ffdc_prefix The prefix to be given to each FFDC file name generated. ffdc_function_list A colon-delimited list of all the types of FFDC data you wish to have collected. A blank value means that all possible kinds of FFDC are to be collected. See FFDC_METHOD_CALL object in lib/openbmc_ffdc_list.py for possible choices. """ ffdc_file_list = [] # Check if Ping and SSH connection is alive OPENBMC_HOST = BuiltIn().get_variable_value("${OPENBMC_HOST}") state = st.get_state(req_states=['ping', 'uptime', 'rest']) gp.qprint_var(state) if not int(state['ping']): gp.print_error("BMC is not ping-able. Terminating FFDC collection.\n") return ffdc_file_list if not int(state['rest']): gp.print_error("REST commands to the BMC are failing." + " Terminating FFDC collection.\n") return ffdc_file_list if state['uptime'] == "": gp.print_error("BMC is not communicating via ssh. Terminating FFDC" + " collection.\n") return ffdc_file_list gp.qprint_timen("Collecting FFDC.") # Get default values for arguments. ffdc_dir_path, ffdc_prefix = set_ffdc_defaults(ffdc_dir_path, ffdc_prefix) gp.qprint_var(ffdc_dir_path) gp.qprint_var(ffdc_prefix) # LOG_PREFIX is used by subordinate functions. LOG_PREFIX = ffdc_dir_path + ffdc_prefix BuiltIn().set_global_variable("${LOG_PREFIX}", LOG_PREFIX) cmd_buf = ["Create Directory", ffdc_dir_path] gp.qprint_issuing(cmd_buf) status, output = BuiltIn().run_keyword_and_ignore_error(*cmd_buf) if status != "PASS": error_message = gp.sprint_error_report("Create Directory failed" + " with the following" + " error:\n" + output) BuiltIn().fail(error_message) # FFDC_FILE_PATH is used by Header Message. FFDC_FILE_PATH = ffdc_dir_path + ffdc_prefix + "BMC_general.txt" BuiltIn().set_global_variable("${FFDC_FILE_PATH}", FFDC_FILE_PATH) status, ffdc_file_list = grk.run_key_u("Header Message") status, ffdc_file_sub_list = \ grk.run_key_u("Call FFDC Methods ffdc_function_list=" + ffdc_function_list) # Combine lists, remove duplicates and sort. ffdc_file_list = sorted(set(ffdc_file_list + ffdc_file_sub_list)) gp.qprint_timen("Finished collecting FFDC.") return ffdc_file_list
def cmd_get_type_cod(message): logger.info("command show info about tenant", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) st = state.get_state(message.from_user.id)
def __init__(self): self.state = state.get_state()
def update_state(n=state['step'], force=False): if n != state['step'] or force: state['step'] = n snapshot, modules = sta.get_state(n) sbx.update_state_boxes(snapshot, modules)
def discover_event_difference(): highscore_epoch, lowscore_epoch = None, None highscorenum, lowscorenum = 0, 0 for i in range(1, 60): try: data_score = get_score(i)[0] data_state = get_state(i, 3) data_eeg = get_epoch_eeg(i).drop(["condition"], axis=1) data_raw_eeg = get_raw_eeg(i) if not (len(data_score) == len(data_eeg["epoch"].value_counts()) and len(data_score) == len( data_state[data_state["markerText"] == "ShotOps"])): continue print("yes") events, event_id = mne.events_from_annotations(data_raw_eeg) #print(events) epochs = mne.Epochs(data_raw_eeg, events, event_id, tmin=-3, tmax=0, event_repeated='drop', preload=True) first, second = get_score(i + 1) rest_eeg = epochs["s1001"][0] total_shot_num = len(first) + len(second) first_shoot_eeg = epochs["s1002"][-total_shot_num:-len(second)] for j in range(len(data_score)): if data_score[j] > 9: if highscore_epoch == None: highscore_epoch = first_shoot_eeg["s1002"][j] else: highscore_epoch = mne.concatenate_epochs( [highscore_epoch, first_shoot_eeg["s1002"][j]]) highscorenum += 1 if data_score[j] < 8: if lowscore_epoch == None: lowscore_epoch = first_shoot_eeg["s1002"][j] else: lowscore_epoch = mne.concatenate_epochs( [lowscore_epoch, first_shoot_eeg["s1002"][j]]) lowscorenum += 1 print(highscorenum) print(lowscorenum) #fig1=highscore_epoch.plot_psd_topomap(show=False,normalize=True) #fig2=lowscore_epoch.plot_psd_topomap(show=False,normalize=True) #fig1.savefig(r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\high_score_3s_test\high_score{}.jpg".format(i)) #fig2.savefig(r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\low_score_3s_test\low_score{}.jpg".format(i)) except Exception as e: traceback.print_exc() freq_low = [0, 4, 8, 12, 30] freq_high = [4, 8, 12, 30, 45] for j in range(len(freq_low)): highscore_epoch.load_data().filter(l_freq=freq_low[j], h_freq=freq_high[j]) highscoredata = highscore_epoch.get_data() corr_matrix = mne.connectivity.envelope_correlation(highscoredata, combine="mean") plt.imshow(corr_matrix) plt.colorbar() plt.title("highscore_({}Hz-{}Hz)".format(freq_low[j], freq_high[j])) plt.savefig( r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\diff\corr\high_score\high_score({}Hz-{}Hz).jpg" .format(freq_low[j], freq_high[j])) plt.close() lowscore_epoch.load_data().filter(l_freq=freq_low[j], h_freq=freq_high[j]) lowscoredata = lowscore_epoch.get_data() corr_matrix = mne.connectivity.envelope_correlation(lowscoredata, combine="mean") plt.imshow(corr_matrix) plt.colorbar() plt.title("lowscore_({}Hz-{}Hz)".format(freq_low[j], freq_high[j])) plt.savefig( r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\diff\corr\low_score\low_score({}Hz-{}Hz).jpg" .format(freq_low[j], freq_high[j])) plt.close() #fig1.savefig(r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\diff\event\high_score.jpg") #fig2.savefig(r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\diff\event\low_score.jpg") print(highscorenum) print(lowscorenum)
#!/usr/bin/env python3 from yeelight import RGBTransition, Flow from bulb_ip import B from state import get_state color = int(get_state(props=['rgb'])['rgb']) b = color & 0xff color >>= 8 g = color & 0xff color >>= 8 r = color & 0xff pink = RGBTransition(0xff, 0x16, 0x94, 500, 100) pink = RGBTransition(0xff, 0x00, 0xff, 500, 100) current = RGBTransition(r, g, b, 500, 100) transitions = [pink if i % 2 == 0 else current for i in range(9)] flow = Flow(count=1, transitions=transitions) B.start_flow(flow)
self.lists['train'] = os.path.join(self.list_dir,'train_1_of_1.txt') self.lists['valid'] = os.path.join(self.list_dir,'valid_1_of_1.txt') self.lists['test'] = os.path.join(self.list_dir,'test_1_of_1.txt') self.preprocessor = PreProcessor(self.dataset_dir) print 'Preparing train/valid/test splits' self.preprocessor.prepare_fold(self.lists['train'],self.lists['valid'],self.lists['test']) self.data = self.preprocessor.data self.targets = self.preprocessor.targets print 'Building model.' self.model = MLP(n_inputs=self.state.get('n_inputs',513),n_outputs=self.state.get('n_ouputs',10), n_hidden=self.state.get('n_hidden',[50]),activation=self.state.get('activation','sigmoid'), output_layer=self.state.get('sigmoid','sigmoid'),dropout_rates=self.state.get('dropout_rates',None)) def train(self,): print 'Starting training.' print 'Initializing train dataset.' self.batch_size = self.state.get('batch_size',20) train_set = Dataset([self.data['train']],batch_size=self.batch_size,targets=[self.targets['train']]) print 'Initializing valid dataset.' valid_set = Dataset([self.data['valid']],batch_size=self.batch_size,targets=[self.targets['valid']]) self.optimizer = SGD_Optimizer(self.model.params,[self.model.x,self.model.y],[self.model.cost,self.model.acc],momentum=self.state.get('momentum',False)) lr = self.state.get('learning_rate',0.1) num_epochs = self.state.get('num_epochs',200) save = self.state.get('save',False) mom_rate = self.state.get('mom_rate',None) self.optimizer.train(train_set,valid_set,learning_rate=lr,num_epochs=num_epochs,save=save,mom_rate=mom_rate) if __name__=='__main__': state = state.get_state() test = trainer(state) test.train()
def discover_psd_difference(): highscore_epoch, lowscore_epoch = None, None highscorenum, lowscorenum = 0, 0 for i in range(1, 60): try: data_score = get_score(i)[0] data_state = get_state(i, 3) data_eeg = get_epoch_eeg(i).drop(["condition"], axis=1) data_raw_eeg = get_raw_eeg(i) if not (len(data_score) == len(data_eeg["epoch"].value_counts()) and len(data_score) == len( data_state[data_state["markerText"] == "ShotOps"])): continue print("yes") events, event_id = mne.events_from_annotations(data_raw_eeg) #print(events) epochs = mne.Epochs(data_raw_eeg, events, event_id, tmin=-3, tmax=0, event_repeated='drop', preload=True) first, second = get_score(i + 1) rest_eeg = epochs["s1001"][0] total_shot_num = len(first) + len(second) first_shoot_eeg = epochs["s1002"][-total_shot_num:-len(second)] for j in range(len(data_score)): if data_score[j] > 9: if highscore_epoch == None: highscore_epoch = first_shoot_eeg["s1002"][j] else: highscore_epoch = mne.concatenate_epochs( [highscore_epoch, first_shoot_eeg["s1002"][j]]) highscorenum += 1 if data_score[j] < 8: if lowscore_epoch == None: lowscore_epoch = first_shoot_eeg["s1002"][j] else: lowscore_epoch = mne.concatenate_epochs( [lowscore_epoch, first_shoot_eeg["s1002"][j]]) lowscorenum += 1 print(highscorenum) print(lowscorenum) fig1 = highscore_epoch.plot_psd_topomap(show=False, normalize=False, cmap="RdBu_r") fig2 = lowscore_epoch.plot_psd_topomap(show=False, normalize=False, cmap="RdBu_r") fig1.savefig( r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\high_low1\high_score{}.jpg" .format(i)) fig2.savefig( r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\high_low1\low_score{}.jpg" .format(i)) break except Exception as e: traceback.print_exc() break #fig1=highscore_epoch.plot_psd_topomap(show=False,cmap="RdBu_r",normalize=True) #fig2=lowscore_epoch.plot_psd_topomap(show=False,cmap="RdBu_r",normalize=True) #fig1.savefig(r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\high_low\high_score.jpg") #fig2.savefig(r"C:\Users\zhou\Desktop\毕业设计\mechanical\最终论文\pic\high_low\low_score.jpg") print(highscorenum) print(lowscorenum)
print 'Starting training.' print 'Initializing train dataset.' self.batch_size = self.state.get('batch_size', 20) train_set = Dataset([self.data['train']], batch_size=self.batch_size, targets=[self.targets['train']]) print 'Initializing valid dataset.' valid_set = Dataset([self.data['valid']], batch_size=self.batch_size, targets=[self.targets['valid']]) self.optimizer = SGD_Optimizer(self.model.params, [self.model.x, self.model.y], [self.model.cost, self.model.acc], momentum=self.state.get( 'momentum', False)) lr = self.state.get('learning_rate', 0.1) num_epochs = self.state.get('num_epochs', 200) save = self.state.get('save', False) mom_rate = self.state.get('mom_rate', None) self.optimizer.train(train_set, valid_set, learning_rate=lr, num_epochs=num_epochs, save=save, mom_rate=mom_rate) if __name__ == '__main__': state = state.get_state() test = trainer(state) test.train()
logger.error("error in cmd_server") else: bot.send_message(message.chat.id, "Access denied, if you need access /access") logger.warning(f"Access denied {message.from_user.id}", extra={'bot': {'chat_id': message.chat.id, 'user_id': message.from_user.id}}) ''' Wraps mach param after bot commands After we set state VM, we needed mach server ID or tenant name. Below code takes users messages, checking it and if all right to send param in opanstack.py ''' # flavor create @bot.message_handler(func=lambda message: state.get_state(message.from_user.id) == config.States.S_flavor_create.value) def flavar_param(message): if opstack.normalize_flavor_param(message.text) is not None: # send request for create requst = opstack.normalize_flavor_param(message.text) answer = opstack.flavor_create(requst[0],requst[1],requst[2]) # send answer in function for division into parts send_large_msg(message.chat.id, answer) state.set_state(message.from_user.id, config.States.S_start.value) logger.info(f"create flavor{answer}") # Console # check state status @bot.message_handler(func=lambda message: state.get_state(message.from_user.id) == config.States.S_cmd_tv.value) def user_entering_idvm(message):