def check_account(): account = open('data.txt', 'r+') first_name = raw_input("What's your first name please: ") password = raw_input("Password please: ") lines = account.readlines() for index in range(len(lines)): dets = (lines[index].split(",")) if (dets[0] == first_name) and (dets[2] == password):
def save_data(self,url,title,endPage): # 加载页面数据到数组中 self.get_data(url,endPage) # 打开本地文件 f = open(title+'.txt','w+') f.writelines(self.datas) f.close() print (u'爬虫报告:文件已下载到本地并打包成txt文件' ) print (u'请按任意键退出...') raw_input()
def create_account(): account = open('data.txt', 'a') first_name = raw_input("first name: ") last_name = raw_input("last name: ") password = "******" balance = 0 account_number = to_string(str(random.randint(0, 10000000000) % 10000000000)) acc_details = first_name + "," + last_name + "," + str(password) + "," + str(balance) + "," + str( account_number) + "\n" account.write(acc_details)
def deposit_money(): account = open('data.txt', 'r+') first_name = raw_input("What's your name please: ") password = str(raw_input("Password please: ")) lines = account.readlines() bigIndex = -1 for index in range(len(lines)): dets = (lines[index].split(",")) if (dets[0] == first_name) and (dets[2] == password):
def withdraw_money(): account = open('data.txt', 'r+') first_name = raw_input("What's your name please: ") password = raw_input("Password please: ") lines = account.readlines() bigIndex = -1 for index in range(len(lines)): dets = (lines[index].split(",")) if (dets[0] == first_name) and (dets[2] == password): money_to_withdraw = raw_input("How much do you want to withdraw: ")
def begin(): print('Welcome! Ready to test what is fact or not?') name = raw_input("What is your name:") print('Welcome,' +name+' !') start = raw_input('Are you ready play? (yes or no)') if start == 'yes': print('Let get started!') begin_game() elif start == 'no': print('Thanks for stopping by!') print()
def populate(): if (len(list(Category.objects.all()))>0) or (len(list(Page.objects.all()))>0): if not (raw_input("資料以存在,是否刪除 yes no? ")=="yes"): print("已停止建置資料.") return Category.objects.all().delete() Page.objects.all().delete() # Python category = addCategory('Python') addPage(category, '官方 Python 教材', 'http://docs.python.org/2/tutorial/') addPage(category, '如何像電腦科學家一樣思考', 'http://www.greenteapress.com/thinkpython/') addPage(category, '10 分鐘內學好 Python', 'http://www.korokithakis.net/tutorials/python/') # 其他程式語言 category = addCategory('其他程式語言') addPage(category, 'C 程式語言', 'http://www.tutorialspoint.com/cprogramming/c_overview.htm') addPage(category, 'Java 程式語言', 'https://www.java.com/zh_TW/') # Django category = addCategory('Django') addPage(category, '官方 Django 教材', 'https://docs.djangoproject.com/en/1.8/intro/tutorial01/') addPage(category, 'Django 真讚', 'http://www.djangorocks.com/') addPage(category, '如何和 Django 跳探戈', 'http://www.tangowithdjango.com/') # 其他框架 category = addCategory('其他框架') addPage(category, 'Bottle 框架', 'http://bottlepy.org/docs/dev/') addPage(category, 'Flask 框架', 'http://flask.pocoo.org') # 印出所輸入的資料 for category in Category.objects.all(): for page in Page.objects.filter(category=category): print("頁面 "+category.name, '--', page.title+"...加入成功")
def main(): global numVariables, numSoluciones , numIteraciones numVariables = int(raw_input("Numero de variables: ")) numSoluciones = int(raw_input("Numero de soluciones a generar: ")) numIteraciones = int(raw_input("Numero de iteraciones: ")) limites = raw_input("Introduzca un intervalo global para las variables [Li Ls]: ") opc = raw_input("Generar intervalos distintos para cada variable? (s/n): ") opc = opc.upper() if "S" in opc: print("Todas las variables tendran un valor aleatorio contenido en ", limites) crearIntervalos(limites, numVariables, 0) elif "N" : crearIntervalos(limites, numVariables, 1) else: print("Opcion incorrecta") generaArchivo()
def classifyPerson(): from pip._vendor.distlib.compat import raw_input from numpy.ma import array resultList = ['not at all', 'in small does', 'in large does'] percentTats = float(raw_input("percentage of time spent playing video games?")) ffMiles = float(raw_input("frequent flier miles earned per year?")) iceCream = float(raw_input("liters of ice cream consumed per year?))")) datingDataMat, datingLabels = KNN.file2matrix("..\\resources\\chp02\\datingTestSet2.txt", 3) # 1. 기존의 데이터와 분류정보 normMat, ranges, minVals = KNN.autoNorm(datingDataMat) # 2. 기존 데이터 정규화 inArr = array([ffMiles, percentTats, iceCream]) # 3. 분류할 데이터를 입력폼에 맞게 설정(배열활) classifierResult = KNN.classify0((inArr - minVals) / ranges, normMat, datingLabels, 3) # 4. 데이터 입력 및 분류 print("You will probably like this person: %s" % resultList[int(classifierResult) - 1]) # 5. 결과 출력
def takeInput(): n = raw_input("Enter the number of disks: ") try: nDisk = int(n) except: print("Invalid input") return nDisk;
def func(x=""): """set pregame var""" name1="" name2="" if x=="": temp=" " elif x==1: temp="" gametype="TEST RUN" name1="CPU1" name2="CPU2" """set game var with user input""" while temp!="y" and temp!="n" and temp!="": temp=raw_input("play against the Computer? y or n ") while name1.isalpha()==False: name1=raw_input("name player 1: ") """check if playing against player or cpu""" if temp=="y": gametype="PVE" name2="CPU" elif temp=="n": gametype="PVP" while name2.isalpha()==False: name2=raw_input("name player 2: ") """set points to zero""" points1=0 points2=0 """add inforamtion to gamedictionary""" game=[] game.append(gametype) names=[] names.append(name1) names.append(name2) game.append(names) points=[] points.append(points1) points.append(points2) game.append(points) return game
def send_user(): usern = raw_input("请输入您的帐户(使用默认帐户请按‘Enter’键):") if usern.strip()=="": usern="15355451791" try: driver.find_element_by_css_selector("#idPlaceholder").send_keys(usern) except NoSuchElementException as e: print(e)
def currencyConverter(): userChoice = raw_input("what do you wont to convert? \n1)USD > Euro \n2)Euro > USD \n") if userChoice == "1": userUSD = raw_input("Enter the amount in USD you wish to convert \n") Euro = int(userUSD) * 0.88 print("$", userUSD, "= ", Euro, "Euro") print("-------------------------------------------------------------") doAgain() elif userChoice == "2": userEuro = raw_input("Enter the amount in Euro you wish to convert \n") USD = int(userEuro) / 0.88 print("Euro", userEuro, "= ", USD, "$") print("-------------------------------------------------------------") doAgain() else: print("Error: You entered invalid information. Please try again") print("-------------------------------------------------------------") currencyConverter()
def doAgain(): userDoAgain = raw_input ("Would you like convert again? \n1) Yes \n2) No \n") if userDoAgain == "1": currencyConverter() elif userDoAgain == "2": print("Thank you for using this program") else: print ("Error: You entered invalid information. Please try again") doAgain()
def takeInput(): faces = raw_input("Enter the sides of the dice: ") try: n = int(faces) except: print("Invalid input") return n
def main(): #continuous gaming experience while(True): wanna_play = raw_input("ROCK PAPER SCISSORS!! (y/n)") if wanna_play == "y": take_user_input() elif wanna_play == "n": print("Thank you for playing!") break
def siSinoAnidado(): x=int (raw_input("Ingrese un numero")) if x==2: print("Es el numero dos") elif(x==3): print("Es el numero tres") elif(x==4): print("Es el numero cuatro") else: print("Es otro numero")
def send_pwd(): passw = raw_input("请输入您的密码(使用默认帐户请按‘Enter’键):") if passw.strip()=="": passw="5912519" print(passw) try: #driver.find_element_by_css_selector("#pwdPlaceholder").clear() driver.find_element_by_id("pwdPlaceholder").send_keys(passw) except NoSuchElementException as e: print(e)
def rollTheDice(numberOfFaces): keepRolling = True while(keepRolling): faceUp = randint(1,numberOfFaces) print("Dice rolled to {}".format(faceUp)) choice = raw_input("Do you want to roll the dice:(y/n) ") if choice == "n": keepRolling = False
def __init__(self): isReaded = 0 while isReaded == 0 : print("type your file name : input.txt") self.fileName = raw_input() try : self.filePointer = open(self.fileName, 'r+') isReaded = 1 except : isReaded = 0 self.filePointer = open(self.fileName, 'r+')
def main(): welcome() path = raw_input("Voer het pad of bestand in dat u wilt onderzoeken: ") print("Bedankt, we gaan nu uw antwoord valideren") if isdir(path): print("Dit is een map") print("De inhoud van de map is als volgt: ") for sub in os.listdir(path): print(sub) elif isfile(path): print("Dit is een bestand") else: print("Wat is dit?!")
def proceed(prompt, allowed_chars, error_prompt=None, default=None): p = prompt while True: s = raw_input(p) p = prompt if not s and default: s = default if s: c = s[0].lower() if c in allowed_chars: break if error_prompt: p = '%c: %s\n%s' % (c, error_prompt, prompt) return c
def take_user_input(): player_choice = raw_input("Choose:\n1.Rock\n2.Paper\n3.Scissors") try: player_choice = int(player_choice) if(player_choice > 3): raise ValueError except ValueError: print("Invalid input") sys.exit(0) #converting choice to 0 based player_choice = player_choice - 1 display(player_choice)
def imprimirEstadoFinal(self,mejoresSol): mejorFinal = mejoresSol[len(mejoresSol) - 1] print("[FIN] MEJOR SOLUCION:\n >>> |APTITUD|: [",mejorFinal[0],"] |SOLUCION|: ", mejorFinal[1], " encontrada en |ITERACION| ",mejorFinal[2],"\n") opc = "s" opc = raw_input("Imprimir conjuto de mejores soluciones? (s/n): ") opc = opc.upper() if "S" in opc: print("----------------------------------------") print("--------- Mejores soluciones -----------") print("----------------------------------------") contador = 0 for solucion in mejoresSol: print(contador,"] |Sol|", solucion[1], "|Iter|",solucion[2],"|Aptitud|",solucion[0]," \n") contador = contador+1 print("FIN de Proframa")
def input_loop(modules): selectedModule = '' while selectedModule != 'exit': selectedModule = raw_input('Please specify a module to deploy ("exit" to exit): ') if selectedModule in modules: readline.add_history(selectedModule) os.chdir(modules.get(selectedModule)) os.system("gradlew deploy") elif selectedModule in portal_paths: readline.add_history(selectedModule) os.chdir(portal_home + portal_paths[selectedModule].get('path')) os.system(portal_paths[selectedModule].get('command')) elif selectedModule != 'exit': print("Nothing to deploy, go along")
def update_to_develop(): """从当前分支更新到 develop """ output_list = local('git status', True).split('\n') branch = output_list[0].replace('On branch ', '') if branch in ['develop', 'master']: puts('不允许在 {} 分支 用 {} 命令直接操作'.format(yellow(branch), get_function_name())) elif 'nothing to commit' in output_list[-1]: confirm = raw_input('是否已经update_from_develop? [y/N]: '.format(yellow(branch))) if confirm.lower() in ['ok', 'y', 'yes']: puts('从 {} 合并到 develop'.format(yellow(branch))) local('git checkout develop') local_proxy('git pull') local('git merge {}'.format(branch)) local_proxy('git push') local('git checkout {}'.format(branch)) else: local('git status') puts('当前 {} 分支有更新未提交, 请先执行 fab git_commit 命令提交'.format(yellow(branch)))
def number_of_days(month): if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: return ("This month has 31 days ") elif month == 4 or month == 6 or month == 9 or month == 11: return ("This month has 30 days") elif month == 2: leap_year = int(raw_input("Enter a year then we will tell you if feb has 28 or 29 days: ")) if leap_year % 4 == 0 and leap_year % 100 != 0 or leap_year % 400 == 0: return ("Leap year 29 days") else: return ("Normal year just 28 days") else: return ("A number between 1-12 please")
def number_of_days(month): if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: print("This month has 31 days ") elif month == 4 or month == 6 or month == 9 or month == 11: print("This month has 30 days") elif month == 2: leapYear = int(raw_input("Enter a year then we will tell you if feb has 28 or 29 days: ")) if leapYear % 4 == 0 and leapYear % 100 != 0 or leapYear % 400 == 0: print("Leap year 29 days") else: print("Normal year just 28 days") else: print("You don't seem to follow rules do you?")
def Program(self): print("PROJE ISIM URETECI >>>") query = raw_input() command = str.upper(query.split(' ')[0]) if command == "GENERATE": language = str.upper(query.split(' ')[1]) count = int(query.split(' ')[2]) self.Generate(count, language) elif command == "HELP": print("### YARDIM ###") print("GENERATE KOMUTU: 1. Parametre; dil ayarı (TR:Türkçe ve EN:İngilizce), 2. Parametre; üretilmek istenen isim sayısı.\n") print("HELP KOMUTU: Yardım menüsü\n") print("EXIT KOMUTU: Çıkış\n") elif command == "EXIT": self.SaveGeneratedDictionary() exit()
def upload(self, specific_path=None): if specific_path is None: only_dir = self.cmd_args.sync_path else: only_dir = os.path.dirname(specific_path) photo_sets = self.local.build_photo_sets(only_dir, EXT_IMAGE + EXT_VIDEO) logger.info('Found %s photo sets' % len(photo_sets)) if specific_path is None: # Show custom set titles if self.cmd_args.custom_set: for photo_set in photo_sets: logger.info('Set Title: [%s] Path: [%s]' % (self.remote.get_custom_set_title(photo_set), photo_set)) if self.cmd_args.custom_set_debug and raw_input('Is this your expected custom set titles (y/n):') != 'y': exit(0) # Loop through all local photo set map and # upload photos that does not exists in online map for photo_set in sorted(photo_sets): folder = photo_set.replace(self.cmd_args.sync_path, '') display_title = self.remote.get_custom_set_title(photo_set) logger.info('Getting photos in set [%s]' % display_title) photos = self.remote.get_photos_in_set(folder) logger.info('Found %s photos' % len(photos)) for photo, file_stat in sorted(photo_sets[photo_set]): # Adds skips if self.cmd_args.ignore_images and photo.split('.').pop().lower() in EXT_IMAGE: continue elif self.cmd_args.ignore_videos and photo.split('.').pop().lower() in EXT_VIDEO: continue if photo in photos or self.cmd_args.is_windows and photo.replace(os.sep, '/') in photos: logger.info('Skipped [%s] already exists in set [%s]' % (photo, display_title)) else: logger.info('Uploading [%s] to set [%s]' % (photo, display_title)) if file_stat.st_size >= 1073741824: logger.error('Skipped [%s] over size limit' % photo) continue file_path = os.path.join(photo_set, photo) photo_id = self.remote.upload(file_path, photo, folder) if photo_id: photos[photo] = photo_id
# -*- coding: utf-8 -*- # @Time : 2020/11/26 23:37 # @Author : SourDumplings # @Email : [email protected] # @Link : https://github.com/SourDumplings/ # @Site : # @File : TCPClient.py from socket import * from pip._vendor.distlib.compat import raw_input serverName = 'localhost' serverPort = 12000 clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName, serverPort)) sentence = raw_input('Input lowercase sentence:') clientSocket.send(sentence.encode()) modifiedSentence = clientSocket.recv(1024) print('From Server: ', modifiedSentence.decode()) clientSocket.close()
import textwrap from pip._vendor.distlib.compat import raw_input def wrap(string, data): str = "" for d in range(0, len(string), max_width): str += string[d:d + max_width] + "\n" return str if __name__ == '__main__': string, max_width = raw_input(), int(raw_input()) result = wrap(string, max_width) print(result)
# Introduction to programming Task2 # Artur Goncharov I-17b-3 from pip._vendor.distlib.compat import raw_input import math print("Introducing to programming: Task1") print("Artur Goncharov, I-17b") x = int(raw_input("please enter x: ")) z = int(raw_input("please enter z: ")) if x == -2: print("Введенный x за областью определения функции!") if z == 0: print("Введенный z за областью определения функции!") y = (((2 * (x ** 2)) + x - 5) / (x + 2)) + (math.cos(x/(2*z))) / (math.sin(x/(2*z))) print(y)
from pip._vendor.distlib.compat import raw_input rows = int(raw_input('输入列数: ')) #声明变量,i用于控制外层循环(图形行数),j用于控制空格的个数,k用于控制*的个数 i = j = k = 1 #打印空心等边三角形 for i in range(0, rows + 1): for j in range(0, rows - i): print(' ', end='') j + 1 for k in range(0, 2 * i - 1): if k == 0 or k == 2 * i - 2 or i == rows: if i == rows: if k % 2 == 0: print('*', end='') else: print(' ', end='') else: print('*', end='') else: print(' ', end='') k += 1 print('\n', end='') i += 1
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from pip._vendor.distlib.compat import raw_input import json from product import Product import time URL = 'https://www.amazon.ae/' # opts = Options() # opts.set_headless() driver = webdriver.Chrome() driver.get(URL) search_item = raw_input("what you want to search : ") search = driver.find_element_by_id('twotabsearchtextbox') search.send_keys(search_item) search.send_keys(Keys.ENTER) products = [] def convert_price_to_number(price): try: price = price.split("AED")[1] price = price.split("\n")[0] + "." + price.split("\n")[1] except: Exception() try: price = price.split(",")[0] + price.split(",")[1] except:
def populate_chapters(self, folder=None, extensions=None): if folder is None: folder = self.args.chapters_path if extensions is None: extensions = self.args.chapters_file_extensions self.log.info("Processing chapters...") filenames_are_ids = raw_input( "\nChapter file names are chapter ids? Y/N\n") has_ids = True if str.lower(filenames_are_ids) == 'y' else False file_paths = self._gather_and_dedupe(folder, extensions, has_ids) char_encoding = raw_input( "\n\nImporting chapters: pick character encoding (check for curly quotes):\n" "1 = Windows 1252\nenter = UTF-8\n") if char_encoding == '1': char_encoding = 'cp1252' else: char_encoding = 'utf8' cur = 0 total = len(file_paths) if has_ids: for cid, chapter_path in file_paths.items(): with codecs.open(chapter_path, 'r', encoding=char_encoding) as c: try: cur = Common.print_progress(cur, total) file_contents = c.read() query = "UPDATE {0}.chapters SET text=%s WHERE id=%s".format( self.args.output_database) self.cursor.execute(query, (file_contents, int(cid))) self.db.commit() except Exception as e: self.log.error( "Error = chapter id: {0} - chapter: {1}\n{2}". format(cid, chapter_path, str(e))) finally: pass else: for _, chapter_path in file_paths.items(): path = chapter_path.replace(self.args.chapters_path, '')[1:] with codecs.open(chapter_path, 'r', encoding=char_encoding) as c: try: cur = Common.print_progress(cur, total) file_contents = c.read() query = "UPDATE {0}.chapters SET text=%s WHERE url=%s and text=''".format( self.args.output_database) self.cursor.execute(query, (file_contents, path)) self.db.commit() except Exception as e: self.log.error( "Error = chapter id: {0} - chapter: {1}\n{2}". format(path, chapter_path, str(e))) finally: pass self.db.close()
ttl = struct.pack('b', 1) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) sock.sendto(json.dumps(message).encode('utf8'), multicast_group) while True: try: sock.recvfrom(16) except: sock.close() return 0 else: print('pesan berhasil dikirim') sock.close() return 1 if __name__ == '__main__': print("receiver port " + str(port) + ": ") print("==============") while 1: print("1. send lokasi") print("2. menerima pesan dan mengirimkan ke node selanjutnya") print("3. keluar") inputan = raw_input('Pilihan > ') if (inputan == '1'): sendPosition() elif (inputan == '2'): multicast() elif (inputan == '3'): exit() else: print('inputan salah')
# # Write your code here # K = int(input()) # if 1 <= K <= pow(10, 5): # ctr = 1 # N = input().split(' ') # h = sorted(N) # # if int(N[-1]) >= int(h[-1]): # print(int(h[-1]) + 1) # else: # print((int(h[-1]) + int(N[-1]) + ctr)) from pip._vendor.distlib.compat import raw_input a = input() b = list(map(lambda x: int(x), raw_input().split())) dem = 1 b.sort() c = b[::-1] dem = 0 kq1 = 0 for i in c: kq = i + 2 + dem dem += 1 if kq > kq1: kq1 = kq print (kq1)
from startchat import start_chat from getdetail import get_details from pip._vendor.distlib.compat import raw_input from spydetails import spy, friends from steganography.steganography import Steganography from datetime import datetime print("Hello! Let\'s get started") question = "Do you want to continue as " + spy['salutation'] + " " + spy[ 'name'] + " (Y/N)? " existing = raw_input(question) if existing == "Y" or existing == "y": start_chat(spy['name'], spy['age'], spy['rating']) else: get_details()
def run_antispoof(): ip = raw_input("[*] Enter IP [192.168.0.37]: ") if ip == "": ip = "192.168.0.37" anti_spoofing(ip)
from pip._vendor.distlib.compat import raw_input print ("It's Brunch Time!! Let me help you find the perfect place!") name = raw_input("Enter a zip code: ") date = raw_input("What day would you like to search hours for? ") color = raw_input("Do you want to also search for bottomless drink deals? ") print (("We are searching for resturants near %s, on %s, and %s for drink deals.") % (name, date, color))
import time def is_palindrome_word(): word = raw_input("Insert word: ") tmp_word = ''.join(reversed(word)) if word == tmp_word: print("Entered word: " + word + " is a palindrome word ") else: print("Entered word: " + word + " isn't a palindrome word ") def print_menu(): print( "==================================================\n Palindorme Word Checker" ) print("==================================================") if __name__ == "__main__": while True: print_menu() # time.sleep(2) This instruction can put on sleep mode the execution of all script is_palindrome_word() choice = raw_input("Another operation? yes/no ") if choice == "yes" or choice == "y": os.system("clear") is_palindrome_word() else: break
bcolors.OKGREEN + 'At each stage of the program execution, you can stop the current process by pressing Ctrl+C.' + bcolors.ENDC) time.sleep(2) # the user must to start the program with interface in the managed mode and program will turn it to the monitor mode print( bcolors.OKGREEN + 'Before starting sniffing is necessary to turn your interface to the monitor mode.' + bcolors.ENDC) time.sleep(2) # list of available interfaces interfaces = os.listdir('/sys/class/net/') print(bcolors.OKGREEN + 'Your available interfaces: %s' % interfaces + bcolors.ENDC) time.sleep(2) # -------------------------------------------------Interface choosing--------------------------------------------------- # user have to choose one of the available interfaces interface = '' while interface == '': interface = raw_input( bcolors.HEADER + 'Please select one of the available interfaces for the wifi capturing: ' + bcolors.ENDC) # if user selected right interface then break otherwise chose again if interface in interfaces: break else: print(bcolors.WARNING + 'The selected interface does not exists... Please select again.' + bcolors.ENDC) interface = '' # switch interface to monitor mode by airmong command print(bcolors.OKBLUE) system('airmon-ng start %s' % interface) print(bcolors.ENDC) interface = interface + 'mon' # ----------------------------------------------------Remove old pcap--------------------------------------------------- if os.path.exists(file_name):
import pandas as pd import numpy as np from pip._vendor.distlib.compat import raw_input ts = pd.Series(np.random.randn(10)) ts[4:-3] = np.nan strex = ts.to_sparse() print(strex) print(strex.fillna(method='pad')) # input types str = raw_input("Enter your input: ") print("Received input is : ", str) str1 = input("Enter your input: ") print("Received input is : ", str1)
def do_authentication_flow(api_key): request_url = SCOPES request_url += api_key webbrowser.open_new_tab(request_url) return raw_input('Paste the token here: ')
from pip._vendor.distlib.compat import raw_input name = raw_input("what is your name?") if name.endswith("tank"): print("hello tank !") else: print(name + " You are welcome !")
def _gather_and_dedupe(self, chapters_path, extensions, has_ids=False): self.log.info("\nFinding chapters and identifying duplicates") extensions = re.split(r", ?", extensions) story_folder = os.walk(chapters_path) file_paths = {} duplicate_chapters = {} has_duplicates = False messages = [] sql_messages = [] cur = 0 for root, _, filenames in story_folder: total = len(filenames) Common.print_progress(cur, total) for filename in filenames: if has_ids and self._ends_with(filename, extensions): file_path = os.path.join(root, filename) cid = os.path.splitext(filename)[0] if cid not in file_paths.keys(): file_paths[cid] = file_path else: duplicate_folder = os.path.split( os.path.split(file_path)[0])[1] messages.append(file_path + " is a duplicate of " + file_paths[cid]) sql_messages.append( "SELECT * FROM chapters WHERE id = {1}".format( cid)) duplicate_chapters[cid] = [{ 'folder_name': os.path.split(os.path.split( file_paths[cid])[0])[1], 'filename': filename, 'path': file_paths[cid] }, { 'folder_name': duplicate_folder, 'filename': filename, 'path': file_path }] has_duplicates = True else: file_path = os.path.join(root, filename) name = os.path.splitext(filename)[0] file_paths[name] = file_path if has_duplicates: self.log.warn('\n'.join(messages + sql_messages)) self.log.warn(duplicate_chapters) folder_name_type = raw_input( "Resolving duplicates: pick the type of the folder name under {0} " "\n1 = author id\n2 = author name\n3 = skip duplicates check\n" .format(chapters_path)) if folder_name_type == '1': for cid, duplicate in duplicate_chapters.items(): # look up the author id and add that one to the file_names list self.cursor.execute( "SELECT author_id FROM chapters WHERE id = {1}".format( cid)) sql_author_id = self.cursor.fetchall() if len(sql_author_id) > 0: author_id = sql_author_id[0][0] file_paths[cid] = [ dc['path'] for dc in duplicate_chapters[cid] if dc['folder_name'] == str(author_id) ][0] elif folder_name_type == '2': self.log.warn("Not implemented") return file_paths
from pip._vendor.distlib.compat import raw_input arab = 0 rome = str(raw_input()) list(rome) last = 2000 last2 = last last3 = last2 for i in range(len(rome)): if (rome[i] == "I"): if (last == 1 and last2 == 1 and last3 == 1): arab = "zle dane" break if (last != 1 and last2 == 1): arab = "zle dane" break last3 = last2 last2 = last last = 1 arab += 1 if (rome[i] == "V"): if (last2 == 1): arab = "zle dane" break if (last == 1): arab += 3 else: arab += 5 last3 = last2 last2 = last last = 5
from pip._vendor.distlib.compat import raw_input print('hello, this is a calculator') num1 = raw_input("number1:\t") num2 = raw_input("number2:\t") operator = raw_input("operator:\t") print("%s %s %s=" % (num1, num2, operator))
if Answer != 0: try: f = open('GRUModelInfoX', "r") lines = f.readlines() for i in lines: thisline = i.split(" ") seq_len = int(thisline[0]) batch = int(thisline[1]) skip = int(thisline[2]) f.close() except: print( "\nUh Oh! Caught some exceptions! May be you are missing the file having time step information" ) seq_len = int( raw_input("Time Steps (I hope, you remember what it was): ")) batch = int( raw_input( "Training batch size(I hope, you remember what it was): ")) skip = int( raw_input( "How many characters do you want to skip after every sequence while training?: (I hope, you remember what it was): " )) f = open('GRUModelInfoX', 'w+') f.write(str(seq_len) + " " + str(batch)) f.close() if Answer == 0 or Answer == 2: """index = int((total_chars-seq_len)/batch) index = batch*index dataset = dataset[:index+seq_len]
from pip._vendor.distlib.compat import raw_input print("HELLO WORLD!") resume = True while (resume): print("Welcome to the Unit Converter. Please enter kilometers to convert them into miles.") input = float(raw_input()) result = float(0.621371 * input) print("%.2f" % result) print("Would you like to convert another number?") input_again = raw_input() if (input_again == "No" or input_again == "no"): resume = False
from pip._vendor.distlib.compat import raw_input age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weight? ") print("So, you're %r old, %r tall and %r heavy." % (age, height, weight))
from pip._vendor.distlib.compat import raw_input if __name__ == '__main__': x = int(raw_input()) y = int(raw_input()) z = int(raw_input()) n = int(raw_input()) print([[a, b, c]for a in range(x+1) for b in range(y+1) for c in range(z+1) if a+b+c != n])
def main(): file = open("UD_English-ParTUT/en_partut-ud-train.conllu") try: sentences = parse(file.read()) finally: file.close() print('Caricamento...') # Crea mappa TAG - numero occorrenze tags_map = set_tags_map(sentences) # POS -> POS - Crea elenco di coppie di TAG con probabilità pos_pos_probability_list = PosPosProbList(tags_map, sentences) # POS -> WORD - Crea un elenco di probabilità associate a tag e parola pos_word_probability_list = PosWordProbList(tags_map, sentences) #show menu menu = {} menu[ '1'] = "The black droid then lowers Vader's mask and helmet onto his head." menu['2'] = "These are not the droids your looking for." menu['3'] = "Your friends may escape, but you are doomed." menu['4'] = "Valutazione test set" menu['5'] = "Confronto baseline" menu['6'] = "Termina" while True: options = menu.keys() for entry in options: print(entry, menu[entry]) selection = raw_input("Please Select:") if selection == '1': phrase = 'The black droid then lowers Vader \'s mask and helmet onto his head .' pos_tagging = viterbi(phrase, pos_pos_probability_list, pos_word_probability_list, tags_map) print(phrase) print(pos_tagging) elif selection == '2': phrase = 'These are not the droids your looking for .' pos_tagging = viterbi(phrase, pos_pos_probability_list, pos_word_probability_list, tags_map) print(phrase) print(pos_tagging) elif selection == '3': phrase = 'Your friends may escape , but you are doomed .' pos_tagging = viterbi(phrase, pos_pos_probability_list, pos_word_probability_list, tags_map) print(phrase) print(pos_tagging) elif selection == '4': file = open("UD_English-ParTUT/en_partut-ud-test.conllu") try: test_sentences = parse(file.read()) finally: file.close() # Get all phrases equals = 0 tot = 0 for sent in test_sentences: phrase = '' for word in sent: phrase = phrase + word['form'] + ' ' pos = viterbi(phrase, pos_pos_probability_list, pos_word_probability_list, tags_map) #print(phrase) #print(pos) for i in range(0, len(pos)): if pos[i] == sent[i]['upostag']: equals += 1 tot += 1 print('Accuracy:', equals, '/', tot, '=', (equals / tot * 100), '%') elif selection == '5': print('DA FARE') #test_baseline() elif selection == '6': break else: print("Selezione non permessa!")
def addItem(): newItem = raw_input("Please, enter to name of the item you want to add: ") groceryList.append(newItem)
from pip._vendor.distlib.compat import raw_input N = int(input()) set1 = set(map(int, raw_input().split())) M = int(input()) set2 = set(map(int, raw_input().split())) symmetric_differences = (set1.difference(set2)).union(set2.difference(set1)) for i in sorted(list(symmetric_differences)): print(i)
if aList[0] == "NICK": return aList[1] else: print("ERROR: INVALID COMMAND") sys.exit() def parsingUser(): pass if __name__ == "__main__": args = [] print("HELLO WELCOME.\n") nickCommand = raw_input( "PLEASE INPUT YOUR NICK COMMAND format: NICK <nickname>\n") stringNick = nickCommand send( stringNick ) # let server verify if nickname already exists. If it already exists the code breaks in server.py nickName = parsingNickname( stringNick) # we parse and only take the nickname args.append(nickName) # not sure what to put in for the user command aside from the port.. # user = raw_input("PLEASE INPUT YOUR USER COMMAND format: USER <username> <hostname> <servername> <realname>\n") main(args)
import wikipedia from pip._vendor.distlib.compat import raw_input while True: my_input = raw_input("Question: ") print(wikipedia.summary(my_input))
if document in self._index[term].keys(): f = self._index[term][document] #Term Frequency in the document n = self._dftable[term][1] #Document Frequency of the term #Calculate the BM25 score for each term with the current document docScore += self.tfIdfTermScore(f, n, dl) #Update the result dictionary. searchResults.update({document : docScore}) #Return an ordered dictionary according to score return OrderedDict(sorted(searchResults.items() , key = lambda x:x[1] , reverse = True)) #Function to calculate tfidf score def tfIdfTermScore(self, f, n , dl): tf = f / dl idf = math.log(CONSTANTS.N(self) / n) return (tf * idf) #Class to define all the constants use to calculate the BM25 score. class CONSTANTS: def N(self): return 3204 if __name__ == "__main__" : index = raw_input("Enter json file where index is stored:") corpus = raw_input("Enter folder where corpus to be searched is stored:") query = raw_input("Enter json file where cleaned queries were stored:") tfIdf = TfIdfSearch(index , corpus , query) tfIdf.search()
return "Vector({},{})".format(self.a, self.b) def __add__(self, other): self.a += other.a self.b += other.b return Vector(self.a, self.b) def __sub__(self, other): self.a -= other.a self.a -= other.b return Vector(self.a, b) def __mul__(self, other): self.a *= other.a self.b *= other.b return Vector(self.a, self.b) def __abs__(self): return math.hypot(self.a, self.b) # Main a, b = map(int, raw_input("Input values of vector 1: ").split()) v1 = Vector(a, b) a, b = map(int, raw_input("Input values of vector 2: ").split()) v2 = Vector(a, b) v3 = Vector(4, 5) print("Vector addition:", v1+v2+v3) print("Vector subtraction:", v1-v2) print("Vector multiplication:", v1*v2) print("Absolute Value:", v1.__abs__())