def start_game(self, board): print("Let`s play Battleship") diff = int(raw_input("Choose difficulty - 1 ship, 2 ships or 3 ships. Pls put a number: ")) while diff < 1 or diff > 3: print("Pls put correct number (between 1 and 3): "), diff = int(raw_input("")) self.fill_ships(diff) print("You have %s turns" % str(3+diff)) for turn in range(1, 3+diff): count = 0 print("Turn %s" % turn) self.print_board(board) guess_row = int(raw_input("Guess raw: ")) guess_col = int(raw_input("Guess col: ")) for ship in self.ships: if 0 > guess_row or guess_row >= len(self.board) or 0 > guess_col or guess_col >= len(self.board): print("Error: Oops, that's not even in the ocean") elif guess_row == ship.row and guess_col == ship.col and ship.status: print("You sunk my battleship") self.board[guess_row][guess_col] = "X" ship.status = False count = +1 else: print("Sorry, you missed") self.board[guess_row][guess_col] = "/" if count == diff: break if count == diff: break print()
def Matrix(): n = int(raw_input("Number of Unknowns: ")) x = eval((raw_input("Initial Guess for Solution: "))) tol = int(raw_input("Tolerance: ")) a = [-1] * (n - abs(-1)) b = [4] * (n - abs(0)) c = [-1] * (n - abs(1)) A = np.diag(a, -1) + np.diag(b, 0) + np.diag(c, 1) B = [] if x == 0: x = np.zeros(len(A)) for i in range(len(A)): B.append(100) return A, B, x, tol
def classify_person(): result_list = ['not at all', 'in small doses', 'in large doses'] percent_tats = float( raw_input("percentage of time spent playing video games?")) ff_miles = float(raw_input("frequent flier miles earned per year?")) ice_cream = float(raw_input("liters of ice cream consumed per year?")) dating_data_mat, dating_labels = file2matrix('datingTestSet2.txt') norm_mat, ranges, min_vals = auto_norm(dating_data_mat) in_array = array([ff_miles, percent_tats, ice_cream]) classfier_result = classify0((in_array - min_vals) / ranges, norm_mat, dating_labels, 3) print("you will probably like this person: " + result_list[classfier_result - 1]) draw_data(dating_data_mat[:, 0], dating_data_mat[:, 1], dating_labels)
def classifyPerson(): resultList = ['not at all', 'in small doses', 'in large doses'] ffMiles = float(raw_input('frequent flier miles earned per year')) percentTats = float( raw_input('percentage of time spent playing video games')) iceCream = float(raw_input('liters of ice cream consumed per year')) intX = array([ffMiles, percentTats, iceCream]) data = file2matrix('F:\pycharm_workapace\数据样本\Ch02\datingTestSet2.txt', 3) minValue, gap, dataSet = autoNorm(data[0]) labels = data[1] resultIndex = classify0((intX - minValue) / gap, dataSet, labels, 3) print(resultIndex) print("You will probably like this person: %s" % (resultList[int(resultIndex) - 1]))
def binary_search(needle: int, array: list, start: int = 0, end: int = None): end = end if end else len(array) length = end - start i = length // 2 + start print(start, end, i, array[start:end], array[i]) raw_input('Press enter') if length == 1: if needle == array[i]: return i else: return False if needle > array[i]: return binary_search(needle, array, i + 1, end) else: return binary_search(needle, array, start, i)
def obtener_numero_negocio(lista_negocios): """Devuelve a que posicion en la lista de Bicicleterias se quiere acceder recibe una lista de tuplas de bicicleterias (nombre, direccion) """ if len(lista_negocios) == 0: print("No hay bicileterias registradas en esta comuna") return None numero_negocio = None input_invalido = True while input_invalido: print() for i in range(0, len(lista_negocios)): print( str(i + 1) + (3 - len(str(i + 1))) * " " + lista_negocios[i][0] + (40 - len(lista_negocios[i][0])) * " " + lista_negocios[i][1]) print() try: numero_negocio = raw_input("Inserte número de bicicleteria :\n") input_invalido = (1 > int(numero_negocio) ) or int(numero_negocio) > (len(lista_negocios)) except: pass finally: if input_invalido: print("Ingrese un numero entre: 1 y " + str(len(lista_negocios))) return numero_negocio
def SOR(): print("SOR Iteration Method") A, B, x, tol = Matrix() w = float(raw_input("Omega Values: ")) Upper = np.triu(A,1) Lower = np.tril(A,-1) Middle = np.diagflat(np.diag(A)) DiagInverse = np.linalg.inv(Middle + Lower * w) iters = 0 Max_Iters = 1000 wB = [] wU = [] for i in B: wB.append(w * i) for i in Upper: wU.append(w * i) for i in range(Max_Iters): iters += 1 x_prev = x x = np.dot(DiagInverse, wB - np.dot((wU + (w - 1) * Middle), x)) error = np.linalg.norm(x - x_prev) / np.linalg.norm(x) if error < 10**tol: print("Solution Vector: ", x) print("Number of Iterations: ", iters) return ""
def askAboutFileOpening(self): print("Do you want to open just the first file or all files with that word?") ans = False chosenAnswer = 0 while ans == False: chosenAnswer = raw_input("Write 1 for just first file, 2 for all files: ") try: chosenAnswer = int(chosenAnswer) except ValueError: print("Answer was not a number") # first check if answer is integer then check the other answer possibilities if(isinstance( chosenAnswer, int ) == True): if(chosenAnswer == 1): # open notepad with the file ans = True osCommandString = "notepad.exe " + Menus.pathsToFilesWithFoundWords[0] os.system(osCommandString) elif(chosenAnswer == 2): # open all files with notepad ans = True for path in Menus.pathsToFilesWithFoundWords: osCommandString = "notepad.exe " + path os.system(osCommandString) elif(chosenAnswer > 2 or chosenAnswer < 1): print("Answer was not 1 or 2") else: print("Answer was not 1 or 2")
def update_details(self, roll_no): try: student_name = raw_input("Update the student Name") # print student_name # print roll_no self.update_student_name(roll_no, "\"" + student_name + "\"") except Exception as e: print(e)
def xreplace(): s1 = raw_input("Enter s1: ") s2 = raw_input("Enter s2: ") s3 = raw_input("Enter s3: ") # s1 = 'here you haNNve soNNme text' # s2 = 'NN' # s3 = '' is_present = True while is_present: indexes = find_index(s1, s2) if indexes is not None: start_index = indexes[0] end_index = indexes[1] s1 = s1[:start_index] + s3 + s1[end_index:] else: is_present = False print('Result is: ' + s1)
def fib(): n = int(raw_input('define n(n=>1) = ')) l = [] if (n < 1): print('error number!') a, b = 0, 1 for i in range(n): l.append(a) a, b = b, a + b return l
def login(): url = 'http://www.zhihu.com' loginURL = "http://www.zhihu.com/login/email" headers = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:41.0) Gecko/20100101 Firefox/41.0', "Referer": "http://www.zhihu.com/", 'Host': 'www.zhihu.com', } data = { "email": "*****@*****.**", "password": "******", "rememberme": "true", } global s s = requests.session() global xsrf if os.path.exists('cookiefile'): with open('cookiefile') as f: cookie = json.load(f) s.cookies.update(cookie) req1 = s.get(url, headers=headers) soup = BeautifulSoup(req1.text, "html.parser") xsrf = soup.find("input", { "name": "_xsrf", "type": "hidden" }).get("value") # 建立一个zhihu.html文件,用于验证是否登陆成功 with open('zhihu.html', 'w') as f: f.write(req1.content) else: req = s.get(url, headers=headers) print(req) soup = BeautifulSoup(req.text, "html.parser") xsrf = soup.find("input", { "name": "_xsrf", "type": "hidden" }).get("value") data["_xsrf"] = xsrf timestamp = int(time.time() * 1000) captchaURL = 'http://www.zhihu.com/captcha.gif?=' + str(timestamp) print(captchaURL) with open('zhihucaptcha.gif', 'wb') as f: captchaREQ = s.get(captchaURL, headers=headers) f.write(captchaREQ.content) loginCaptcha = raw_input('input captcha:\n').strip() data["captcha"] = loginCaptcha loginREQ = s.post(loginURL, headers=headers, data=data)
def repetir(): """1 para realizar otra busqueda o 2 para cerrar""" while True: try: respuesta = int( raw_input( " \n 1 Para realizar otra busqueda \n 2 Para salir \n")) if respuesta == 1 or respuesta == 2: return respuesta except: pass
def main(): email = raw_input("Please enter your uyan login email:") password = raw_input("Please enter your uyan password:"******"parent_uname"] del c_comment["parent_uname"] for p_comment in comments: if p_comment['uname'] == parent_uname and c_comment["url"] == p_comment["url"]: if not 'child' in p_comment.keys(): p_comment['child'] = [c_comment] else: p_comment['child'].append(c_comment) break print("Your comments will saved to comments.json.") demjson.encode_to_file("comments.json", comments, 'utf-8', True, indent_amount=2, compactly=False) print("Finish !!!! Now you can open comments.json to see the comments")
def classifyPerson(): #输出结果 resultList = ['不喜欢', '一般喜欢', '特别喜欢'] #特征用户的输入 precentTats = float(raw_input("玩视频游戏所耗时间百分比:")) ffMiles = float(raw_input("每年获得的飞行常客里程数:")) iceCream = float(raw_input("每周消费的冰淇淋公升数:")) filename = "DataTestSet2.txt" #打开并处理数据 datingDataMat, datingLabels = filematrix(filename) #训练集的归一化 normMat, ranges, minVals = autoNorm(datingDataMat) #生成测试集 inArr = np.array([ffMiles, precentTats, iceCream]) #把测试集归一化 norminArr = (inArr - minVals) / ranges #返回分类结果 classifierResult = classify0(norminArr, normMat, datingLabels, 3) #打印输出结果 print("海伦可能%s这个人" % (resultList[classifierResult - 1]))
def get_user_move(board): ticTacToeBoard = matrix.array(board) #print() player_X = raw_input("Give value for X move %d to %d" % (0, ticTacToeBoard.shape[0]-1)) player_Y = raw_input("Give value for Y move %d to %d" % (0, ticTacToeBoard.shape[0]-1)) player_move_X = int(player_X) player_move_Y = int(player_Y) oneMoreTime = True for i in range(0, ticTacToeBoard.shape[0]): for j in range(0, ticTacToeBoard.shape[0]): if (i==player_move_X): if (j == player_move_Y): #print("IN") if (ticTacToeBoard[i][j] == "_"): ticTacToeBoard[i][j] = "O" oneMoreTime = False if(oneMoreTime == True): print("Not empty space!!! One more time:") get_user_move(ticTacToeBoard) return ticTacToeBoard
def run(): stop_words = set(stopwords.words('english')) lmtzr = WordNetLemmatizer() query = raw_input('Enter your query:') query_tokenize = word_tokenize(query) query_filtered = [] for w in query_tokenize: # and not re.match("^[a-zA-Z0-9]*$", w) if w not in stop_words and len(w) > 1: word_lemm = lmtzr.lemmatize(w) query_filtered.append(word_lemm) return query_filtered
def goThroughFilesInFolder(self,word): searching = OpenAndSearch() # get all folder paths folderPaths = OpenAndSearch().getAllFolderPaths() # for each folder path in folderpaths get all files in folder # then open the files one by one and check for the word for fPath in folderPaths: onlyfiles = [f for f in listdir(fPath) if isfile(join(fPath, f))] for file in onlyfiles: path = fPath+"\\"+file fileToBeSearched = searching.openFile(fPath+"\\"+file) #check if type has text in it, if it does it can be searched mimeTypeTextTest = mimetypes.guess_type(path)[0] # check first if mimetype return value is text so it can be compared to "text" if(isinstance(mimeTypeTextTest, str)): if("text" in mimeTypeTextTest): if(searching.searchFile(word,fileToBeSearched) == True): Menus.pathsToFilesWithFoundWords.append(path) else: pass else: pass searching.closeFile(fileToBeSearched) # close file if not Menus.pathsToFilesWithFoundWords: # list is empty, no words were found print("That word was not found in any of the files.") raw_input("Press Enter to exit.") else: print("%d files have the word you are looking for." % Menus.pathsToFilesWithFoundWords.__len__()) self.askAboutFileOpening()
def obtener_numero_comuna(): """Devuelve a que número de comuna se quiere acceder""" comuna = None input_invalido = True while input_invalido: try: comuna = " " + raw_input("Inserte número de Comuna :\n") input_invalido = not (0 < int(comuna) < 16) except: pass finally: if input_invalido: print("Debe ingresar un numero entre: 1 y 15") return comuna
def mainMenu(self): answer = False # while answer is not true (ex. no answer was given) get word from user while answer == False: wordToSearch = raw_input("Please write the word you want to search: ") if wordToSearch.isspace() == True: answer = False print("The word seems to be empty. Did you actually write something?") else: answer = True self.goThroughFilesInFolder(wordToSearch)
def selectMenu(): while True: viewMenu() try: cmd = str(raw_input("Input Command: ")) print("cmd: ", cmd) if (cmd.find("1") == 0): VowifiRegi().vowifiScript() elif (cmd.find("2") == 0): # print("[2] Vowifi Regi + MMS send 구현 안됨\n") VowifiMMS().vowifiScript() elif (cmd.find("3") == 0): # print("[3] Vowifi Regi + Call 구현 안됨\n") VowifiCall().vowifiScript() elif (cmd.find("4") == 0): print("[4] HO (W to L) 구현 안됨\n") elif (cmd.find("5") == 0): print("[5] HO (L to W) 구현 안됨\n") elif (cmd.find("6") == 0): print("[6] HO (L to W) in Call 구현 안됨\n") elif (cmd.find("7") == 0): print("[7] HO (L to W) in Call 구현 안됨\n") elif (cmd.find("8") == 0): print("[8] VOWIFI ALL Case 구현 안됨\n") VowifiRegi().vowifiScript() VowifiMMS().vowifiScript() VowifiCall().vowifiScript() elif (cmd.find("0") == 0): print("[0] Test END\n") break else: print("입력 규칙을 벗어나셨습니다\n") except ValueError: print("입력 규칙을 벗어나셨습니다\n") pass
from Tools.scripts.treesync import raw_input __author__ = 'aseem' #This program generates a Pascal Triangle import math; def combination(n, r): return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r))); def for_test(x,y): for y in range(x): return combination(x,y); def pascals_triangle(rows): result=[]; for count in range(rows): row = []; for element in range(count + 1): row.append(combination(count,element)); result.append(row); return result; num =int(raw_input("\n Enter number of rows till you want Pascal Triangle: ")); for row in pascals_triangle(num): print(row)
#!/bin/python from Tools.scripts.treesync import raw_input s, t = raw_input().strip().split(' ') s, t = [int(s), int(t)] a, b = raw_input().strip().split(' ') a, b = [int(a), int(b)] m, n = raw_input().strip().split(' ') m, n = [int(m), int(n)] apple = map(int, raw_input().strip().split(' ')) orange = map(int, raw_input().strip().split(' ')) appleDistance = [] orangeDistance = [] for i in apple: appleDistance.append(a + i) for j in orange: orangeDistance.append(b + j) count1 = 0 for i in appleDistance: if s <= i <= t: count1 += 1 print(count1) count1 = 0 for i in orangeDistance: if s <= i <= t: count1 += 1 print(count1)
from Tools.scripts.treesync import raw_input str = raw_input("Enter your input: ") print("Received input is : ", str)
if len(user.memory) >= 255: self.__send(True, _snd_nick, "у меня память кончается, не могу больше запоминать текст", _public) user.action = None def action_stop(): del user.memory[-1] self.__send(True, snd_nick, "ок", public) user.action = UpdAction(action, action_stop, "store") return True def __end_action(self, tags: list, bot_nick: str, snd_nick: str, dst_nicks: list, public: bool, text: str) -> bool: if bot_nick not in dst_nicks: return False user = self.__users[snd_nick] if user.action.stopped(): self.__send(True, snd_nick, "ты мне не давал заданий", public) return False user.action.stop() return True if __name__ == "__main__": bot = IrcBot(3, "irc.esper.net", 6667, "#cc.ru", "PythonBot", "", {"Seryoga"}) bot.connect() connected = True while True: inp = raw_input("") if inp == "close\n" or not bot.connected(): bot.disconnect() break
import logging from Tools.scripts.treesync import raw_input from custom_components.wireless_hub import WirelessHub logging.basicConfig(level=logging.DEBUG) #wireless_sender = WirelessHub("192.168.31.190", 1319, 7000, "iyk_008434ae") wireless_sender = WirelessHub("192.168.31.107", 1319, 7000, "iyk_0065c772") wireless_sender.listen() # wireless_hub.send( # '{"msg_type":"set","msg_id":7,"device_id":"iyk_008434ae","services":{"rf":{"type":0,"value":"48a2a3db"}}}') wireless_sender.learn_rf() #wireless_sender.send_ir("g463g2284d3e4ec94d3e4ec94dc94dca4e3d4dca4ec94dc94d3e4dc94d3e4d3d4dca4d3d4dca4d3d4dca4a414dca4a4149424a414d3e4dc949424dc94d3e4dc94dc94dca4dh2d1g463g2284e3d4dca4e3d4dc94dca4dc94d3e4dc949cd4ec94d3d4acc4a414a4149cd4a4049cd494249cd49424acd49424a414a4149414acd49414acc4a414acc4acd49cd4ah2d4g463g2294d3e4ec949414acd49cd49ce4a4149ce4acd49cd4a4149cd494249414acd49414acc4a414acc4a4149ce4a4149424a414a4149cd4e3d49cd494249cd49ce4acd4") name = raw_input('please enter your name: ')
shutil.rmtree(test_dest, ignore_errors=True) os.makedirs(test_dest) shutil.rmtree(signal_dest, ignore_errors=True) os.makedirs(signal_dest) # remove only batch files in streaming unlabelled folder # batch data's filenames are in this format: dddddddd_dd.csv where d is a digit for files in glob.glob(unlabelled_dest + ('[0-9]' * 8) + '_' + ('[0-9]' * 2) + '.csv'): os.remove(files) print('Deleted existing files') ## streaming options # stream batch train/test data or not if python_version == 3: inputtest = input("Do you want to update the model? (y/n) : \n") else: inputtest = raw_input("Do you want to update the model? (y/n) : \n") train = inputtest == 'Y' or inputtest == 'y' # stream batch unlabelled data or not if python_version == 3: inputtest = input("Do you want to stream batch unlabelled data? (y/n) : \n") else: inputtest = raw_input("Do you want to stream batch unlabelled data? (y/n) : \n") unlabel = inputtest == 'Y' or inputtest == 'y' # stream realtime data or not if python_version == 3: inputtest = input("Do you want to stream realtime tweets? (y/n) : \n") else: inputtest = raw_input("Do you want to stream realtime tweets? (y/n) : \n") realtime = inputtest == 'Y' or inputtest == 'y'
import os import subprocess from Tools.scripts.treesync import raw_input url = "http://www.twitch.tv/" + raw_input("Enter stream: ") cmd = 'livestreamer ' + url + 'best' subprocess.call(['runas', '/user:Administrator', cmd])
#TCP 6 UDP 17 #if not UDP, SET udp size AS 0 if txt_array[2] == '6': output.writelines(txt_line) logger.info("Finish TCP filter ") output.close() #################################################### ##########The main interactive of the Data Process #################################################### show_help_info() exitFlag = 0 while 1: #获得用户输入 userInput = raw_input("Please Enter your Choice:") if userInput == '0': print("Scanning...") scan_input_data() print("Scanning finished...") elif userInput == '1': show_scan_result(1) process_normal_no = raw_input("Please Input which file you want to process:") print("Proceing Normal files...") normal_process(int(process_normal_no)) print("Proceing Normal files Finished") print("The DB records has: " + str(normal_db_size)) elif userInput == '2': show_scan_result(0) process_normal_no = raw_input("Please Input which file you want to process:") print("Proceing Infect files...")
from Tools.scripts.treesync import raw_input from scipy.linalg import norm # Assuming that the given matrix does not change on the diagonal and the B vector does not change, # then all that would have to be done is follow the prompts in the console and input the number of # unknowns, your initial guess, and a tolerance (For SOR you will also need a w). For the tolerance all you have # to do is input the number that you want 10**x. So if you want 10^-6, Just input -6 for tolerance. # If your guess is just the 0 vector, then you can just input 0 for guess, otherwise input the whole # guess vector in the form [x1, x2, x3, ...., xn]. The functions will return a solution vector # [x1 x2 x3 ... xn] and the number of iterations to meet the given error tolerance. I have a max # iteration set to 1000 and i used relative errors for all the iterations. print("Press 1 for Jacobi Method") print("Press 2 for Gauss-Seidel Method") print("Press 3 for SOR Method") T = int(raw_input("Choose Now: ")) """"Makes Matrix""""" def Matrix(): n = int(raw_input("Number of Unknowns: ")) x = eval((raw_input("Initial Guess for Solution: "))) tol = int(raw_input("Tolerance: ")) a = [-1] * (n - abs(-1)) b = [4] * (n - abs(0)) c = [-1] * (n - abs(1)) A = np.diag(a, -1) + np.diag(b, 0) + np.diag(c, 1) B = [] if x == 0: x = np.zeros(len(A))
from Tools.scripts.treesync import raw_input #coding=utf-8 __author__ = 'Rail' #идея в том чтобы загнать данные словарь где ключиком является логин а значением является пароль f = open('loginsANDpasswords.txt') log = raw_input('Login:\n') password = raw_input('Password:\n') d = {} for line in f: d[line.split()[0]] = line.split()[1] for i in d: if not log.replace('\n', '') in d or d[log.replace('\n', '')] != password.replace('\n',''): print('Incorrect login or password') if raw_input('Do you want to register?(type yes if you want to)\n')=='yes\n': new_login=raw_input('Enter login: \n') new_password=raw_input('Enter password:\n') rep_password=raw_input('Repeat password:\n') if new_password==rep_password: f=open('loginsANDpasswords.txt','a') f.writelines('\n'+ new_login.replace('\n','')+' '+new_password.replace('\n','')) break else: print('Welcome') break
############################################################################### # delete all rows in table, but don't drop the table or database it is in # usage: cleardb.py dbname? (tablename is implied) ############################################################################### import sys from Tools.scripts.treesync import raw_input if raw_input('Are you sure?') not in ('y', 'Y', 'yes'): sys.exit() dbname = 'peopledb' # cleardb.py if len(sys.argv) > 1: dbname = sys.argv[1] # cleardb.py testdb from loaddb import login conn, curs = login(db=dbname) curs.execute('delete from people') conn.commit() # else rows not really deleted print(curs.rowcount, 'records deleted') # conn closed by its __del__
def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) for turn in range(4): print("Turn", turn + 1) guess_row = int(raw_input("Guess Row: ")) guess_col = int(raw_input("Guess Col: ")) if guess_row == ship_row and guess_col == ship_col: print("Congratulations! You sank my battleship!") break else: if guess_row not in range(5) or guess_col not in range(5): print("Oops, that's not even in the ocean.") print("Game Over") elif board[guess_row][guess_col] == "X": print("You guessed that one already.") else: print("You missed my battleship!") board[guess_row][guess_col] = "X" print_board(board)
from Tools.scripts.treesync import raw_input def getsum(num): sumi = 0 num = str(num) i = 0 while i < len(num): sumi += int(num[i]) i += 1 return sumi test = int(raw_input()) for j in range(0, test): n, k = raw_input().split() n = int(n) k = int(k) j = n - 1 list = [] while j >= 0: if getsum("{0:b}".format(j)) <= k and j % 2 != 0: list.append(j) j -= 1 list.sort() print(list[len(list) - 1])
from random import randint from Tools.scripts.treesync import raw_input random_number = randint(1, 10) guesses_left = 3 # Start your game! while guesses_left > 0: guess = int(raw_input("Your guess: ")) if random_number == guess: print("You win!") break guesses_left -= 1 else: print("You lose.")
import string from Tools.scripts.treesync import raw_input alphas = string.ascii_letters + '_' nums = string.digits print('Welcome to the Identifier') print('Testees must ') myInput = raw_input('Identifier to test?') if len(myInput) > 1: if myInput[0] not in alphas: print('invalid: first symbol must be alphabetic') else: for otherChar in myInput[1:]: if otherChar not in alphas + nums: print('invalid: remaining') break else: print('okay as an identifier')
from Tools.scripts.treesync import raw_input str = raw_input("请输入:") print("你输入的内容是: ", str)
import random from Tools.scripts.treesync import raw_input min = 1 max = 6 roll_again = "yes" while roll_again == "yes": print("Rolling the dices...") print("The values are....") print(random.randint(min, max)) print(random.randint(min, max)) roll_again = raw_input("Roll the dices again?")
sleep(3) except Exception as e: dr.get_screenshot_as_file(DIR + '/' + newtime + '_test_wap.jpg') print(e) self.assertIsNone(e) def test_m_mynest(self): try: dr = self.driver dr.find_element_by_id('MYNEST').click() sleep(1) dr.find_element_by_link_text('我的窝首页').click() sleep(2) dr.switch_to.frame('mainFrame') if dr.find_elements_by_id('table') == None: raise ValueError('显示内容有误') dr.switch_to.default_content() sleep(3) except Exception as e: dr.get_screenshot_as_file(DIR + '/' + newtime + '_test_mynest.jpg') print(e) self.assertIsNone(e) @classmethod def tearDownClass(self): self.driver.quit() if __name__ == '__main__': unittest.main() raw_input()
import urllib.request import time import re import subprocess from Tools.scripts.treesync import raw_input url = input("输入电影的的地址:") dizhi = "https://660e.com/?url=" + url print("确认地址:" + dizhi) time.sleep(0.7) print("") print("以下为网页解析的网页代码,请自行找出m3u8地址") response = urllib.request.urlopen(dizhi) html = response.read().decode('utf-8') print(html) url = re.search(r"""url=(.*.m3u8)""", html).group(1) print(url) command = "ffmpeg -i " + url + " -vcodec copy -acodec copy 1.mp4" print(subprocess.call(command)) raw_input("Press <enter>")
#!/usr/bin/python # -*- coding: UTF-8 -*- # 题目:输入三个整数x,y,z,请把这三个数由小到大输出。 # 程序分析: # 我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换, # 然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。 from Tools.scripts.treesync import raw_input l = [] for i in range(3): x = int(raw_input('integer:\n')) l.append(x) l.sort() print(l)
#coding:utf-8 import socket,select #xiaorui.cc from Tools.scripts.treesync import raw_input host = "localhost" port = 10000 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((host,port)) data = raw_input("Please input some string > ") #在python2中是可以这样用的,但是3以后就必须使用编码了 s.sendall(data.encode('utf-8')) s.close()
def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) print(ship_row) print(ship_col) # Everything from here on should go in your for loop! # Be sure to indent four spaces! for turn in range(4): guess_row = int(raw_input("Guess Row:")) guess_col = int(raw_input("Guess Col:")) if guess_row == ship_row and guess_col == ship_col: board[guess_row][guess_col] = "+" print("Congratulations! You sunk my battleship!") break else: if (guess_row < 0 or guess_row > 4) \ or (guess_col < 0 or guess_col > 4): print("Oops, that's not even in the ocean.") elif board[guess_row][guess_col] == "X": print("You guessed that one already.") else: print("You missed my battleship!") board[guess_row][guess_col] = "X" # Print (turn + 1) here!
clf1,String1 = svm_train(train_vecs,y_train,test_vecs,y_test) Precision(clf1,String1)#训练svm并保存模型 clf2,String2 = lg_train(train_vecs, y_train, test_vecs, y_test) Precision(clf2,String2) ''' xiugaiguo ''' ##对输入句子情感进行判断 string1='电池充完了电连手机都打不开.简直烂的要命.真是金玉其外,败絮其中!连5号电池都不如' string2='牛逼的手机,从3米高的地方摔下去都没坏,质量非常好' string =[string1 , string2] ##用户自定义输入 sentence1 = raw_input("Enter your sentence1:") sentence2 = raw_input("Enter your sentence2:") SENTENCE = [sentence1, sentence2] ##使用word2vec+svm print("使用word2vec+SVM进行预测") for i in string: svm_predict(i) for sentence in SENTENCE: svm_predict(sentence) ##使用word2vec+lg print("使用word2vec+LG进行预测") for i in string: lg_predict(i) for sentence in SENTENCE:
from Tools.scripts.treesync import raw_input Id = raw_input('enter your id: ') print("here is the id:"+str(Id))
import platform from Tools.scripts.treesync import raw_input from netaddr import * import subprocess from termcolor import colored import sys workingips = set([]) while (1): ipAdrress = raw_input('Enter the ip Address range or n to exit:') if ipAdrress[0].lower() == "n": sys.exit("good bye :D") try: print() ips = list(IPNetwork(ipAdrress)) for i in range(len(ips)): print(colored("Pinging %s" % ips[i], 'blue')) if platform.system() == "Windows": command = ("ping " + str(ips[i]) + " -n 3 -w " + str(1 * 50)) else: command = "ping -i " + str(1) + " -c 3 " + str(ips[i]) p = subprocess.Popen(command, stdout=subprocess.PIPE) p.wait() if p.poll(): print(colored("%s is down" % ips[i], 'red')) else: print(colored("%s is up" % ips[i], 'green')) workingips.add(ips[i])