Exemple #1
0
def escolher_pasta():
    c_pasta_origem = r"V:\COMPARTILHADO_CSC-SSE_NSIF\NP-2\GPI\4 - Apoio Administrativo\4.4 - Monte " \
                     r"Albuquerque\Desenvolvimento\Pedro\Pycharm\Anexar_Ordem_SAP\A Transferir"

    while 1:

        msg = "Escolha a Pasta de Origem dos arquivos. Gostaria de Selecionar a pasta ou usar a pasta padrão?" \
              r"      Pasta Padrão: " + c_pasta_origem
        title = "Escolha Pasta Origem"
        choices = ["Usar Padrão", "Escolher"]
        choice = g.choicebox(msg, title, choices)

        # note that we convert choice to string, in case
        # the user cancelled the choice, and we got None.

        if choice == "Escolher":
            choice = g.diropenbox()
            c_pasta_origem = choice

        # g.msgbox("Você escolheu: " + str(c_pasta_origem), "Resultado Escolha")

        msg = "Gostaria de Continuar?   Você escolheu: " + str(c_pasta_origem)
        title = "Please Confirm"
        if g.ccbox(msg, title):  # show a Continue/Cancel dialog
            pass  # user chose Continue
            break
        else:
            choice = ""  # user chose cancel
    # user chose Cancel

    # Escolha da pasta de Saída

    c_pasta_destino = r"V:\COMPARTILHADO_CSC-SSE_NSIF\NP-2\GPI\4 - Apoio Administrativo\4.4 - Monte " \
                      r"Albuquerque\Desenvolvimento\Pedro\Pycharm\Anexar_Ordem_SAP\OK"

    while 1:

        msg = "Escolha a Pasta de Destino. Gostaria de Selecionar a pasta ou usar a pasta padrão?" \
              r"      Pasta Padrão: " + c_pasta_destino
        title = "Escolha Pasta Destino"
        choices = ["Usar Padrão", "Escolher"]
        choice = g.choicebox(msg, title, choices)

        # note that we convert choice to string, in case
        # the user cancelled the choice, and we got None.

        if choice == "Escolher":
            choice = g.diropenbox()
            c_pasta_destino = choice

        # g.msgbox("Você escolheu: " + str(c_pasta_destino), "Resultado Escolha")

        msg = "Gostaria de Continuar?   Você escolheu: " + str(c_pasta_destino)
        title = "Please Confirm"
        if g.ccbox(msg, title):  # show a Continue/Cancel dialog
            pass  # user chose Continue
            return c_pasta_origem, c_pasta_destino
            # break
        else:
            choice = ""  # user chose cancel
def final(t, w):  #对结局进行判断
    if w == 6:  #如果先赢了6次,就算赢
        askplay = g.ccbox(
            '现在的比分为 %d : %d,\n这一局,你赢了!' % (10 - t - w, w),
            '石头-剪刀-布1.0版', ('再来一局', '不想玩了'),
            image='E:\\python files\\IDEL FILES\\picture\\youwin.png')
        if askplay == True:  #如果选择再来一次
            return 'continue'  #这里只是一个信号,返回一个字符串,当主程序收到这个字符串是会对t,w变量初始化,由于是局部变量不能在函数里面进行初始化,所以要移到主程序。
        else:  #如果选择退出
            sys.exit()
    if t == 0 and w == 5:  #如果10次,最后只赢了5次,平局
        askplay = g.ccbox(
            '现在的比分为 %d : %d,\n这一局,我们是平局!' % (10 - t - w, w),
            '石头-剪刀-布1.0版', ('再来一局', '不想玩了'),
            image='E:\\python files\\IDEL FILES\\picture\\tie.png')
        if askplay == True:
            return 'continue'
        else:
            sys.exit()
    if (10 - t - w) == 6:  #如果先输了6次,就输
        askplay = g.ccbox(
            '现在的比分为 %d : %d,\n这一局,你输了!' % (10 - t - w, w),
            '石头-剪刀-布1.0版', ('再来一局', '不想玩了'),
            image='E:\\python files\\IDEL FILES\\picture\\final lose.png')
        if askplay == True:
            return 'continue'
        else:
            sys.exit()
def main():
    try:
        while True:
            # Directory input
            directory = easygui.diropenbox(
                "Select a folder to recursively search", program)
            if directory is None:
                if easygui.ccbox("No folder selected. Try again?", program):
                    continue
                else:
                    exit()
            print("Directory: ", directory)

            # Keyword input
            keyword = easygui.enterbox(
                "Enter the keyword to search for, case insensitive", program)
            if keyword is None:
                if easygui.ccbox("No keyword entered. Try again?", program):
                    continue
                else:
                    exit(0)

            print("Keyword: ", keyword)

            results = search(directory, keyword)

            print("Entries: ", len(results))
            print("Results: ", results)

            if results is None:
                if easygui.ccbox("No Results found. Try again?", program):
                    continue
                else:
                    exit(0)
            unc = pathlib.Path(directory).resolve()
            header = "To save press OK.\nResults: \n Directory: " + directory + "\n UNC: " + str(
                unc
            ) + "\n Keyword: " + keyword + "\n Number of Results: " + str(
                len(results))
            results_pretty = ""
            for line in results:
                results_pretty += line + "\n\n"
            if easygui.textbox(header, program, results_pretty):
                path = easygui.filesavebox("Save Results", program,
                                           program + "_" + keyword,
                                           results_pretty)
                if path is not None:
                    save_file(path, results)
                    exit(0)
                else:
                    exit(0)
            else:
                exit(0)

    except SystemExit:
        exit(0)
    except:
        easygui.exceptionbox(
            "Error occurred. Please contact the maintainer of this program.",
            program)
def land():
    global username, password
    number_of_time = 1
    value = []
    value = g.multpasswordbox(msg="Land( Press 'OK' to go to the next step )",
                              fields=("Username : "******"Password : "******"哈哈只有这一步是中文,我是Cyg,这个程序是我一个人编写出来的,有什么报错给我说下哈,启动turing机器人")
        turing.turing()
    elif value[0] != now_username:
        choice = g.msgbox("Username error , do you want to tyr again?")
        if choice and number_of_time <= 2:
            number_of_time += 1
    else:
        choice = g.ccbox(msg="Password error, do you want to try again?")
        if choice and number_of_time <= 2:
            number_of_time += 1

        else:
            forpassword = g.ccbox(msg="Forget Password?",
                                  choices=("Yes", "No"))
            if forpassword:
                forget_password()
            else:
                g.msgbox("See you next time!")
def final(t, w):  #对结局进行判断
    if w == 6:  #如果先赢了6次,就算赢
        askplay = g.ccbox('现在的比分为 %d : %d,\n这一局,你赢了!' % (10 - t - w, w),
                          '石头-剪刀-布1.0版', ('再来一局', '不想玩了'),
                          image=resource_path(
                              os.path.join('source', 'youwin.png')))
        if askplay == True:  #如果选择再来一次
            return 'continue'  #这里只是一个信号,返回一个字符串,当主程序收到这个字符串是会对t,w变量初始化,由于是局部变量不能在函数里面进行初始化,所以要移到主程序。
        else:  #如果选择退出
            sys.exit()
    if t == 0 and w == 5:  #如果10次,最后只赢了5次,平局
        askplay = g.ccbox('现在的比分为 %d : %d,\n这一局,我们是平局!' % (10 - t - w, w),
                          '石头-剪刀-布1.0版', ('再来一局', '不想玩了'),
                          image=resource_path(os.path.join(
                              'source', 'tie.png')))
        if askplay == True:
            return 'continue'
        else:
            sys.exit()
    if (10 - t - w) == 6:  #如果先输了6次,就输
        askplay = g.ccbox('现在的比分为 %d : %d,\n这一局,你输了!' % (10 - t - w, w),
                          '石头-剪刀-布1.0版', ('再来一局', '不想玩了'),
                          image=resource_path(
                              os.path.join('source', 'final lose.png')))
        if askplay == True:
            return 'continue'
        else:
            sys.exit()
Exemple #6
0
 def login_interface(self):
     while 1:
         title = '校团委实践部文件管理系统(demo@Fan)'
         msg = '请选择你的身份'
         choice = ('管理员', '游客')
         identity = g.ccbox(msg, title, choice)  #管理员是TURE,游客是FALSE
         while (identity):
             msg = '请输入账号和密码'
             fields = ('账号', '密码')
             ret = g.multpasswordbox(msg, title, fields)
             if (ret == None):  # 点击右上角的xx
                 return 0
             if ret != ['admin', '123456']:  #现在暂时固定密码,之后可能会放到一个加密文件夹中
                 msg = '账号或密码输入错误,请选择重新输入还是返回上一步'
                 choice = g.ccbox(msg, title, choices=('返回上一步', '重新输入'))
                 if (choice == None):
                     return 0
                 if (choice):
                     break
                 else:
                     continue
             else:
                 return 'admin'
         else:
             return 'tourist'
Exemple #7
0
def check_database_file_exists(user_dir):
    # print(os.path.abspath(os.path.join(user_dir, "Experiment_Database.xlsx")))
    if not os.path.exists(
            os.path.abspath(os.path.join(user_dir,
                                         "Experiment_Database.xlsx"))):
        easygui.ccbox(
            title="WARNING",
            msg=
            "The database file Experiment_Database.xlsx where power data is stored was not found in the RecPwr main program directory. In order to successfully Save data and to ensure that the data you capture is added sequentially with the correct Run number at the bottom of the database, you must Copy and Paste the most up to date Excel_Database.xlsx file from the Network drive into the folder '{0}' and Then click CONTINUE or rerun this program. Once testing is complete, make sure to copy this Local file back to the Network so that the Network is always up to date."
            .format(os.path.abspath(user_dir)))
Exemple #8
0
def get_access_token():
    data = {"grant_type": "client_credentials"}
    msg = "Please enter your client credentials and company base url.\nIf you need help finding your credentials, " \
          "please visit:\n" \
          "https://arthurosipyan.github.io/JamaScript/"
    field_names = ["Base URL", "Client ID", "Client Secret"]
    field_values = multpasswordbox(msg, title, field_names)
    # make sure that none of the fields was left blank
    while 1:
        if field_values is None:
            break
        errmsg = ""
        for i in range(len(field_names)):
            if field_values[i].strip() == "":
                errmsg = errmsg + ('"%s" is a required field.\n\n' %
                                   field_names[i])
        if errmsg == "":
            break  # no problems found
        field_values = multpasswordbox(errmsg, title, field_names,
                                       field_values)
    global access_token, base_url
    base_url = field_values[0]
    username = field_values[1]
    password = field_values[2]
    try:
        requests.post(base_url + "/rest/oauth/token",
                      data=data,
                      auth=(username, password))
    except:
        msg = 'ERROR: Please enter the correct base url.'
        if ccbox(msg, title):
            get_access_token()
        else:
            exit()

    try:
        response = requests.post(base_url + "/rest/oauth/token",
                                 data=data,
                                 auth=(username, password))
        access_token = response.json()['access_token']
        user = response.json()['application_data']["JAMA_CORE"]
        global welcome
        welcome = ("Welcome, " + user)
    except KeyError:
        response = requests.post(base_url + "/rest/oauth/token",
                                 data=data,
                                 auth=(username, password))
        msg = (
            'ERROR: Please enter the correct client credentials.\nSTATUS: ' +
            str(response.json()['status']) + ' ' + response.json()['error'] +
            '\n' + 'MESSAGE: ' + response.json()['message'])
        if ccbox(msg, title):
            get_access_token()
        else:
            exit()
 def get_max(self, fname):
     easygui.ccbox('insert image with hebrew inst for max check')
     # max config
     self.socket.send_json(0, flags=0)
     winsound.Beep(250, 3000)
     incoming = self.socket.recv_json()
     self.socket.send_json(self.connected_channels)
     incoming = self.socket.recv_json()
     easygui.ccbox(
         'insert image: dont touch the sensor for 3 seconds and then press cont'
     )
Exemple #10
0
 def show_your_turn(self):
     """Shows rooms in which it is the user's turn to play."""
     if self._rooms:
         string = self.create_string(self._rooms)
         string = self._username + ", it's your turn on rooms:" \
             + string
         if not easygui.ccbox(string, self._title):
             sys.exit(0)
     elif self._no_room:
         string = self._username + ", it isn't your turn in any room!"
         if not easygui.ccbox(string, self._title):
             sys.exit(0)
def run():
    """Main Function that will run the whole program including the gui
    :param:none
    :rtype:none
    """
    global TITLE
    global SECTIONS
    global SPEAKERS
    global DATA
    #Welcome Window
    eg.msgbox("Welcome to the Beckman Research Application!", TITLE)
    #Instruction Window
    instruction_string = MakeInstructionString()
    eg.msgbox(instruction_string, TITLE)
    #create window for text file
    msg = ('What is the name of the Text file \n'
           + 'Make sure it is contained within the same folder as the application')
    documentname = eg.enterbox(msg='What is the name of the Text file'
                               , title=TITLE
                               , default='TextDocument'
                               , strip=True
                               , image=None
                               , root=None)
    datafile = os.path.abspath('../../../' + documentname + '.txt')
    DATA = ReadFile(datafile)

    #Show Section Titles To User
    SECTIONS = AddSectionToCollection(GetSectionTitleIndicies())
    SECTIONS = CleanSection()
    SECTIONS = fix_empty_section_titles(SECTIONS)
    SECTIONS = fix_empty_section_texts(SECTIONS)

    choices = ShowSectionTitlesToBeSelected()
    choice = eg.choicebox(msg, TITLE, choices)

    #display the selected section text to user
    ShowSelectedSectionText(choice)
    #display next section title just in case to user for future ref

    #once the use has chose a section to analyze, run the gui
    SectionSelectedGUI(choice)

    if eg.ccbox('EXIT?', TITLE):  # show a Continue/Cancel dialog
        pass  # user chose Continue
    else:
        sys.exit(0)  # user chose Cancel

    msg = "Do you want to continue?"
    title = "Please Confirm"
    if eg.ccbox(msg, title):  # show a Continue/Cancel dialog
        pass  # user chose Continue
    else:
        sys.exit(0)  # user chose Cancel
Exemple #12
0
 def login_avature(self): # TODO Wait for List View to Be Loaded
     self.driver.get("https://cisco.avature.net")
     easygui.msgbox("Please Login Into Avature. Minimize this window and then click OK when you are logged in.")
     time.sleep(5)
     easygui.ccbox("Confirming You Are Logged In to Avature")
     if self.clean_slate() is False:
         self.clean_slate()
     self.driver.get("https://cisco.avature.net/#People/Id:2266")
     time.sleep(1)
     WebDriverWait(self.driver, 30).until(
         EC.element_to_be_clickable((By.XPATH, "//*[text()='Add filter']"))
     )
     if self.clean_slate() is False:
         self.clean_slate()
def play():
    while True:
        player1 = HumanPlayer()
        player2 = Player(epsilon=0)
        judger = Judger(player1, player2)
        player2.load_policy()
        winner = judger.play()
        output = sys.stdout
        outputfile = open('tic.txt', "w")
        sys.stdout = outputfile
        if winner == player2.symbol:
            print("You lose!")
        elif winner == player1.symbol:
            print("You win!")
        else:
            print("It is a tie!")
        outputfile.flush()
        f = open('tic.txt', 'r')
        msg = ("结果是:")
        title = "tic_tac_toe"
        text = f.read()
        g.codebox(msg, title, text)
        f.close()
        msg = "您希望重新开始小游戏吗?"
        title = "请选择"
        if g.ccbox(msg, title):
            pass
        else:
            sys.exit(0)
        type = sys.getfilesystemencoding()  # python编码转换到系统编码输出
Exemple #14
0
def quizzer():
    temp = "Not selected yet"
    while 1:
        title = "Quizzer Window"
        choice = ["+","-","*","Create Expression"]
        msg = "Lets test your skills! Select an operator, then create your expression to solve"
        q_msg = eg.buttonbox(msg = msg,title = title,choices = choice)
        print(temp)
        
        if q_msg == "Create Expression":
            if temp == "Not selected yet":
                e_msg = "Oooops... You forgot to select an operator!"
                pick = ["Try again", "Return to Main Window"]
                err_msg = eg.ccbox(msg = e_msg,choices = pick)
                
                if err_msg == False:
                    return err_msg
            
            else:
                q = question(temp)
                if q == False:
                    return q
        temp = q_msg
        if temp == "Create Expression":
            temp = "Not selected yet"
Exemple #15
0
def is_there_a_sample():
    msg = "The balance reported a weight of 0.0000 g. Is there a sample on the balance?"
    title = "Missing sample?"
    if easygui.ccbox(msg, title):     # show a Continue/Cancel dialog
        return "continue"
    else:
        return "cancel"
Exemple #16
0
def ask_for_pause():
    msg = "Pausing weighing. Press Continue to carry on with measurement."
    mtitle = "Pause"
    if easygui.ccbox(msg, title=mtitle):     # show a Continue/Cancel dialog
        return "continue"  # user chose Continue
    else:
        return "exit"
Exemple #17
0
	def createFolder(self):
		# Create folder
		self.statusText["text"] = "Getting list of files..."
		self.statusText.update()

		print("Getting list of files")
		files = self.jotform.get_form_files(self.formID)

		if len(files) == 0:
			easygui.msgbox(msg="Form has 0 uploads. Please choose a form with uploaded files.")
			self.getForms()
			return

		# Got the file list - check if form file folder exists
		formPath = "./downloads/" + str(self.formID) + "/"

		d = os.path.dirname(formPath)
		if not os.path.exists(d):
			print("Creating form download path...")
			os.makedirs(d)

		self.progress = 0

		if easygui.ccbox(msg="You have " + str(len(files)) + " files uploaded for your form. Would you like to download them all?"):

			self.startDownload(d, files)
Exemple #18
0
def compare(input_num, answer_num_list):
    correct_num = 0
    correct_all = 0
    guess_num_list = []  #把输入的数字拆开,装入列表
    global times_guess
    times_guess += 1

    for i in input_num:
        guess_num_list.append(i)
    if operator.eq(guess_num_list, answer_num_list) == True:
        g.msgbox('恭喜你,猜对了!')
    else:
        if times_guess >= 7:
            g.msgbox('游戏结束了!')
        else:
            for j in range(0, 4):
                for k in range(0, 4):
                    if (guess_num_list[j] == answer_num_list[k]) and (j != k):
                        correct_num += 1
            for i in range(4):
                if guess_num_list[i] == answer_num_list[i]:
                    correct_all += 1
            feedback = "第 %d 次猜数字了,你的答案是 %dA %dB" % (times_guess, correct_all,
                                                     correct_num)
            if g.ccbox(feedback, choices=('继续猜', '不猜了')):
                input_num = g.enterbox(msg='请输入一个不重复的四位数:')
                judge_input
                compare(input_num, answer_num_list)
            else:
                g.msgbox('游戏结束了!')
                os._exit(0)
Exemple #19
0
def copyworkspace(src, dst):
    for dir in os.listdir(src):
        src_dir = src + '\\' + dir
        dst_dir = dst + '\\' + dir

        if checksubdirectory(src_dir) == False:
            shutil.copy(src_dir, dst_dir)
        else:
            try:       
                if os.path.exists(src_dir) == False:   # test the existence of src_file
                    easygui.msgbox("Source directory: " + src_dir + " does not exist!")
                    sys.exit(0) 
                            
                if os.path.exists(dst_dir) == True:    # test the existence of dst_file
                    if easygui.ccbox(dst_dir + " already exists! Overwriting?", title):
                        #pass
                        print("Overwriting " + dst_dir)
                        shutil.rmtree(dst_dir)
                    else:
                        print("Not overwriting " + dst_dir)
                        continue

                if dir == ".metadata":
                    print("Directory: " + src + " skipped!")
                else:                  
                    shutil.copytree(src_dir, dst_dir) 
                    print("Directory: " + src + " successfully copied!")
            except IOError as err:
                easygui.msgbox("I/O error: {0}".format(err))
                        
    easygui.msgbox("Backup executed successfully!")
Exemple #20
0
def gui():
    if g.ccbox("亲,你要不要爬取汽车之家呢", title="汽车之家", choices=("要", "不要")):
        g.msgbox("亲,请等待大概两分钟!!!,点击ok后开始爬取", title="汽车之家")
        getAllcarprice()
        g.msgbox("爬取完毕,请去本地D盘找到pacar.xlsx打开,查看数据", title="汽车之家")
    else:
        sys.exit(0)
Exemple #21
0
    def createFolder(self):
        # Create folder
        self.statusText["text"] = "Getting list of files..."
        self.statusText.update()

        print("Getting list of files")
        files = self.jotform.get_form_files(self.formID)

        if len(files) == 0:
            easygui.msgbox(
                msg=
                "Form has 0 uploads. Please choose a form with uploaded files."
            )
            self.getForms()
            return

        # Got the file list - check if form file folder exists
        formPath = "./downloads/" + str(self.formID) + "/"

        d = os.path.dirname(formPath)
        if not os.path.exists(d):
            print("Creating form download path...")
            os.makedirs(d)

        self.progress = 0

        if easygui.ccbox(msg="You have " + str(
                len(files)
        ) + " files uploaded for your form. Would you like to download them all?"
                         ):

            self.startDownload(d, files)
Exemple #22
0
def CreateMessageBox(message, title, style):
    if style == MESSAGE_BOX_TYPE['OK']:
        return easygui.msgbox(message, title)
    elif style == MESSAGE_BOX_TYPE['OK|CANCEL']:
        return easygui.ccbox(message, title)
    elif style == MESSAGE_BOX_TYPE['YES|NO']:
        return easygui.ynbox(message, title)
Exemple #23
0
def end():
    response = easygui.ccbox("Do want to do another operation ?",
                             "Confirmation Message")
    if (response):
        return -1
    else:
        sys.exit(0)
Exemple #24
0
def main():
	msg = "Start pomodoro-timing?"
	choices = ["Yes","No"]
	reply = g.buttonbox(msg, choices=choices)

	if reply == "Yes":
		title = "Please Confirm"
		print("25 minute work")
		timer(1500)
		choices = ["Yes","No","Long break!","Lunch"]
		while(True):
			#push("Pause")
			os.system('cls' if os.name == 'nt' else 'clear')
			reply = g.buttonbox("Worked for 25 min. Time for a break! \n Do you want to continue?" ,choices=choices)
			if reply == "Yes":
				print("5 min break")
				timer(300)
			elif reply == "Long break!":
				print("long break! coma back in 15 minutes!")
				timer(900)
			elif reply == "Lunch":
				print("Taking a 30 min lunch!")
				timer(1800)
			else:
				break
			
			push("Pause over! Get back to Work!")
			if g.ccbox("Five minute break over! Time to work the next 25 min! \n Do you want to continue?", title):
				print("sleeping for 25 minutes")
				timer(1500)
				#print(chr(27) + "[2J")
			else:  
				break
Exemple #25
0
def ask_for_sample():
    msg = "Please place sample on balance and hit continue when stabilized"
    title = "Add sample"
    if easygui.ccbox(msg, title):     # show a Continue/Cancel dialog
        return "continue"  # user chose Continue
    else:
        return "exit"
Exemple #26
0
def main():
    global VERSION
    global OS
    global PATHS

    OS = get_os()
    PATHS = get_paths()

    # Init GUI
    message = "Operating System: " + OS + " - Undernuke Version: " + VERSION + "\n" \
        "Copyright (c) 2015 Younes \"drcd\" Zakaria\n\n"\
        "All the savefiles within the following paths will be deleted:\n"

    for p in PATHS:
        message += "\n  -  " + p

    message += "\n\nThis program is designed to fully reset the savefiles of Undertale to its initial state.\n" \
        "\nPlease note that all savefiles for Undertale will be deleted after running this program." \
        "\nIf you want to reset the game to a fresh state, press the \"Continue\" button.\n" \
        "\nDISCLAIMER: Undertale and all associated characters (c) Toby Fox 2013 - 2015.\n" \
        "THIS SOFTWARE IS NOT AFFILIATED WITH, OR ENDORSED BY THE DEVELOPER(S) OF UNDERTALE.\n\n" \
        "This software is licensed under the MIT License. For more info, visit: \ndrcd.github.io/undernuke/LICENSE.txt"

    title = "Undernuke - v" + VERSION

    if g.ccbox(message, title):
        if nuke():
            g.msgbox("Your soul has now been refunded!", title="Savefiles successfully reset", ok_button="Alright!")
        else:
            g.msgbox("An error occurred, most likely due to permission errors.\n" +
                     "Have you tried running as an administrator?", title="Error", ok_button="OK")
    else:
        sys.exit(0)
Exemple #27
0
def sql_performer(input_dict):
    """
    Takes input as dictionary of sql queries' and their corresponding arguments' list,
    return list of results or status of the query
    :param input_dict: dict
    :return: list or boolean
    """
    try:
        db = pymysql.connect(host="replace_with_host_name_or_address",
                             user="******",
                             password="******",
                             db="replace_with_database")
        try:
            query_list = []
            update = fetch = False
            with db.cursor() as cur:
                print("Connected to the cursor")
                for sql, args in zip(input_dict['sqls'],
                                     input_dict['search_query']):
                    # zipped the args in query_return to use here, which is best practice to
                    # prevent from sql-injection
                    query_list.append(sql % args)
                    cur.execute(sql.strip(), (args, ))
                    if sql.startswith('DELETE') or sql.startswith('UPDATE'):
                        update = True
                    elif sql.startswith('SELECT'):
                        fetch = True
                        result = cur.fetchall()

            if update:
                try:
                    y_n = easygui.ccbox(
                        msg="Following changes would be made\n" +
                        "\n".join(str(e) for e in query_list) + "\n" +
                        "Do you want to proceed?")
                    if y_n:
                        db.commit()
                    else:
                        db.rollback()
                    print("Changed successfully made to the database!")
                    return True
                except:
                    print("Some error occured")
                    db.rollback()
                    return False

            if fetch:
                print("Got following result(s): ")
                for i in result:
                    print(i)
                return result

        except:
            print("Some error fetching data.")

    except pymysql.err.OperationalError:
        print("Access Denied")

    finally:
        db.close()
Exemple #28
0
def create_semapp(semapps):
    """Ask for new course reserve, return an updated list."""
    semapps = semapps
    title = "SEMAPP"
    msg = "Bitte Namen für den neuen Semesterhandapparat eingeben!"
    new_semapp = ""

    while not new_semapp:
        new_semapp = easygui.enterbox(msg, title).strip()

        # prüfen, ob der Name mit einem Großbuchstaben beginnt. Wenn nicht,
        # nächster Versuch
        if new_semapp[0].islower():
            easygui.msgbox(
                "Der Name des Semesterhandapparates muss mit einem Großbuchstaben beginnen."
            )
            new_semapp = ""
            continue

        if new_semapp:
            if new_semapp in semapps:
                # Wenn ein Apparat dieses Namens schon vorhanden ist, nichts tun
                easygui.msgbox(
                    f'Apparat "{new_semapp}" ist bereits vorhanden!')
            else:
                # Neuen Apparat zur Liste hinzufügen
                confirm_msg = f'Neuen Semesterhandapparat "{new_semapp}" anlegen?'
                confirmation = easygui.ccbox(confirm_msg, title)
                if confirmation:
                    semapps.append(new_semapp)

    # pickle the new list
    pickle.dump(sorted(semapps), open(semapps_path, "wb"))
    return sorted(semapps)
Exemple #29
0
def run(url):
    if url.startswith('https://www.youtube.com/watch'):
        vid = pafy.new(url)
        if ccbox('Downloading ' + vid.title + '. Confirm?'):
            best = vid.getbest(preftype='mp4')
            path = diropenbox('Select save directory')
            best.download(filepath=path, quiet=True)
Exemple #30
0
def play_selected_movie(movies_dict, selected, is_easygui=True):
    if selected is None:
        print("Goodbye!")
        sys.exit(0)
    # get selected movie path
    selected_movie = movies_dict[selected]
    #use with esaygui
    if is_easygui:
        try:
            if easygui.ccbox("Play " + str(selected_movie) + " ?",
                             "Movie to play"):
                cmd = "/usr/bin/omxplayer -o hdmi " + str(selected_movie)
                print(cmd)
                output = subprocess.check_output(cmd, shell=True)
                print(output)
            else:
                main_w_gui()
        except KeyboardInterrupt:
            print("Goodbye")
            sys.exit(0)
    else:
        # use with console
        if str(input("Play " + str(selected_movie) +
                     " ?\nMovie to play[Y/N] ")).lower() == "y":
            cmd = "/usr/bin/omxplayer -o hdmi " + str(selected_movie)
            print(cmd)
            output = subprocess.check_output(cmd, shell=True)
            print(output)
        else:
            main_w_console()
Exemple #31
0
def getUserInput():
    #Get user input
    url = ez.enterbox(
        "Please enter a YouTube URL\n(Eg. https://www.youtube.com/watch?v=TPqTDtKiTIE)",
        "YouTube_dl GUI")
    '''
	1. First check: Check whether URL is null
	2. Second check: Check whether it's a valid YouTube URL
	3. Third check: Using requests library to send a HEAD request to check whether response code returns 200 OK
	'''
    if (url) and re.match(
            "^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$", str(url)):
        r = requests.head(str(url))
        if r.status_code == 200:
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                meta = ydl.extract_info(str(url), download=False)
                if ez.ccbox(
                        "Title: " + str(meta['title']) + "\nDuration: " +
                        str(meta['duration']) +
                        " seconds\nProceed to download?", "YouTube_dl GUI"):
                    return url
                else:
                    sys.exit(0)
        else:
            ez.msgbox(
                "This video doesn't exist, please try with another video")
            sys.exit(0)
    else:
        ez.msgbox(
            "Sorry, the URL you input is invalid, please try with another URL",
            "YouTube_dl GUI")
        sys.exit(0)
def show_windows():
    while 1:
#            title = "Message from test1.py"
#            eg.msgbox("Hello, world!", title)
    
        msg ="Run with which classification model?"
        title = "Classification model"
        models = ["Multinomial Naive Bayes", "Support Vector Machines", "Maximum Entropy"]
        model_choice = str(eg.choicebox(msg, title, models))
    
        msg     = "Use saved preset values?"
        choices = ["Yes","No"]
        choice = eg.buttonbox(msg,choices=choices)
        if str(choice)=="Yes":
            model_preset_functions[model_choice]()
        else:
            model_select_functions[model_choice]()
    
        # note that we convert choice to string, in case
        # the user cancelled the choice, and we got None.
#            eg.msgbox("You chose: " + str(choice), "Survey Result")
        message = "Sentiments over time period something something"
        image = "temporal_sentiments.png"
        eg.msgbox(message, image=image)
        
        msg = "Do you want to continue?"
        title = "Please Confirm"
        if eg.ccbox(msg, title):     # show a Continue/Cancel dialog
            pass  # user chose Continue
        else:
            sys.exit(0)           # user chose Cancel
Exemple #33
0
def gui_mode():
    load_mode_list = ['file', 'folder']
    load_mode = easygui.ccbox(msg='load a file or folder?',
                              title=' ',
                              choices=load_mode_list)

    choicess_list = [
        'count_char', 'count_words', 'count_lines', 'all_data', 'file_type'
    ]
    mode = easygui.buttonbox(msg='choose mode:',
                             title=load_mode,
                             choices=choicess_list)

    if load_mode == 0:  # 递归遍历目录下的所有子目录
        path = easygui.diropenbox(msg='please choose a path')
        os.chdir(path)
        for dirpath, dirs, files in os.walk('.'):  # 递归遍历当前目录和所有子目录的文件和目录
            for name in files:  # files保存的是所有的文件名
                if is_code_file(name):
                    print('--------------------{}--------------------'.format(
                        name))
                    file_name = os.path.join(dirpath,
                                             name)  # 加上路径,dirpath是遍历时文件对应的路径
                    choose_mode_gui(mode, file_name)
    else:
        file_name = easygui.fileopenbox(msg='please choose a file')
        choose_mode_gui(mode, file_name)
Exemple #34
0
def loop_times():
    loop = easygui.ccbox('是否需要循环多次执行?','循环执行测试',choices=['否','是'])
    if loop == 0:
        times = easygui.enterbox(msg='格式如:5',title='请输入循环执行的次数')
        print "Run loop times is %s"%times
        return times
    return loop
def mappingVideo():
    ext = ".mp4"

    while (True):
        try:
            filename = easygui.fileopenbox("Please Select Video")
            # show an "Open" dialog box and return the path to the selected file

            if (ext not in filename):

                easygui.msgbox(
                    "Please Select a file that has \".mp4\" extention",
                    "Wrong Entry Message", "OK")
                continue

            # loop to check if ext is not ".mp4" once it's found --- break the loop

            video = "INSERT INTO video (video_name) VALUES (%s)"
            value = filename
            mycursor.execute(video, (value, ))
            mydb.commit()
            print(mycursor.rowcount,
                  "Video is selected and it's name stored in the database.\n")
            return filename

        except mysql.connector.Error as e:
            exception = easygui.ccbox(
                "The video name is already stored in the database would you like to continue?",
                "Warning Message")

            if (exception):  # show a Continue/Cancel dialog
                return filename  # user chose Continue
            else:  # user chose Cancel
                continue
Exemple #36
0
 def fk_move(self):
     if ord(self.key) ==119:
         self.x-=1
     elif ord(self.key) ==115:
         self.x+=1
     elif ord(self.key) ==97:
         self.y-=1
     elif ord(self.key) ==100:
         self.y+=1
     elif ord(self.key) ==106:
         return 'j'
     elif ord(self.key) ==107:
         return 'k'
     elif ord(self.key) == 27:  # key nr 27 is escape
         if easygui.ccbox('是否退出游戏','退出',choices=(['是','否'])):
             return 'esc'
         else:
             pass
     #边缘判定
     if self.x<0:
         self.x=map_xy_max[0]-1
     if self.x>=map_xy_max[0]:
         self.x=0
     if self.y<0:
         self.y=map_xy_max[1]-1
     if self.y>=map_xy_max[1]:
         self.y=0
Exemple #37
0
def ccbox_2():
    if g.ccbox(msg='do you want continue?',
               title='choose',
               choices=('yao', 'buyao')):
        g.msgbox('结束了,不给玩了', ok_button='想玩就再点我')
    else:
        sys.exit(0)
Exemple #38
0
def writeUserID():
    """写入保存ID的配置文件的GUI界面"""
    while True:
        user_id = easygui.enterbox(msg="输入id(如e1765849):",
                                   title="录入ID").replace("e", "")
        # 获取输入GUI
        if not user_id:
            easygui.msgbox("错误!ID不得为空!")
            # 为空时的操作
        else:
            try:
                userName = func.getUserName(user_id)
                # 尝试获取名字,检测ID是否正确
            except:
                easygui.msgbox("错误!请检查你的ID是否正确!")
                # 丢出错误
            else:
                if easygui.ccbox("您是%s吗?" % userName, choices=("是", "不是")):
                    # 确定
                    break
    idtxt = open("youxue_user_id.txt", 'w+')
    idtxt.write(user_id)
    # 不存在的话创建并写入ID
    easygui.msgbox("录入成功!重启生效!")
    # 重新启动以刷新全局变量
    return 0
Exemple #39
0
def main(fake_data):
    with PomodoriLogger(fake_data) as pomo:

        while True:
            action = g.indexbox('', image=POMODORO_IMG, choices=OPTIONS)

            if action == 0:
                pomo.add_pomodori()

            elif action == 1:
                num_pomos = g.choicebox('How many pomodori?',
                                        'Input amount of pomodori',
                                        POMODORI_AMOUNTS)
                pomo.add_pomodori(num_pomos)

            elif action == 2:
                pomo.show_stats()

            elif action == 3:
                msg = "Do you want to continue?"
                title = "Please Confirm"
                if g.ccbox(msg, title):
                    pomo.reset()

            elif action == 4:
                print('Goodbye')
                sys.exit(0)

            else:
                print('Invalid choice')
                continue
Exemple #40
0
def completed_text():
    msg = "Files sorted succesfully. Sort another folder?"
    title = "File Sorter v1.0"
    if easygui.ccbox(msg, title):
        pass
    else:
        sys.exit(0)
Exemple #41
0
def change(addr):
    while True:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(addr, 22, "root", "root")
        get_time = ['date +%F', 'date +%T']
        tim = []
        for m in get_time:
            stdin, stdout, stdeer = ssh.exec_command(m)
            tim.append(stdout.read())
        y = tim[0]
        h = tim[1]
        y = y.strip().split('-')
        h = h.strip().split(':')
        x = y + h

        msg = '输入日期'
        title = '挂机one修改时间'
        fieldNames = ['*年', '*月', '*日', '*时', '*分']
        fieldValues = []
        fieldValues = g.multenterbox(msg, title, fieldNames, values=x)

        y = int(fieldValues[0])
        m = int(fieldValues[1])
        d = int(fieldValues[2])
        h = int(fieldValues[3])
        M = int(fieldValues[4])

        update_time = ['date -s "%d-%d-%d %d:%d"' % (y, m, d, h, M)]
        ssh.exec_command(update_time[0])
        cho = g.ccbox('是否继续')
        if cho == 1:
            continue
        else:
            sys.exit()
Exemple #42
0
def main(inputFile=None):
    if(inputFile is not None):
        myarq = inputFile
    else:
        myarq = eg.fileopenbox(msg="Enter the latex file to be converted",
               title="Open tex file", default='*', filetypes=["*.tex"])

    msg = """
The file:
         %s
will be used to generate the .doc,.html and .pdf files.
Do you want to continue ?""" % myarq

    if eg.ccbox(msg, 'Start Process'):
        pass
    else:
        sys.exit(0)

    msg = '''If you have some figures in pdf it will be necessary convert these
    images in png files? Have you somo pdf images
'''
    if eg.ccbox(msg, title='Convert pdf figures to png',
                choices=('Yes', 'No')):
        figuresDir = eg.diropenbox(msg='Open the Figure Directory',
                                     title='Figure Directory')
    else:
        pass

    changeDir(myarq)

    depurarFicheiro(myarq)

    cleantemp1()

    bibAndHtml()

    grafiAjust()

    docGen()

    cleantemp2()

    changeFinalName(myarq)

    loc = '/'.join(myarq.split('/')[:-1])

    eg.msgbox("The .doc,.html and .pdf are in the folder:\n %s/ " % loc)
def main():
    
    def process_test(test):
        answer_match = string_find(regexes[1], test)
        if answer_match:
            answer_key = [x[1] for x in answer_match]
            test = string_replace(regexes[0], "A) True\nB) False\n", test)
            for regex in regexes[1:]:
                test = string_replace(regex, '', test)
            print test
            format_answers(answer_key)
            
    def string_find(pattern, string):
        return re.findall(pattern, string, flags=re.I | re.X)            

    def string_replace(pattern, string_old, string_new):
        return re.sub(pattern, string_old, string_new, flags=re.I | re.X)

    def format_answers(answers):
        print 'Answers:'
        number = 0
        for answer in answers:
            number += 1          
            answers = string_replace(regexes[3], "", str(number) + '.' + answer.replace(":", ""))
            print string.capwords(answers)
            
    msg = "This program will attempt to format a test file for use with Respondus, Do you want to continue?"
    title = "Respondus Format Utility version 1.5 Beta"
    if easygui.ccbox(msg, title):
        pass
    else:
        sys.exit(0)        
    try:
        sys.stdout = open(easygui.filesavebox(msg='Before we begin choose where to save your formatted test file?',
                                          default='formatted_test.txt'), 'w')      
    except TypeError:
        sys.exit(-1) 
    file_choice = easygui.indexbox(msg="Choose the file type of your test file (Note: Word is very experimental)",
                                   choices=("Plain text file (.txt)", "Word 2007, 2010 file (.docx)", "Quit"))
    if file_choice is 0:
        input_file = easygui.fileopenbox(msg='Where is the test file to format?')
        try:
            with open(input_file) as inputFileHandle:
                process_test(inputFileHandle.read().replace("\n", "\n\n"))
        except (TypeError, IOError):
            sys.stderr.write('Could not open %s\n' % input_file)
            sys.exit(-1)
    elif file_choice is 1:
        try:
            with zipfile.ZipFile(easygui.fileopenbox(msg='Where is the test file to format?')) as docx:                
                process_test(re.sub('<(.|\n)*?>', '\n', docx.read('word/document.xml')))                             
        except (TypeError, AttributeError, IOError):
            sys.stderr.write('Could not open %s\n' % zipfile)
            sys.exit(-1)  
    else:
        sys.exit(0)
    easygui.msgbox("Format complete!", ok_button="Close", image="tick_64.png")
    sys.stdout.flush()
    sys.stdout.close()
def main():
    print ("starting")
    msg = "hello"
    image ="2010 Anais ecoles-soccer"
    if easygui.ccbox():
        print("exciting")
    else:
        print ("finished")
Exemple #45
0
def done():
    STOPPED.set(1)
    NEXTSTEP.set(1)
    msg = "Done. Continue or exit?"
    mtitle = "Continue or Exit"
    if easygui.ccbox(msg, title=mtitle):     # show a Continue/Cancel dialog
        return "continue"  # user chose Continue
    else:
        sys.exit(0)
Exemple #46
0
def askContinue():  # check if user wishes to continue
    global main_flag

    msg = "Do you wish to continue?"
    title = "Continue?"
    choices = ["Sure", "Nah. I'm done"]
    if not eg.ccbox(msg, title, choices):
        main_flag = False
        exitMsg()
Exemple #47
0
def dlTutAll():
  msg = 'This will download all available tutorials as separate files.\nDo you wish to continue?'
  title = 'Download All?'

  if eg.ccbox(msg, title, image=imgTC):
    msg = 'Choose where you want the downloads to be kept:'
    path = eg.diropenbox(msg, default=os.getcwd() + os.sep + os.pardir)

    maker.makePDFfromList(tutList, path)
Exemple #48
0
def startup_text():
    '''shows at startup of program
    '''
    msg = "This program will sort files in a folder. Continue?"
    title = "File Sorter v1.0"
    if easygui.ccbox(msg, title):
        pass
    else:
        sys.exit(0)
def get_dir():
    dir_path = None
    while(dir_path == None):
        dir_path = easygui.diropenbox(msg="Choose directory",title="Choose directory",default=DEFAULT_DIRECTORY)
        if dir_path == None:
            if easygui.ccbox("Are you sure that you want to stop the scrip's execution?", "Please confirm"):
                sys.exit(0)
            else:
                continue
    print("Chosen directory: %s" % dir_path)
    return dir_path
Exemple #50
0
def gui():
    t = "Check Web Page Speed v 1.0"
    url2 = eg.enterbox(msg='Enter web site URL.', title='Web Page Speed v 1.0', default =' ', strip = True, image=None, root=None) 
 #   eg.exceptionbox(msg="You entered %s" % url2,title="Web Page Speed v 1.0" )   
 #   return url2
    msg = "Do you want to continue check %s ?" % url2
    title = "Please Confirm to continue"
    if eg.ccbox(msg, title):
       pass
       return url2
    else:
       sys.exit(0)
def set_num():
    numeration_type = None
    while(numeration_type == None):
        numeration_type = easygui.choicebox("What kind of numeration do you prefer?", "Numeration type", ["Increasing numbers", "Creation date", "Modification date"])
        if numeration_type == None:
            if easygui.ccbox("Are you sure that you want to stop the scrip's execution?", "Please confirm"):
                sys.exit(0)
            else:
                continue
        else:
            print("Chosen numeration type: %s" % numeration_type)
            return numeration_type
def connect(show_panel=True):
	resp = True
	if abtronics.IE:
		resp = ccbox('Il semblerait que vous soyez déjà connécté! Voulez-vous vous reconnécter?')
	if resp:
		run('taskkill /IM iexplore.exe /F')
		run('taskkill /IM JuniperSetupClient.exe /F')
		run('taskkill /IM dsSamProxy.exe /F')
		run('taskkill /IM dsSamUI.exe /F')
		abtronics.IE = Dispatch('InternetExplorer.Application')
		abtronics.IE.Visible = False
		with open('D:\\Users\\denis13\\logins.json') as f:
			logins = load(f)
		choices = []
		for login in logins['logins']:
			choices.append(login['username'] + ' (' + login['password'] + ')')
		msg ="Quel compte voulez-vous utiliser?"
		title = "Choix du compte"
		choice = choicebox(msg, title, choices)
		account = choice.split(' ')[0]
		pwd = choice.split(' ')[1].replace('(', '').replace(')', '')
		print('you choosed:', account, pwd)
		abtronics.IE.Navigate('https://lyon.metagate.orange.com/dana-na/auth/logout.cgi')
		while abtronics.IE.Busy: sleep(1)
		abtronics.IE.Navigate('https://lyon.metagate.orange.com/dana-na/auth/url_default/welcome.cgi')
		while abtronics.IE.Busy: sleep(1)
		abtronics.IE.Document.all.item('username').value = account
		abtronics.IE.Document.all.item('password').value = pwd
		abtronics.IE.Document.all.item('btnSubmit_6').Click()
		while abtronics.IE.Busy: sleep(1)
		if abtronics.IE.Document.all.item('btnContinue'):
			abtronics.IE.Document.all.item('btnContinue').Click()
		while abtronics.IE.Busy: sleep(1)
		while 'Orange' not in abtronics.IE.Document.all.tags('title')[0].innerText:
			sleep(1)
		while abtronics.IE.Busy: sleep(1)
		abtronics.IE.Navigate('http://geofibre.sso.francetelecom.fr/geofibre/login.jsp')
		while abtronics.IE.Busy: sleep(1)
		if abtronics.IE.Document.all.item('overridelink'):
			abtronics.IE.Document.all.item('overridelink').Click()
		while abtronics.IE.Busy: sleep(1)
		abtronics.IE.Document.all.item('user').value = account
		abtronics.IE.Document.all.item('password').value = pwd
		abtronics.IE.Document.all.item('linkValidForm').Click()
		while abtronics.IE.Busy: sleep(1)
		# if abtronics.IE.Document.GetElementsByTagName('a'):
		# 	abtronics.IE.Document.GetElementsByTagName('a')[0].Click()
		# 	while abtronics.IE.Busy: sleep(1)
		abtronics.IE.Navigate('http://geofibre.sso.francetelecom.fr/RestFmkSrvDeploy/orion/applications/clientorion/gestionConnexion?action=connexion&codealliance=' + account)
		while abtronics.IE.Busy: sleep(1)
	if show_panel: abtronics.__main__()
def set_file():
    file_name = None
    while(file_name == None):
        file_name = easygui.enterbox("Please enter the new name convention for the files' naming.", "Name convention")
        if file_name == None:
            if easygui.ccbox("Are you sure that you want to stop the scrip's execution?", "Please confirm"):
                sys.exit(0)
            else:
                continue
        if file_name == "":
            easygui.msgbox("You did not specified a name convention for the files' naming. Please do so!", "Attention!")
            file_name = None
    print("Chosen name convention: %s" % file_name)
    return file_name
Exemple #54
0
def alarm_clock():

	hours = float(easygui.enterbox(msg='Please enter the hours: 0 to 23', title='Hours', default='23'))

	if hours < 0 or hours > 23:
		print "Invalid value for hours, should be >= 0 or <=23"
		sys.exit(1)

	minutes = float(easygui.enterbox(msg='Please enter the minutes: 0 to 60', title='Minutes', default='59'))

	if minutes < 0 or minutes > 59:
		print "Invalid value for minutes, should be >= 0 or <=59"
		sys.exit(1)

	now_hour = time.strftime("%H")
	now_min = time.strftime("%M")
	now_sec = time.strftime("%S")

	if float(now_hour) != hours or float(now_min) != minutes:
		min_hours = (hours - float(now_hour))
		min_mins = minutes - float(now_min)
		total = (min_hours*60) + min_mins
		sec = (total * 60) - float(now_sec)

		if min_mins == 1:
			unit_word = "minute"
		else:
			unit_word = "minutes"
	
		if total > 0:
			if total < 60:
				print "Sleeping for", int(total), unit_word
			else:
				print "Sleeping for", int(min_hours), "hours and", int(min_mins), unit_word
			sleep(sec)
			alarm()
			msg = "Click \"Continue\" to snooze for 10 minutes"
			title = "J.A.R.V.I.S"
			if easygui.ccbox(msg, title):
				print "Snoozing for 10 minutes"
				mixer.music.stop()
				sleep(600)
				alarm()
			else:
				for i in range(5):
					print "Alarm ringing!!", chr(7)
					sleep(1)
def main():
	dir_name = str(easygui.diropenbox(title="please choose contacts folder"))
	dict = {
			"01([2|7|8]{1})([0-9]{7})(\r|\n)$": r"012\1\2\3",
			"01([0|9|6]{1})([0-9]{7})(\r|\n)$": r"010\1\2\3",
			"01([1|4]{1})([0-9]{7})(\r|\n)$": r"011\1\2\3",
			"0150([0-9]{7})(\r|\n)$": r"0120\1\2",
			"0151([0-9]{7})(\r|\n)$": r"0101\1\2",
			"0152([0-9]{7})(\r|\n)$": r"0112\1\2"
			}
	if dir_name != 'None' :
		msg = "Are you sure you wanna update cellphone numbers in " + dir_name
		title = "Please Confirm"
		if easygui.ccbox(msg, title):
			for key in dict:
				replace_vcf(key, dict[key], dir_name)
			easygui.msgbox("Contacts have been updated successfully :) ")
		else:
			sys.exit(0)
	else:
		sys.exit(0)
Exemple #56
0
def fetchTut():
  # URL mods
  title = 'fetching tutorials'
  msg = '\tBy default, the program fetches tutorials from:\n'+ url + '\nContinue with this URL?'

  if eg.ccbox(msg, title, choices=('C[o]ntinue', '[N]o. Let me change it')):
    url = defURL
  else:
    url = fetch.initURL()

  # get response
  response = fetch.fetchURL(url)

  if not fetch.checkBackup(tutPklFilePath):
    tutPklFilePath = fetch.makeListTC(tutPklFilePath)

  tutList = fetch.getBackupPK(tutPklFilePath)

  title = 'fetch complete.'
  msg = 'Available tutorials have been fetched.'
  eg.msgbox(msg, title)
    # show image 
    else:
        PIL_img.save("gmap.png", "PNG") # save as png image in disk
        image_name="gmap.png"
        return image_name
        
        

if __name__ == '__main__':
    is_url_given=False 
    url=""
    title="IP Expose"
    easygui.msgbox("Welcome to IP Expose", title, image=show_image)
    msg = "Are you ready to begin Decrepifying?"
    
    if easygui.ccbox(msg, title,image=show_image):     # show a Continue/Cancel dialog
        pass  # user chose Continue
    else:  # user chose Cancel
        sys.exit(0)
    while is_url_given != True :
        url=easygui.enterbox("Enter URL , Press OK and Wait...", title, default='', strip=True, image=show_image, root=None)
        if url==None:
            sys.exit(0)
        if url !="" :
            is_url_given=True
            try:
                ipaddress=socket.gethostbyname(url)
            except:
                easygui.msgbox("Entered url can not be processed \nCheck the network connection."+
                               "\n Or the url is either not correct or not available."+"\n \n Try again after sometime","ERROR")
                sys.exit(0)
        g.msgbox('you choose the game1 is the best one!')
    if str(goodgame) == 'game2':
        g.msgbox('you choose the game2 is the best one!')
    if str(goodgame) == 'game3':
        g.msgbox('you choose the game3 is the best one!')

    index1 = g.indexbox('indexboxtest','indexibox',('yes','no'))
    if index1 == 0:
        g.msgbox('indexbox choose yes')
    if index1 == 1:
        g.msgbox('indexbox choose no')
        

    a = g.multchoicebox('multchoicebox test','multchoicebox',['game1','game2','game3','game4'])
    if a == None:
        print(a)
        a = ['meiyou']
        print(type(a))
    try:
        b = list(g.multchoicebox('multchoicebox test','multchoicebox',a))
    except:
        g.exceptionbox()
    
    
    if g.ccbox('continue the game?','please choose'):
        pass
    else:
        sys.exit(0)

input('please input any key to continue:')
def process(PA):
	global ActiveWindow, Shapes, Word, TRs_all, xl, Visio
	global RESULTS
	try:

		# ouvrir le fichier excel et faire les initialisations de coutume
		xl = CreateObject("Excel.application")
		xl.Visible = False
		xl.DisplayAlerts = False
		wb = xl.Workbooks.Open(PA)
		wb.Sheets("synoptique-bilan µmodules").Select()

		# dans la sheet visée, détecter tout les objets OLE (qui seront 
		# normalement tous des déssins visio)
		OLEObjects = wb.Sheets("synoptique-bilan µmodules").OLEObjects()

		# pour chaque déssin ...
		for OLEObject in OLEObjects:
			# l'ouvrir dans Visio
			OLEObject.Verb(2)
			# prendre la main sur la fenêtre visio ouverte
			Visio = GetActiveObject("Visio.Application")
			# Visio.Visible = False
			Visio.DisplayAlerts = False
			ActiveWindow =  Visio.ActiveWindow
			Page = ActiveWindow.Page
			Shapes = Page.Shapes

			msg = "Voulez confirmer le nombre de PBs après chaque sélection?\n" \
						+ "(si c'est plan assez complexe mieux vaut répondre par oui)"
			yn = ynbox(msg)

			# allons-y!
			# On extrait d'abord les infos d'entête
			for shape in Shapes:
				text = shape.Text
				if text.startswith('NRO'):
					bloc_NRO = text
				elif text.startswith('PT'):
					try:
						blocs_PT.append(shape)
					except:
						blocs_PT = [shape]
				elif text.startswith('PA'):
					PA_posx = get_XY(shape)[0]
			if get_XY(blocs_PT[0])[0] > get_XY(blocs_PT[1])[0]:
				FI_bloc = blocs_PT[0]
				PA_bloc = blocs_PT[1]
			else:
				PA_bloc = blocs_PT[1]
				FI_bloc = blocs_PT[0]
			PA_PT = PA_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			PMZ_PT = FI_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			CH = PA_bloc.Text.rsplit('\n')[2].replace('CH: ', '')
			NRO = extract('NRO/PMZ/PA', bloc_NRO, 'NRO')
			ADRESSE1 = ' '.join(PA_bloc.Text.rsplit('\n')[3:5])\
									.replace('Adresse: ', '')
			ADRESSE2 = ADRESSE1.rsplit('-')[0]

			TRs = {}
			empty_TRs = []
			# là ça va barder!
			for shape in Shapes:
				if shape.Text.startswith('TR'):
					if get_XY(shape)[0] > PA_posx:
						TR_TXT = str(shape.Text.encode()).replace("b'", '').replace("'", '')
						TR = TR_TXT.rsplit('FO')[0] \
							.replace('\\n', ' ') + 'FO'
						if not re.match(r'TR\s+\d{2}\s+\d{4}\s+\d+FO', TR):
							empty_TRs.append(shape.ID)
							continue
						if TR not in TRs:
							TRs[TR] = {
								'LONG': 0,
								'SHAPES': [shape.ID],
								'CH/IMB/AP': [],
								'PTs': [],
								'maxPT': 0
								}
						else:
							TRs[TR]['SHAPES'].append(shape.ID)
						try:
							TR_LONG = int(TR_TXT.rsplit('\\xe2\\x80\\x93 ')[1] \
															.replace('m', ''))
						except:
							TR_LONG = 0
						TRs[TR]['LONG'] = TRs[TR]['LONG'] + TR_LONG
			
			title1 = 'Sélectionnez les bloc'
			title2 = 'Confirmez la sélection'
			for TR in TRs:
				while True:
					SelectShapes(TRs[TR]['SHAPES'])
					if ccbox(TR, title1):
						CH_OR_IMB_OR_AP_all = []
						PTs = []
						msg = "Pour " + TR + "\nVous avez sélectionné:\n"
						selected_PBs = 0
						yn_yes = True
						for selected in ActiveWindow.Selection:
							try:
								TEXT = str(selected.Text)
								if not TEXT.startswith('PB'):
									continue
								selected_PBs = selected_PBs + 1
								PT = TEXT.rsplit('\n')[2]
								ADR = TEXT.rsplit('\n')[3]
								CH_OR_IMB_OR_AP = TEXT.rsplit('\n')[4]
								if (not CH_OR_IMB_OR_AP.startswith('AP ')
										and not CH_OR_IMB_OR_AP.startswith('Ch.')
										and not CH_OR_IMB_OR_AP.startswith('IMB')):
									SelectShapes([selected.ID])
									msgbox("T'as surement encore fais une connerie dans tes"
												+ "déssins, regarde ce bloc dans la ligne PT!\n"
												+ "Je devrais trouver Ch.XXXX ou AP XXXX"
												+ "ou IMB/XXXX/XXX mais j'ai trouvé\n"
												+ CH_OR_IMB_OR_AP + "\n"
												+ "Quand t'auras détécté l'erreur click sur OK")
									cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
									if not cont:
										exit(0)
									else:
										pass
								else:
									msg = msg + "- " + CH_OR_IMB_OR_AP + "\n"
									CH_OR_IMB_OR_AP_all.append([ADR, CH_OR_IMB_OR_AP])
									PTs.append(int(PT.replace('PT', '')))
							except:
								SelectShapes([selected.ID])
								msgbox("T'as surement encore fais une connerie dans tes"
									+ "déssins, regarde ce bloc dans la ligne PT!\n"
									+ "Quand t'auras détécté l'erreur click sur OK")
								cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
								if not cont:
									exit(0)
								else:
									msg = msg + "(RIEN!)"
									CH_OR_IMB_OR_AP_all = []
									PTs = []
									yn_yes = False
						if not selected_PBs:
							cont = boolbox("Tu n'as rien sélectionné! Tu confirmes"
															+ " que ce n'est pas une connerie?",
															"Sélection vide!",
															['Oui vas-y', 'Comme d\'hab! Une connerie'])
							if cont:
								break
							else:
								continue
						if yn and yn_yes:
							msg = msg + "(" + str(selected_PBs) + " sélectionnés)"
							conf = boolbox(msg, title2, ['Confirmer?', 'Refaire?'])
							if conf:
								TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
								TRs[TR]['PTs'] = PTs
								break
							else:
								pass
						else:
							TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
							TRs[TR]['PTs'] = PTs
							break
					else:
						exit(0)
				if len(TRs[TR]['PTs']):
					TRs[TR]['maxPT'] = 'DE_PT%06d' % max(TRs[TR]['PTs']) + '.doc'
				else:
					TRs[TR]['maxPT'] = 'je_ne_suis_pas_cense_exister.doc'
			if TRs == {}:
				msgbox("il n'y pas de TR valide sur ce déssin")
			TRs_all.append(TRs)
			Visio.Visible = False

		RESULTS[PA] = {
			'TRs_all': 	TRs_all,
			'NRO':			NRO,
			'PMZ_PT':		PMZ_PT,
			'PA_PT':		PA_PT,
			'CH':				CH,
			'ADRESSE1':	ADRESSE1,
			'ADRESSE2':	ADRESSE2,
			'DATE':			DATE
		}
		xl.Quit()
		return

	except:
		print(format_exc())
		codebox("t'as encore fais une connerie! Fais moi un screen de malheur!",
						"Erreur",
						format_exc())
		going()
savedate = datetime.strftime(datetime.now(),'%m-%d-%y') #made DT format similar to data system format
savedir = 'C:/OESdata/' + process + ' ' + savedate + '/'
runToday = False
folders = os.listdir('C:/OESdata/')
for folder in folders:
    if re.search(savedate,folder):
        runToday = True
        savedir = 'C:/OESdata/' + folder + '/'
        print savedir
        process = re.search('([BP][EC])',folder).group(1)
        print process

if todaysRun == False and runToday:
    msg = "Use today's run?"
    title = "Use today's run?"
    todaysRun = eg.ccbox(msg, title, choices = ('yes','choose another run'))

if not todaysRun:
    if not os.path.isdir('C:/OESdata/'):
        default = 'Y:/Nate/new MC02 OES program/backup from MC02 computer/data'
    else:
        default = 'C:/OESdata/'
    savedir = eg.diropenbox(msg = 'choose a directory to load data from', title = 'load OES data', default = default)
    try:
        runNum = savedir[-5:].strip('0')
    except Exception as e:
        print 'could\'t get run number from save directory'
        print e
    for f in glob.iglob(savedir + '\\' + '*.csv'):
        if re.search('OES signals', f):
            dataFile = f