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编码转换到系统编码输出
    def _run_tblastn(self):
        self._get_run_id()
        # Organism file has to be closed to be used by the tblastn.
        # So we have to clean it up manually. The results file though we can
        # have cleaned up automatically.
        (orgf, orgfname) = self._createTemporaryFile(delete=False)
        (resf, resfname) = self._createTemporaryFile(delete=False)
        orglist = getOrganismsInClusterRun(self.accumulated_data['runid'], self.sqlite_cursor)
        orgids = []
        for org in orglist:
            orgid = organismNameToId(org, self.sqlite_cursor)
            orgf.write(orgid + "\n")
        orgf.close()
        sys.stderr.write("Now running the tblastn wrapper (this could take some time...)\n")
#        f1 = subprocess.Popen([ "echo", self.accumulated_data['ITEP_id'] ], stdout=subprocess.PIPE)
#        f2 = subprocess.Popen(["db_TBlastN_wrapper.py", "-f", orgfname, "-r", "1" ], stdin=f1.stdout, stdout=resf)
#        f1.stdout.close()
#        f2.communicate()
        cmd = "echo '%s' | db_TBlastN_wrapper.py -f %s -r 1 > %s" %(self.accumulated_data['ITEP_id'], orgfname, resfname)
        print cmd
        os.system(cmd)
        tblastn_results = [ line.strip("\r\n").split("\t") for line in resf ]
        tblastn_results.insert(0, self._tblastnHeader())
        text = self._print_readable_table(tblastn_results, header=True)
        easygui.codebox(text=text)
        output_file = self._save_file_dialogs(extension="txt")
        if output_file is not None:
            self._save_text(text, output_file)
            self._success_dialog(output_file)      
        # Clean up temp files
        os.remove(orgfname)
        os.remove(resfname)
        return True
def main():
	# Check to see if we have all the information we need
	try:
		#directory = unicode(sys.argv[1])
		directory = sys.argv[1]
		template = sys.argv[2]
	except IndexError:
		try:
			import easygui
			
			# get directory from user
			directory = None
			while not directory:
				directory = easygui.diropenbox('Where are the files?')
			
			# get template from user
			template = None
			while not template:
				template = easygui.choicebox('What template do you want?', choices=os.listdir(absolute_path('templates')))
		except ImportError:
			sys.stderr.write("Usage: " + sys.argv[0] + " <directory> <template>\n")
			exit()
	
	root = Folder(directory)
	root.scan()
	
	env = Environment(loader=PackageLoader('bxt_description_generator', 'templates'))
	env.filters['cleanify'] = cleanify
	template = env.get_template(template)
	output = template.render(root=root).encode("utf-8")
	
	try:
		easygui.codebox(text=output)
	except NameError:
		print output
    def _run_tblastn(self):
        self._get_run_id()
        # Organism file has to be closed to be used by the tblastn.
        # So we have to clean it up manually. The results file though we can
        # have cleaned up automatically.
        (orgf, orgfname) = self._createTemporaryFile(delete=False)
        (resf, resfname) = self._createTemporaryFile(delete=False)
        orglist = getOrganismsInClusterRun(self.accumulated_data['runid'], self.sqlite_cursor)
        orgids = []
        for org in orglist:
            orgid = organismNameToId(org, self.sqlite_cursor)
            orgf.write(orgid + "\n")
        orgf.close()
        sys.stderr.write("Now running the tblastn wrapper (this could take some time...)\n")
#        f1 = subprocess.Popen([ "echo", self.accumulated_data['ITEP_id'] ], stdout=subprocess.PIPE)
#        f2 = subprocess.Popen(["db_TBlastN_wrapper.py", "-f", orgfname, "-r", "1" ], stdin=f1.stdout, stdout=resf)
#        f1.stdout.close()
#        f2.communicate()
        cmd = "echo '%s' | db_TBlastN_wrapper.py -f %s -r 1 > %s" %(self.accumulated_data['ITEP_id'], orgfname, resfname)
        print cmd
        os.system(cmd)
        tblastn_results = [ line.strip("\r\n").split("\t") for line in resf ]
        tblastn_results.insert(0, self._tblastnHeader())
        text = self._print_readable_table(tblastn_results, header=True)
        easygui.codebox(text=text)
        output_file = self._save_file_dialogs(extension="txt")
        if output_file is not None:
            self._save_text(text, output_file)
            self._success_dialog(output_file)      
        # Clean up temp files
        os.remove(orgfname)
        os.remove(resfname)
        return True
Exemple #5
0
def load_file(filename):

    pd_csv = pd.read_csv(filename)

    # initialize list for GRB objects
    GRB_list = []

    # run through list containing lines read from file
    for line in pd_csv.values:
        # split csv and assign to corresponding variables
        ID, dtX, dtO, dt, BetaX, SigmaX_u, SigmaX_l, BetaOX, SigmaOX_u, SigmaOX_l = line
        # create and append GRB object from file contents
        GRB_list.append(
            GRB(ID, dtX, dtO, dt, BetaX, SigmaX_u, SigmaX_l, BetaOX, SigmaOX_u,
                SigmaOX_l, "", ""))

    GRB_counter = len(GRB_list)

    easygui.codebox(
        msg="Total number of lines (or number of GRBs) read from file: " +
        str(len(pd_csv)) + "\nTotal number of GRBs in list: " +
        str(GRB_counter
            ),  # notify user of total number of lines read from file
        title="File contents",
        text=pd_csv.to_string())  # display formatted data table

    # return list of GRB objects
    return GRB_list
Exemple #6
0
def genre():
    '''
    This function adds all genre-matched movies to pandas dataframe,
    alter the dataframe for correct easygui display by dropping some 
    columns, resetting df index, merging df's and sorting movies to display
    only movies rated >= 2.5 , it also casts the final df columns to lists
    and rearrange them in a numpy array for easygui display.  
    '''

    # append genre matched movies as dataframe object
    final_1 = []
    for i in final:
        final_1.append(df_movies.loc[df_movies['genres'].isin(i)])

    # reset df index, drop index columns as well as duplicate entries
    lst = final_1[0]
    lst = lst.reset_index()
    lst.drop('index', axis=1, inplace=True)
    lst.drop('title', axis=1, inplace=True)
    lst.drop('genres', axis=1, inplace=True)
    lst = lst.drop_duplicates(subset='movieId')

    # merge movieId with movie names, rating and genres + drop index, title and genres column
    df = pd.merge(lst, df_1, on='movieId', how='left')

    # sort movies by ratings, display only movies rated above or = 2.5 rating
    data = df.sort_values(by='rating', ascending=False)
    data.drop('movieId', axis=1, inplace=True)
    data = data[data['rating'] >= 2.5]
    heading = []  # add column names as first dataframe row for easygui display
    heading.insert(
        0, {
            'rating': 'Rating',
            'title': '----------Title',
            'genres': '----------Genre'
        })
    data = pd.concat([pd.DataFrame(heading), data],
                     ignore_index=True,
                     sort=True)

    # casting dataframe columns to lists
    rating = data['rating'].tolist()
    title = data['title'].tolist()
    genres = data['genres'].tolist()

    # compiling numpy array from dataframe column lists for easygui display
    data = np.concatenate(
        [np.array(i)[:, None] for i in [rating, title, genres]], axis=1)
    data = str(data).replace('[', '').replace(']', '')

    # displaying matched movies to user
    gui.codebox(msg='Movies filtered by genre returned from database:',
                text=(data),
                title='Movies')

    which_way()
Exemple #7
0
def secimekrani():
    try:
        yemek = easygui.choicebox(msg="Seçim yapın.", title="Seçim Ekranı", choices=obf.Meals.meals)
    except:
        easygui.exceptionbox()

    try:
        easygui.codebox(msg="Tarife göz atın.", title="Tarif Ekranı", text=obf.Recipes.recipes[str(yemek[:4])])
    except:
        easygui.exceptionbox()
 def _get_similar_genes(self, blastn=False):
     blastres = getBlastResultsContainingGenes( [ self.accumulated_data['ITEP_id'] ], self.sqlite_cursor, blastn=blastn )
     blastres.insert(0, self._blastHeader())
     text = self._print_readable_table(blastres, header=True)
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="txt")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
 def _get_similar_genes(self, blastn=False):
     blastres = getBlastResultsContainingGenes( [ self.accumulated_data['ITEP_id'] ], self.sqlite_cursor, blastn=blastn )
     blastres.insert(0, self._blastHeader())
     text = self._print_readable_table(blastres, header=True)
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="txt")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
Exemple #10
0
def Showanswer(grid):
	Answer = ''
	for cell in range(81):
		if cell%9 == 0:
			if cell != 0:
				Answer += '\n'
			Answer += 'Line %s >> |' % (cell/9)
		Answer += str(grid[cell][0])
		Answer += '|'
	gui.codebox('This should be the solution', 'Answer', Answer)
	exit()
 def _get_cluster_blast(self):
     clusterid = self._getClusterId()
     genelist = getGenesInCluster(self.accumulated_data['runid'], clusterid, self.sqlite_cursor)
     blast = getBlastResultsBetweenSpecificGenes(genelist, self.sqlite_cursor)
     blast.insert(0, self._blastHeader())
     text = self._print_readable_table(blast, header=True)
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="txt")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
Exemple #12
0
def ifconfigg():
    if sys.platform == "win32":
        a = subprocess.check_output("ipconfig /all",
                                    stderr=subprocess.STDOUT,
                                    shell=True)
    else:
        a = subprocess.check_output("ifconfig",
                                    stderr=subprocess.STDOUT,
                                    shell=True)
    easygui.codebox(msg="Ifconfig information",
                    title="IFCONFIG/IPCONFIG",
                    text=a)
 def getDismiss(self):
     try:
         data = self.Fun.getTobeDismissed()
         result = "  id   name"
         if data:
             for each in data:
                 result += "\n" + "  ".join(each)
         else:
             result = "None"
         easygui.codebox(msg="Results:", title="Result", text=result)
     except:
         easygui.exceptionbox()
 def _get_cluster_geneinfo(self):
     clusterid = self._getClusterId()
     genelist = getGenesInCluster(self.accumulated_data['runid'], clusterid, self.sqlite_cursor)
     geneinfo = getGeneInfo(genelist, self.sqlite_cursor)
     geneinfo.insert(0, self._geneInfoHeader())
     text = self._print_readable_table(geneinfo, header=True)
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="txt")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
def display(header, results):
    """
    Display header string and list of result lines
    """
    if displayer == 'easygui':
        title = 'Waveform properties'
        easygui.codebox(header, title, '\n'.join(results))
    else:
        print('No EasyGUI; printing output to console\n')
        print(header)
        print('-----------------')
        print('\n'.join(results))
Exemple #16
0
def display(header, results):
    """
    Display header string and list of result lines
    """
    if displayer == 'easygui':
        title = 'Waveform properties'
        easygui.codebox(header, title, '\n'.join(results))
    else:
        print 'No EasyGUI; printing output to console\n'
        print header
        print '-----------------'
        print '\n'.join(results)
 def _get_cluster_geneinfo(self):
     clusterid = self._getClusterId()
     genelist = getGenesInCluster(self.accumulated_data['runid'], clusterid, self.sqlite_cursor)
     geneinfo = getGeneInfo(genelist, self.sqlite_cursor)
     geneinfo.insert(0, self._geneInfoHeader())
     text = self._print_readable_table(geneinfo, header=True)
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="txt")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
 def _get_cluster_blast(self):
     clusterid = self._getClusterId()
     genelist = getGenesInCluster(self.accumulated_data['runid'], clusterid, self.sqlite_cursor)
     blast = getBlastResultsBetweenSpecificGenes(genelist, self.sqlite_cursor)
     blast.insert(0, self._blastHeader())
     text = self._print_readable_table(blast, header=True)
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="txt")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
Exemple #19
0
 def show_for_user(self):
     report_file = f'Analizator report {time.strftime("%m%d%H%M%S")}.txt'
     try:
         with open(report_file, 'w') as data_file:
             data_file.write(
                 '\t*This file will be delete when you close window!*\n\n')
             data_file.write(self.text)
         os.system(f"notepad.exe {report_file}")
         os.remove(report_file)
     except:
         if os.path.exists(report_file):
             os.remove(report_file)
         easygui.codebox('Result', 'That is what I found', self.text)
def Choice_Run_Tabanalys():
    #Run Tabanalys and clean into CSV file
    now = datetime.datetime.now()
    TabAnalysFile = PilotApp.Settings['EpicorDBDir'] + r'\TabAnalys.tmp'
    TabCSVFile = PilotApp.Settings['EpicorDBDir'] + r'\TabAnalys ' + str(now.year) + '-' + str(now.month) + '-' + str(now.day) + '.csv'
    easygui.msgbox('This may take a few, please be patient.')
    Command(PilotApp.Settings['OpenEdgeDir'] + r'\bin\proutil.bat ' + PilotApp.Settings['EpicorDBDir'] + '\\' + PilotApp.Settings['Database Name'] + ' -C tabanalys > ' + TabAnalysFile).run()
    #print PilotApp.Settings['OpenEdgeDir'] + '\\bin\\proutil.bat ' + PilotApp.Settings['EpicorDBDir'] + '\\' + PilotApp.Settings['Database Name'] + ' -C tabanalys > ' + TabAnalysFile
    tabtmp = open(TabAnalysFile)
    tabcontents = tabtmp.readlines()
    easygui.codebox('Contents','Contents',tabcontents)
    tabtmp.close()
    CleanTabAnalys(TabAnalysFile,TabCSVFile)
    easygui.msgbox('Saved csv (w/ headers) file to ' + TabCSVFile)
 def _get_presence_absence_table(self):
     (pa_file, pa_fname) = self._createTemporaryFile(delete=True)
     cluster = self._getClusterId()
     cmd = 'db_getPresenceAbsenceTable.py -r %s -c %s > %s 2> /dev/null' %(self.accumulated_data['runid'], cluster, pa_fname)
     print cmd
     os.system(cmd)
     pa_table = [ line.strip('\r\n').split('\t') for line in pa_file ] 
     text = self._print_readable_table(pa_table)
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="txt")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
 def _make_crude_alignment(self):
     (aln_file, aln_fname) = self._createTemporaryFile(delete=True)
     cluster = self._getClusterId()
     cmd = 'makeTabDelimitedRow.py %s %s | db_makeClusterAlignment.py -m mafft_linsi -n | Gblocks_wrapper.py | db_replaceGeneNameWithAnnotation.py -a -o > %s 2> /dev/null' \
         %(self.accumulated_data['runid'], cluster, aln_fname)
     print cmd
     os.system(cmd)
     text = ''.join( [ line for line in aln_file ] )
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="fasta")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
def display_req_response(sql_cmd, response, gui=False):
	error_sql = response['error_sql']
	print_ = ''
	if error_sql:
		print_ = print_ + 'error_sql: ' + error_sql + '\n'
		if gui:
			codebox('Commande: ' + sql_cmd, 'Erreur', print_)
		else:
			print(print_)
	else:
		if gui:
			codebox('Commande: ' + sql_cmd, 'Résultat', print_)
		else:
			print(prettify_sql_response(response))
 def _make_crude_alignment(self):
     (aln_file, aln_fname) = self._createTemporaryFile(delete=True)
     cluster = self._getClusterId()
     cmd = 'makeTabDelimitedRow.py %s %s | db_makeClusterAlignment.py -m mafft_linsi -n | Gblocks_wrapper.py | db_replaceGeneNameWithAnnotation.py -a -o > %s 2> /dev/null' \
         %(self.accumulated_data['runid'], cluster, aln_fname)
     print(cmd)
     os.system(cmd)
     text = ''.join([line for line in aln_file])
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="fasta")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
 def getstu():
     mode = sel.get()
     value = key.get()
     try:
         data = self.Fun.getStuInfo(value, mode)
         if data:
             result = '   id     name   dept   gender birthday'
             for each in data:
                 result += "\n" + "  ".join(each)
         else:
             result = "None"
         easygui.codebox(msg="Results:", title="Result", text=result)
     except:
         easygui.exceptionbox()
Exemple #26
0
def friendly_failure(failure_message=None):
    if running_mode() == RunningMode.gui:
        try:
            yield
        except Exception:
            if failure_message is None:
                failure_message = "An error occurred running {0}!".format(
                    os.path.basename(sys.argv[0]))
            failure_message += (
                "\nThe following might be helpful to report to someone, "
                "or provide a clue about how to fix it:\n\n")
            easygui.codebox(msg=failure_message, text=traceback.format_exc())
    else:
        yield
 def _get_presence_absence_table(self):
     (pa_file, pa_fname) = self._createTemporaryFile(delete=True)
     cluster = self._getClusterId()
     cmd = 'db_getPresenceAbsenceTable.py -r %s -c %s > %s 2> /dev/null' %(self.accumulated_data['runid'], cluster, pa_fname)
     print cmd
     os.system(cmd)
     pa_table = [ line.strip('\r\n').split('\t') for line in pa_file ] 
     text = self._print_readable_table(pa_table)
     easygui.codebox(text=text)
     output_file = self._save_file_dialogs(extension="txt")
     if output_file is not None:
         self._save_text(text, output_file)
         self._success_dialog(output_file)
     return True
Exemple #28
0
    def encode():
        global number
        global file
        global problem
        try:
            if inputt == "normal":
                ans = raw_input("Encode text: ")
            elif inputt == "gui":
                ans = easygui.codebox(msg="Enter text", title="Text encoding")
            else:
                problem = "Wrong mode. Check your input"
                help()
            f = open(file, "w")
            f.close()
            text = "q!!!!!!!!@@@@@@@#######%wer%t%yuio%p%as%lkd%jg%hz%m*x*n*c*b*vQWERTYUIOPAL*SK%DJFHG#ZM@XNC!BV1234567890"
            a = ans.split()
            f = open(file, "a")
            os.system("clear")
            print("\n[+] [MESSAGE]\n")
            time.sleep(3)
            for g in a:
                b = g.split()
                for p in g:
                    for i in xrange(number):
                        q = random.choice(text)
                        print '\033[93m%s\033[0m' % q,
                        f.write(q)
                    print '\033[91m%s\033[0m' % p,
                    f.write(p)

            for i in xrange(number):
                q2 = random.choice(text)
                print "\033[93m%s\033[0m" % q2,
                f.write(q2)
            f.close()
            l = ""
            if "-eb" in sys.argv[-1]:
                f = open(file, "r").read()
                f2 = base64.b64encode(f)
                fil = open(file, "w")
                fil.write(f2)
                fil.close()
                l = " -->base64"
            print("\n----------------------")
            fi = open(file, "r").read()
            print("\n\n[+] Saving encoded message%s\n" % l)
            time.sleep(3)
            print(str(fi))
            time.sleep(2)
            print("\n[+] Output stored at %s" % file)
            print("   - Number: %d" % number)
            print("   - Size  : %sb" % os.path.getsize(file))
            print("   - Length: %d" % len(str(fi)))
            sys.exit()
        except KeyboardInterrupt:
            print("\nInterrupted by User")
            sys.exit()
        except OverflowError:
            problem = "Just too much. Please enter smaller number"
            help()
 def getTeached(self):
     fieldNames = ["Student ID:"]
     values = []
     values = easygui.multenterbox("Enter Student ID:", "get Average Score",
                                   fieldNames)
     try:
         data = self.Fun.getTeached(values[0])
         result = "  Tid   Tname"
         if data:
             for each in data:
                 result += "\n" + "  ".join(each)
         else:
             result = "None"
         easygui.codebox(msg="Results:", title="Result", text=result)
     except:
         easygui.exceptionbox()
Exemple #30
0
def MostrarReservas():
    msg = "Bem Vindo ao Air Civil/UFSCar"
    title = "Air Civil UFSCar - Reserva de Assentos"

    text = ''
    for i in range(0, 10):
        text = text + "Fila " + str(i) + "-->"
        for j in range(0, 4):
            if (i % 2) == 0:
                text = text + str(j) + "(X) "
            else:
                text = text + str(j) + "( ) "

            if (j == 1):  #corredor
                text = text + "  "
        text = text + "\n"

    gui.codebox(msg, title, text)
Exemple #31
0
def Choice_Run_Tabanalys():
    #Run Tabanalys and clean into CSV file
    now = datetime.datetime.now()
    TabAnalysFile = PilotApp.Settings['EpicorDBDir'] + r'\TabAnalys.tmp'
    TabCSVFile = PilotApp.Settings['EpicorDBDir'] + r'\TabAnalys ' + str(
        now.year) + '-' + str(now.month) + '-' + str(now.day) + '.csv'
    easygui.msgbox('This may take a few, please be patient.')
    Command(PilotApp.Settings['OpenEdgeDir'] + r'\bin\proutil.bat ' +
            PilotApp.Settings['EpicorDBDir'] + '\\' +
            PilotApp.Settings['Database Name'] + ' -C tabanalys > ' +
            TabAnalysFile).run()
    #print PilotApp.Settings['OpenEdgeDir'] + '\\bin\\proutil.bat ' + PilotApp.Settings['EpicorDBDir'] + '\\' + PilotApp.Settings['Database Name'] + ' -C tabanalys > ' + TabAnalysFile
    tabtmp = open(TabAnalysFile)
    tabcontents = tabtmp.readlines()
    easygui.codebox('Contents', 'Contents', tabcontents)
    tabtmp.close()
    CleanTabAnalys(TabAnalysFile, TabCSVFile)
    easygui.msgbox('Saved csv (w/ headers) file to ' + TabCSVFile)
Exemple #32
0
def run():
    try:
        path_to_main = easygui.fileopenbox(
            'Input full path to Main.xaml of your project')
        if path_to_main:
            main = Main(path_to_main)
            main.declare_config()
            if main.config_exist:
                main.config_obj = Config(main.path_to_config)
                try:
                    main.config_obj.get_config(main.response)
                except Exception:
                    main.config_exist = False

            main.check_project()
            main.response.show_for_user()
    except Exception as e:
        easygui.codebox('Something was wrong', 'Check exception', str(e))
Exemple #33
0
	def ethcontr(self):
		# Set parameters for input box
		msg = "Enter details for connection to another computer"
		title = "Ethernet Controller"
		fieldNames = ["Computer IP", "User"]
		fieldValues = []
		fieldValues = easygui.multenterbox(msg, title, fieldNames)
		if fieldValues == None:
			return
		reply = easygui.passwordbox("Enter password")
		if reply == None:
			return	
	
		# Connect through SSH
		ssh = paramiko.SSHClient()
		ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		
		if (fieldValues[0] == "" or fieldValues[1] == ""):
			return
		
		ssh.connect(fieldValues[0], username=fieldValues[1], password=reply)
		
		while True:
			# Set parameters for query
			msg2 = "Enter command to run"
			title2 = "Connected to " + fieldValues[1] + "@" + fieldValues[0]
			fieldNames2 = ["Command"]
			fieldValues2 = []
			fieldValues2 = easygui.multenterbox(msg2, title2, fieldNames2)
			
			if (fieldValues2 == None or fieldValues2[0] == ""):
				break
			
			if cmp(fieldValues2[0], 'exit') == 0:
				break

			stdin, stdout, stderr = ssh.exec_command(fieldValues2[0])
			
			# Compose output
			output = ""
			for line in stdout:
				output = output + "\n" + line
			if output != "":	
				easygui.codebox("Command result", "Show result", output)
Exemple #34
0
    def ethcontr(self):
        # Set parameters for input box
        msg = "Enter details for connection to another computer"
        title = "Ethernet Controller"
        fieldNames = ["Computer IP", "User"]
        fieldValues = []
        fieldValues = easygui.multenterbox(msg, title, fieldNames)
        if fieldValues == None:
            return
        reply = easygui.passwordbox("Enter password")
        if reply == None:
            return

        # Connect through SSH
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        if (fieldValues[0] == "" or fieldValues[1] == ""):
            return

        ssh.connect(fieldValues[0], username=fieldValues[1], password=reply)

        while True:
            # Set parameters for query
            msg2 = "Enter command to run"
            title2 = "Connected to " + fieldValues[1] + "@" + fieldValues[0]
            fieldNames2 = ["Command"]
            fieldValues2 = []
            fieldValues2 = easygui.multenterbox(msg2, title2, fieldNames2)

            if (fieldValues2 == None or fieldValues2[0] == ""):
                break

            if cmp(fieldValues2[0], 'exit') == 0:
                break

            stdin, stdout, stderr = ssh.exec_command(fieldValues2[0])

            # Compose output
            output = ""
            for line in stdout:
                output = output + "\n" + line
            if output != "":
                easygui.codebox("Command result", "Show result", output)
Exemple #35
0
def main():
    forfun = os.getcwd()
    while 1 == 1:
        try:
            reply = easygui.enterbox(msg='Enter a word \nLowercase only!',
                                     title='Anti Adverb',
                                     strip=True)

            if reply in alist:
                easygui.msgbox(msg=reply + " is an adverb!",
                               title='Yes',
                               image='images/yes.png')

            elif reply == "":
                print("Error: Nothing Entered")  # restarts loop

            elif reply == "AntiAdverb":
                easygui.msgbox(
                    msg="Anti Adverb is a creation of the great SupaFresh! \n "
                    "Find me at https://github.com/SupaFresh \n Happy Writing! \n \n Version 1.0 \n 11/1/2018",
                    title="About Anti Adverb",
                    ok_button="That's Nice")

            elif reply == "killdata":
                sys.exit()  # closes program

            elif reply == "helptips":
                filename = forfun + "/TipsAndTricks.txt"
                f = open(filename, "r")
                text = f.readlines()
                f.close()
                easygui.codebox(filename, "Tips and Tricks", text)

            elif reply == "easygui":
                easygui.abouteasygui()  # Checks easygui version

            else:
                easygui.msgbox(msg=reply + " is NOT an adverb!",
                               title='No',
                               image='images/no.png')

        except Exception:  # Clicking cancel on enterbox exception/freezing
            sys.exit(1)  # solved by closing program silently on exception
Exemple #36
0
def isolate_ID(GRB_list, parsed_filename, user_defined_ID):

    # create list for GRB objects with user's ID of interest
    user_defined_ID_list = []
    # initialize counter for number of GRBs with user's ID of interest
    interest_counter = 0

    # run through list of GRB objects
    for a in GRB_list:
        # check if ID from full list of GRB objects matches the user's ID of interest
        if user_defined_ID == a.ID:

            # append GRB to list of GRB objects with user's ID of interest
            user_defined_ID_list.append(a)

    # check if no data point with user's ID of interest exists
    if len(user_defined_ID_list) > 0:
        # print out GRB object attributes for each GRB object in list of GRB objects with user's ID of interest
        easygui.codebox(
            msg=
            f"Found {len(user_defined_ID_list)} data points matching {user_defined_ID}.",
            title="Selected GRB data",
            text=pd.DataFrame([[
                l.ID, l.dtX, l.dtO, l.del_t, l.BetaX, l.upper_sigmaX,
                l.lower_sigmaX, l.BetaOX, l.upper_sigmaOX, l.lower_sigmaOX
            ] for l in user_defined_ID_list],
                              columns=[
                                  "ID Number", "\u0394t\u2093 [hr]",
                                  "\u0394t\u2092 [hr]", "\u0394t [hr]",
                                  "\u03B2\u2093", "\u03C3\u2093_Up",
                                  "\u03C3\u2093_Low", "\u03B2\u2092\u2093",
                                  "\u03C3\u2092\u2093_Up",
                                  "\u03C3\u2092\u2093_Low"
                              ]).to_string())
    else:
        # notify user that no data point exists for ID of interest
        easygui.msgbox("\nThere is no data point with GRB ID " +
                       user_defined_ID + " in file " + parsed_filename +
                       ".csv.  " + "Please try again.\n")

    # return list of optically dark bursts
    return user_defined_ID_list
Exemple #37
0
def decode():

    foto = easygui.fileopenbox(msg="Seleziona foto")
    f = open(foto, "rb").read()
    c = base64.encodebytes(f)
    o = easygui.codebox(c)
    os = easygui.textbox(o)
    scr = open("fll.txt", "w")  #crea doc.txt
    scr.write(str(os))
    scr.close()
    salva(scr)
Exemple #38
0
def main(args):
    """ main entry point """

    # set environment var for valid CA SSL cert
    if not OS.startswith('linux'):
        os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(get_script_dir(), "cacert.pem")

    mypath = getMyFile()
    if OS == "win32":
        toaster = win10toast.ToastNotifier()
        toaster.show_toast(
            "SciComp SSH Tester",
            "Testing ssh...",
            icon_path=mypath,
            duration=3,
            threaded=True) 
   
    test = ssh_exec_gss([args.host], ['srun hostname'])
    for t,std in test.items():
        easygui.codebox(' Output of command "%s":' % t,'Show Slurm Output',"\n".join(std[0].readlines()))
def msgStage2(offer, msg):
    """
		Genere un msg associé aux offres dans un codebox
	"""

    text = ""
    L = offer

    # Parcours les élements du dictionnaire
    for i in L:
        # La clée
        text += i + "\n"
        # Les valeurs
        if offer[i] is None:
            text += "None\n\n"
        else:
            text += offer[i] + "\n\n"

    # On affiche tout
    codebox(msg, "Stable Roommates Problem", text)
    return None
Exemple #40
0
def readme():
    """Parameters
       ----------
       None
           
       Returns
       -------
       readmepg
           Gui object containing README information
       """

    rdmsg = "py-decom Readme"
    rdtitle = "py-decom"
    rdtext = """
    py-decom

    What this program does:

    1. Looks at all of the approved and under consideration 
       Decommissioning [PDF] programmes on the OGA site.
    2. Saves them all to hard drive.
    3. Converts them to a fully searchable format.
    4. Searches them with user input search terms and outputs 
       a results file.
    5. Opens all the search files on user request.
    6. Searches all the downloaded files for recorded well numbers.

    Instructions:

    1. Download all the current Decom Programmes using the 
       'Download Programmes' button.
    2. Convert the files to searchable [.txt] format using the 
       'Convert Files' button.
    3. Search the Programme Files with term of your choice 
       using 'Search Programmes'.
    4. Open the returned files with the 'Open Files' button 
       [will open all associated search PDFs].
    5. Use 'Well Search' to return a list of all Well 
       references in the Programmes.

    The program will save and time/date-stamp all term & well 
    searches in a .txt format.

    All Programmes and converted files are stored in C:\OGA\Programmes
    All Term Search data is stored in C:\OGA\Reports
    All Well Search data is stored in C:\OGA\Wells

    The program is written with an easygui interface.

    For support contact [email protected]"""
    readmepg = gui.codebox(rdmsg, rdtitle, rdtext)
 def act(self):
     self.time += 1
     #人类玩家每下一个子之前画出棋盘
     if self.time == 1:
         image = 'tic.png'
         g.msgbox("您将进入井字棋游戏", image)
         msg = "选择您要下棋的位置"
         title = "井字棋游戏"
         image = 'tic.png'
         choices = ['q', 'w', 'e', 'a', 's', 'd', 'z', 'x', 'c']
         self.key = g.buttonbox(msg, title, choices, image)
         data = self.keys.index(self.key)
         i = data // int(BOARD_COLS)
         j = data % BOARD_COLS
         return (i, j, self.symbol)
     else:
         output = sys.stdout
         outputfile = open('tic.txt', "w")
         sys.stdout = outputfile
         self.state.print_state()
         outputfile.flush()
         # sys.stdout = outputfile
         type = sys.getfilesystemencoding()  # python编码转换到系统编码输出
         f = open('tic.txt', 'r')
         msg = ("您的选择是" + str(self.key), "结果")
         title = "tic_tac_toe"
         text = f.read()
         g.codebox(msg, title, text)
         f.close()
         msg = "选择您要下棋的位置"
         title = "井字棋游戏"
         image = 'tic.png'
         choices = ['q', 'w', 'e', 'a', 's', 'd', 'z', 'x', 'c']
         self.key = g.buttonbox(msg, title, choices, image)
         data = self.keys.index(self.key)
         i = data // int(BOARD_COLS)
         j = data % BOARD_COLS
         return (i, j, self.symbol)
def msgStage(D, msg):
    """
		Genere un msg associé à un dictionnaire des preferences dans un codebox
	"""

    text = ""
    L = sorted(D.keys())

    # Parcours les élements du dictionnaire
    for i in L:
        # La clée
        text += i + "\n"
        # Les valeurs
        if D[i] is None:
            text += "None\n\n"
        else:
            for j in range(len(D[i]) - 1):
                text += D[i][j] + " - "
            text += D[i][-1]
            text += "\n\n"

    # On affiche tout
    codebox(msg, "Stable Roommates Problem", text)
    return None
Exemple #43
0
def askQueryCode():  #Prompts the user to enter the query as code
    msg = "Columns, Operators and SearchTerms have to be encapsulated in quotes \"\". Numbers do not.\nLogical operators : $and $not $or $nor\nFind query code example : { \"Column\" : { \"$queryType\" : \"searchTerm\" }}"
    while 1:
        queryCode = eg.codebox(msg, title)
        if queryCode is None:
            quit()
        elif re.search(isodateRegex, queryCode):
            eg.msgbox(
                "ISODates are not supported in typed queries. Please refer to the examples."
            )
        elif re.match(queryRegex, queryCode):
            break
        eg.msgbox(
            "An improper query has been entered.\nPlease modify the query.")
    return queryCode
Exemple #44
0
def exportthem(maxrp, maxrc):
    global allpokedata
    allpokedata+="\n"
    if (not gui):
        print allpokedata
        dec = raw_input("\nExport Pokémon to Files? (y/n): ").lower()
    else:
        dec = easygui.codebox("Displaying Pokémon Data:","Rare Candy",allpokedata)

    if dec in yes:
        maxr = 0
        if (maxrp!=None):
            PartyToPkm(maxrp,True)
            maxr+=maxrp
        if (maxrc!=None):
            PartyToPkm(maxrc,False)
            maxr+=maxrc

        print "\nAll",maxr,"Pokémon Successfully Exported!"
def main():
    global parser
    (options, args) = parser.parse_args()
    # Check to see if we have all the information we need
    directory = None; template = None
    try:
        directory = args[0]
        template = args[1]
    except IndexError:
        try:
            import easygui
            # get directory from user
            while not directory:
                directory = easygui.diropenbox("Where are the files?")
            # get template from user
            while not template:
                template = easygui.choicebox(
                    "What template do you want?",
                    choices=os.listdir(absolute_path("templates")))
        except ImportError:
            sys.stderr.write("Usage: " + sys.argv[0] + " <directory> <template>\n")
            return 1

    scans = {}
    albums = {}
    metafiles = {}
    for branch, dirs, files in os.walk(directory):
        for filename in files:
            if filename == ".albuminfo":
                add_metafile(branch, filename, metafiles)
                continue
            extension = os.path.splitext(filename)[1][1:]
            if extension in ignoreFileExtensions:
                continue
            elif extension in imageFileExtensions:
                add_scan(branch, filename, scans)
            else:
                add_track(Track(os.path.join(branch, filename)), albums)

    if options.album_info:
        filepath = os.path.join(directory, ".albuminfo")
        album_index = ConfigParser.RawConfigParser()
        album_index.read(filepath)
        for album in albums:
            if album not in metafiles:
                sys.stdout.write("++ {0}\n".format(album))
                ripper = raw_input("Ripper: ")
                catalog_no = raw_input("Catalog #: ")
                album_art = raw_input("Album art URL: ")
                try:
                    album_index.add_section(album)
                    album_index.set(album, "ripper", ripper)
                    album_index.set(album, "catalog_no", catalog_no)
                    album_index.set(album, "album_art", album_art)
                except DuplicateSectionError:
                    # We've got 2 albums with the same name...
                    pass
        fp = open(filepath, "rw+")
        album_index.write(fp)
        fp.close()
        add_metafile(directory, ".albuminfo", metafiles)

    merge_metafiles(albums, metafiles)
    merge_scans(albums, scans)

    root_node = albums.values()
    root_node.sort(natural_sort)
    for album in root_node:
        album.tidy()

    env = Environment(loader=PackageLoader("bxt_description_generator", "templates"))
    env.filters["cleanify"] = cleanify
    env.filters["pretty_time"] = pretty_time
    template = env.get_template(template)
    output = template.render(albums=root_node).encode("utf-8")

    try:
        if options.outfile:
            f = open(options.outfile,"wb")
        else:
            f = tempfile.NamedTemporaryFile(delete=False, suffix=".htm")
        f.write(output)
        f.close()
    except IOError:
        sys.stderr.write("Unable to write to {0}".format(options.outfile))
        return 1
    else:
        try:
            easygui.codebox(text=output)
        except NameError:
            sys.stdout.write(output)
    return 0
Exemple #46
0
import easygui as eg
import socket
import sys
reload(sys) 
sys.setdefaultencoding('utf-8')

PORT=50000
HOST=eg.enterbox("What is your server IP")

while(True):
	#data=" ".join(sys.argv[1:])
	#data=raw_input("Please input your instruction:")
	msg         = "Enter your HTTP instruction.The server support 'ls' 'add' 'delete' 'modify' "
	title       = "GchHTTP Network communication"
	fieldNames  = ["Instruction","StudentID","StudentName","StudentPicture"]
	fieldValues = []  # we start with blanks for the values
	fieldValues = eg.multenterbox(msg,title, fieldNames)
	data=fieldValues[0]+' '+fieldValues[1]+' '+fieldValues[2]+' '+fieldValues[3]

	sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	try:
		sock.connect((HOST,PORT))
		sock.sendall(data)
		received=sock.recv(1024)
	finally:
		sock.close()
	#print "Sent: {}".format(data)
	#print "Received: {}".format(received)
	eg.codebox("Received from server:" , "GchHTTP response", received)
	#if data=="quit":
Exemple #47
0
def dialog_text(message = "Press OK to continue", title = "Text Box", text = ""):
    """
    Show a dialog with prompt `message`, title `title`, and text content `text`.
    """
    easygui.codebox(str(message), str(title), str(text))
def process(PA):
	global ActiveWindow, Shapes, Word, TRs_all, xl, Visio
	global RESULTS
	# Bien gérer les erreurs
	try:

		# ouvrir le fichier excel et faire les initialisations de coutume
		xl = CreateObject("Excel.application")
		xl.Visible = False
		xl.DisplayAlerts = False
		PA_wb = xl.Workbooks.Open(PA)
		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 = PA_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
			# Ceci est pour les déssins plutôt compliqués, après chaque sélection des PB, le script
			# les affichera et demandra de confirmer si c'est bon ou non
			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'):
					# certaines shapes buguent je ne sais pas pourquoi, elles n'ont pas d'utilité
					try:
						blocs_PT.append(shape)
					except:
						blocs_PT = [shape]
				elif text.startswith('PA'):
					bloc_PA = text
					# On extrait la position x du PA pour prendre toutes les TR qui sont à droite
					PA_posx = get_XY(shape)[0]
			# Les deux blocs FI et PA tout deux commencent par PT, celui de PA est plus à gauche
			# on les différenciera par leur position
			if get_XY(blocs_PT[0])[0] < get_XY(blocs_PT[1])[0]:
				FI_bloc = blocs_PT[0]
				PA_bloc = blocs_PT[1]
			else:
				FI_bloc = blocs_PT[1]
				PA_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]

			# Les TRs du déssin courant
			TRs = {}

			# là ça va barder!
			for shape in Shapes:
				if shape.Text.startswith('TR'):
					# Seulement ceux qui sont plus à droite de PA
					if get_XY(shape)[0] > PA_posx:
						# Le text est un peu bizarre, il est vraiment en texte mais paraît être un
						# bytes! On doit le nettoyer
						TR_TXT = str(shape.Text.encode()).replace("b'", '').replace("'", '')
						# Extraire ne TR
						TR = TR_TXT.rsplit('FO')[0] \
							.replace('\\n', ' ') + 'FO'
						# Si ce n'est pas un TR valide, passer
						if not re.match(r'TR\s+\d{2}\s+\d{4}\s+\d+FO', TR):
							continue
						# Si ce TR n'a pas encore été enregistré dans la liste TRs, l'enregistrer
						## Initialiser la longueur à 0
						## Mettre le shape courant dans la liste "shapes"
						## Initialiser une liste vide pour les CH ou IMB ou AP qui vont avec
						## Initialiser une liste vide pour les PTs qui vont avec (pour le nommage)
						## Et initialiser une variable "0" pour le PT qui est maximum (pour le nommage)
						if TR not in TRs:
							TRs[TR] = {
								'LONG': 0,
								'SHAPES': [shape.ID],
								'CH/IMB/AP': [],
								'PTs': [],
								'maxPT': 0
								}
						# Sinon si le TR est déjà dans TRs, ajouter le shape courant à "SHAPES"
						else:
							TRs[TR]['SHAPES'].append(shape.ID)
						# Essayer d'extraire la longueur du TR courant
						try:
							TR_LONG = int(TR_TXT.rsplit('\\xe2\\x80\\x93 ')[1] \
															.replace('m', ''))
						except:
							TR_LONG = 0
						# Et incrémenter la longueur du TR global corréspondant à cette ligne
						TRs[TR]['LONG'] = TRs[TR]['LONG'] + TR_LONG
			
			# Message pour que l'utilisateur sélectionner les blocs PB pour chaque TR
			title1 = 'Sélectionnez les bloc'
			title2 = 'Confirmez la sélection'
			# Pour chaque TR dans TRs
			for TR in TRs:
				# Python n'a pas de "REDO", on hack avec un "WHILE"
				while True:
					# Sélectionner toutes les shapes de cette ligne de TR
					SelectShapes(TRs[TR]['SHAPES'])
					# Demander lui de sélectionner, quand il confirme continuer...
					if ccbox(TR, title1):
						# Une liste vide pour tout les PB dans ce TR
						CH_OR_IMB_OR_AP_all = []
						# Une liste vide pour tout les PTs dans ce TR
						PTs = []
						# Une liste vide pour tout les PBs dans ce TR
						PBs = []
						# Un message au cas où l'utilisateur aurait choisit une confirmation
						msg = "Pour " + TR + "\nVous avez sélectionné:\n"
						# Le nombre de PBs sélectionnées (pour affichage dans la confirmation)
						selected_PBs = 0
						# Au cas où il n'y aurait pas de PB valide, pas la peine de mettre une 
						# fenêtre de confirmation, supposer tout de même qu'il y'en a ...
						yn_yes = True
						# Pour chaque fenêtre sélectionnée
						for selected in ActiveWindow.Selection:
							# (certains shapes n'aiment pas qu'on appelle leur .Text!!!!)
							try:
								TEXT = str(selected.Text)
								# Prendre seulement les blocs qui commencent par "PB"
								if not TEXT.startswith('PB'):
									continue
								# Incrémenter le nombre de PBs trouvés par +1
								selected_PBs = selected_PBs + 1
								# Enregister le PB, PT, l'adresse, et le text qui peut être un:
								## Ch.XXXXX
								## IMB/XXXXX/XXXX
								## AP XXXX
								PB = TEXT.rsplit('\n')[0].rstrip()
								PT = TEXT.rsplit('\n')[2]
								ADR = TEXT.rsplit('\n')[3]
								CH_OR_IMB_OR_AP = TEXT.rsplit('\n')[4]
								# Si l'un de ces lignes ne se trouve pas à la bonne place
								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')):
									# Resélectionner les sélectionnés (pfff sert à rien ça!)
									SelectShapes([selected.ID])
									# Et dire qu'il y a un truc qui cloche!
									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")
									# Continuer ou quitter!
									cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
									if not cont:
										exit(0)
									else:
										pass
								else:
									# Sinon, préparer le message de confirmation
									msg = msg + "- " + CH_OR_IMB_OR_AP + "\n"
									# Et ajouter le CH/IMB/AP à la liste
									CH_OR_IMB_OR_AP_all.append([ADR, CH_OR_IMB_OR_AP])
									# Ajouter le PT de ce bloc à la liste PTs
									PTs.append(int(PT.replace('PT', '')))
									# Ajouter le PB de ce bloc à la liste PBs
									PBs.append(PB)
							except:
								# Si quelque chose cloche, trouver une porte de sortie!!:
								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?'])
								# Vraiment je ne sais pas à quoi sert ce que j'ai écrit dans les 
								# 8 prochaines lignes!!!!
								if not cont:
									exit(0)
								else:
									msg = msg + "(RIEN!)"
									CH_OR_IMB_OR_AP_all = []
									PTs = []
									PBs = []
									yn_yes = False
						# S'il n'a rien sélectionné
						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'])
							# Soit on quitte!
							if cont:
								break
							# Soit c'est délibéré et on continue
							else:
								continue

						# Si l'utilisateur avait demandé une confirmation, la montrer
						# (S'il y a eu une erreur, yn_yes est False, et pas la peine de montrer la
						# confirmation)
						if yn and yn_yes:
							msg = msg + "(" + str(selected_PBs) + " sélectionnés)"
							conf = boolbox(msg, title2, ['Confirmer?', 'Refaire?'])
							if conf:
								# Si c'est confirmé, stocher ces données pour le shape
								TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
								TRs[TR]['PTs'] = PTs
								TRs[TR]['PBs'] = PBs
								break
							else:
								pass
						# Sinon s'il n'avait pas demandé de confirmation, stocker ces données
						# directement pour le shape
						else:
							TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
							TRs[TR]['PTs'] = PTs
							TRs[TR]['PBs'] = PBs
							break
					# En cas d'erreur sortir :-(
					else:
						exit(0)
				# Il doit y avoir au moins un PT pour créer un fichier doc et xls avec le max des TRs
				if len(TRs[TR]['PTs']):
					TRs[TR]['DE_filename'] = 'DE_PT%06d' % max(TRs[TR]['PTs']) + '.doc'
					TRs[TR]['AR_filename'] = 'AR_PT%06d' % max(TRs[TR]['PTs']) + '.xls'
				# Les fichiers avec ce nom ne devront jamais voir le jour!
				else:
					TRs[TR]['DE_filename'] = 'je_ne_suis_pas_cense_exister.doc'
					TRs[TR]['AR_filename'] = 'je_ne_suis_pas_cense_exister.xls'
					# Un cas très particulier m'a forcé à ajourer la ligne suivant!
					TRs[TR]['PBs'] = []

			# Si je n'ai trouvé aucun TR, montrer un message
			if TRs == {}:
				msgbox("il n'y pas de TR valide sur ce déssin")
			# Ajouter ces TRs à TR_all
			TRs_all.append(TRs)
			# Cacher le déssin Visio
			Visio.Visible = False

		# Demander qui est le client
		xl.Visible = True
		msg = "Quel est le client pour cette fiche PA?"
		choices = ["Circet","Engie"]
		client = buttonbox(msg, choices=choices)

		# Résultat globaux pour cette fiche PA
		RESULTS[PA] = {
			'PA_REF':		bloc_PA,
			'client':		client,
			'TRs_all': 		TRs_all,
			'NRO':			NRO,
			'PMZ_PT':		PMZ_PT,
			'PA_PT':		PA_PT,
			'CH':			CH,
			'ADRESSE1':		ADRESSE1,
			'ADRESSE2':		ADRESSE2,
			'DATE':			DATE
		}

		# Quitter excel et passer à la prochaine fiche PA
		xl.Quit()
		return

	except:
		# En cas d'erreur innatendue!
		print(format_exc())
		codebox("t'as encore fais une connerie! Fais moi un screen de malheur!",
				"Erreur",
				format_exc())
		going()
Exemple #49
0
                        break
                    id = int(fieldValues[0])
                    start_addr = int(fieldValues[1])
                    reg_quantity = int(fieldValues[2])
                    byte_count = int(fieldValues[3])
                    reg_value = fieldValues[4].split(' ')
                    length = 7 + 2 * reg_quantity
                    send_multiple = struct.pack("!h", tx_id) + "\x00\x00" + struct.pack("!h", length)  + struct.pack("B", id) + "\x10" + struct.pack("!h",start_addr) + struct.pack("!h", reg_quantity) + struct.pack("B", byte_count) #corrregit estructura pquete

                    for value in range(0, reg_quantity):
                        send_multiple = send_multiple + struct.pack("!H", int(reg_value[value]))
                    write_multiple_values_tcp(send_multiple)

                tx_id += 1
                sys.stdout = open ('output', 'r')
                easygui.codebox(msg, title, sys.stdout.readlines())
        else :
            print "Connection TIMEOUT"
            sys.stdout = open ('output', 'r')
            easygui.codebox(msg, title, sys.stdout.readlines())

    elif reply == "Serial Port":

        ser = serial.Serial()
        sys.stdout = open('output', 'w')
        ports = list(serial.tools.list_ports.comports())

        msg = "Select the port to use"
        title = "Selecting Serial Port"
        choices = []
        for port in ports:
Exemple #50
0
def hexview_data (data, msg='', title='ezhexviewer', length=16, startindex=0):
    hex = hexdump3(data, length=length, startindex=startindex)
    easygui.codebox(msg=msg, title=title, text=hex)
Exemple #51
0
def pdfViewStreams(pyew, doprint=True, stream_id=-1, gui=False):
    """ Show decoded streams """
    streams_filters, buf = pdfStreams(pyew, doprint=False, get_buf=True)

    streams = 0

    while 1:
        pos = buf.find("stream")
        if pos == -1:
            break
        streams += 1
        pos2 = buf.find("endstream")
        # -8 means -len("stream")
        #tmp = buf[pos+8:pos2-1]
        tmp = buf[pos+6:pos2]
        tmp = tmp.lstrip(" ")
        failed = False
        dones = []
        if stream_id == -1 or streams == stream_id:
            if streams_filters.has_key(streams):
                for filter in streams_filters[streams]:
                    try:
                        print "Applying Filter %s ..." % filter
                        if filter in dones:
                            print pyew.hexdump(tmp, pyew.hexcolumns)
                            msg = "The filter %s is already applied, it seems to be a PDF Bomb."
                            msg += os.linesep + "Do you want to apply it? "
                            ret = raw_input(msg % filter)
                            if ret != "y":
                                continue
                        else:
                            dones.append(filter)
                        
                        if filter == "FlateDecode":
                            tmp = zlib.decompress(tmp.strip("\r").strip("\n"))
                        elif filter == "ASCIIHexDecode":
                            tmp = binascii.unhexlify(tmp.replace("\r", "").replace("\n", "").replace(" ", "").strip("<").strip(">"))
                        elif filter == "ASCII85Decode":
                            tmp = ASCII85Decode(tmp.strip("\r").strip("\n"))
                        elif filter == "RunLengthDecode":
                            tmp = RunLengthDecode(tmp)
                        elif filter == "LZWDecode":
                            tmp = LZWDecode(tmp)
                    except:
                        failed = True
                        print "Error applying filter %s" % filter, sys.exc_info()[1]
                
                print "Encoded Stream %d" % streams
            else:
                print "Stream %d" % streams
            
            if not gui:
                print "-"*80
                if tmp.find("\x00") == -1:
                    print tmp
                else:
                    print pyew.hexdump(tmp, pyew.hexcolumns)
                print "-"*80
            else:
                if tmp.find("\x00") == -1:
                    textbox("Stream %d" % streams, "Stream", tmp)
                else:
                    codebox("Stream %d" % streams, "Stream", pyew.hexdump(tmp, pyew.hexcolumns))
            
            if tmp.find("\x00") > -1 and not failed and not gui:
                res = raw_input("Show disassembly (y/n)? [n]: ")
                if res == "y":
                    print pyew.disassemble(tmp)
        
        buf = buf[pos2+11:]
        if buf.find("stream") == -1:
            break
        
        if stream_id == -1:
            try:
                if not gui:
                    res = raw_input("Continue? ")
                    
                    if res in ["q", "n"]:
                        break
                else:
                    if not ccbox("Do you want to continue?", "Streams Viewer"):
                        break
            except:
                break
        elif stream_id == streams:
            break
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()
Exemple #53
0
def main():
    """Main program to demonstrate the easygui module."""

    # The most basic message box displays a message with an OK button.
    easygui.msgbox( "Your software installation is complete.\n\n" +
                    "This and the following dialogs are a\ndemonstration of the easygui module.\n\n" +
                    "Your responses to each dialog are\nprinted in the console window.\n\n" +
                    "You may find this module useful\nthroughout the semester." )

    # A default Yes/No box asks "Shall I continue?", shows Yes and No buttons,
    # and returns True if Yes is clicked, False if No is clicked.
    response = easygui.ynbox()
    print( type( response ), response )

    # The message/question and dialog title can be specified.
    response = easygui.ynbox( msg="Is your squad the best at USAFA?", title="Best Squad?" )
    print( type( response ), response )

    # The more generic Bool box allows different text in the Yes/No buttons.
    response = easygui.boolbox( msg="Is your squad the best at USAFA?", title="Best Squad?",
                                choices=[ "Hooah!", "Form 10" ] )

    # This is how you might use the response from a Yes/No or Bool box.
    # Note the variable 'response' is already True or False, so there is no
    # need to compare it to anything (i.e., response == True is not necessary).
    if response:
        # The message box displays a message and a button to close the box.
        easygui.msgbox( msg="Of course my squad is best!", title="Best Squad", ok_button="Hooah!" )
    else:
        # If not specified, the button says "OK", as you would expect.
        easygui.msgbox( msg="My squad improves every day.", title="Best Squad" )

    # A button box allows more than two choices.
    response = easygui.buttonbox( msg="Who is your favorite turtle?", title="Select",
                                  choices=[ "Leonardo", "Michelangelo", "Raphael", "Donatello" ] )
    print( type( response ), response )

    # The enter box returns a string and allows specification of the default value.
    response = easygui.enterbox( msg="Enter your favorite baseball team:",
                                 title="Go Cubs!", default="Chicago Cubs" )
    print( type( response ), response )

    # The integer box returns an int and allows specification of lower and upper bounds.
    response = easygui.integerbox( msg="What is the answer?", title="Input",
                                   default="42", lowerbound=0, upperbound=100 )
    print( type( response ), response )

    # The file open box is a standard file chooser dialog and returns the file name as a string.
    filename = easygui.fileopenbox( msg="Open file...", filetypes=[ "*.txt", "*.py" ] )
    print( type( filename ), filename )

    # Here is a simple way to read the entire contents of a file into a single string.
    with open( filename, "r" ) as data_file:
        data = data_file.read()

    # A code box displays editable text in a monospaced font and does not wrap lines;
    # (not shown here, but a textbox would use a proportional font and wrap lines).
    edited_data = easygui.codebox( msg=filename, title="Code Box", text=data )

    # The text in the code box is returned as a single string when the window is closed.
    if data == edited_data:
        easygui.msgbox( msg="No changes made to text." )
    else:
        # The file save box asks to confirm before overwriting an existing file.
        filename = easygui.filesavebox( msg="Save file...", filetypes=[ "*.txt", "*.py" ] )
        # The file name will be None if the user clicks Cancel.
        if filename is not None:
            # Here is a simple way to write the entire contents of a string to a file.
            # Note: If the filename already exists, it will be completely overwritten!!
            with open( filename, "w" ) as data_file:
                data_file.write( edited_data )
Exemple #54
0
def out(text):
    eg.codebox(msg='Speed Results', title='Web Page Speed Results', text='%s' % (text))
    eg.msgbox("%s" %text)
Exemple #55
0
 def LogGui(self, title="Alert", msg="Alert", arq="Essa_test.log"):
     filename = os.path.normcase("{}{}".format(_globals.pathLog,arq))
     f = open(filename, "r")
     text = f.readlines()
     f.close()
     return codebox(msg=msg + filename, title=title, text=text)
#1 (with extra stuff) :)
import easygui
easygui.msgbox ("This program converts Fahrenheit to Celcius.")
user=easygui.integerbox("Type in the temperature in fahrenheit:")
girl=float(user)
celcius= (girl-32)*5.0/9
easygui.msgbox("The temperture in celcius is  " + str(celcius))
girl=easygui.buttonbox ("Isn't this program great?",
                        choices= ['YES','NO'])
if girl== 'YES':
    easygui.msgbox ("Great! I thought so too! It makes converting temperature easier.")
else:
    easygui.msgbox ("Really? I thought it was helpful!")
    extra=easygui.codebox ("Type in your reply", title= 'Your reply....')
    easygui.msgbox('Oh...good point. I will look into that. Thanks for the reply.....   ' + str(extra))

 

#2
easygui.msgbox("This program will help setup your adress and name in mail-style.")
name= easygui.enterbox ("What is your first name and your last name?")
street= easygui.enterbox ("What is your number and what is your street?")
live= easygui.enterbox ("What town do you live in, and what state or country?")
zip_code= easygui.enterbox ("What is your zip code?")
easygui.msgbox ( name + "\n" + 
                 street + "\n" +  
                 live + "\n" +
                 zip_code)
Exemple #57
0
      minval, maxval=ask_for_minmax_values(min(x),max(x))

      results += "NON FILTERED RESULTS"+"\n\r"
      results += regression_figure(evenPlotRegression,
         evenlySpacedXArray,evenlySpacedYArray,
         weightSubPlot,
         x,y,minval,maxval,
         dbfilename,sampleNumber)

      #weightFilteredSubPlot=fig.add_subplot(6,2,4)
      #results2 = regression_figure(weightFilteredSubPlot,fx,fy,minval,maxval,dbfilename,sampleNumber)
      #results += "FILTERED RESULTS "+ filterFlag+"\n\r"
      #results += results2+"\n\r"

      easygui.codebox(msg=None, title='Results ', text=results)

      test=""




      #plt.plot(xArray,ap_valueArray,'+')
      msg     = "What would you like to do?"
      choices = ["Try Again","Next Sample","Quit"]
      reply   = easygui.buttonbox(msg,image=None,choices=choices)

      if reply=="Next Sample":
         plt.clf()
         sampleNumber += 1
         break
import easygui as eg
import subprocess
import os
import re

source = eg.buttonbox(msg="How would you like to get the album?", title="Album Splitter", choices=("Youtube", "File"))

if source == "File":
    link = "-mp3 \"" + os.path.abspath(eg.fileopenbox(msg="Select mp3 file", title="Album Splitter", default='*', filetypes="\*.mp3") + "\"")
else:
    link = "-yt \"" + eg.enterbox(msg="Enter Youtube link", title="Album Splitter", default="", strip=True, image=None, root=None) + "\""
    
format = eg.choicebox(msg="Select format", title="Album Splitter", choices=("<start time> - <title>", "<start time> <title>")) #More formats can be added


tracks = eg.codebox(msg="Paste track list:", title="Album Splitter", text="")

#More formats can be added
if format == "<start time> - <title>":
    with open("tracks.txt", 'w') as t:
        t.write(tracks)
if format == "<start time> <title>":    
    tracks = tracks.split('\n')
    regex = re.compile("(\d*\s\-\s)*(?P<start>\S+)\s*(?P<title>.+)")
    for i in range(len(tracks)):
        if tracks[i] != "":
            m = regex.match(tracks[i])
            tStart = m.group('start').strip()
            tTitle = m.group('title').strip()
            tracks[i] = tStart + " - " + tTitle
    with open("tracks.txt", "w") as t:
	summer_holiday_last_ture = summer_holiday_last+1 #暑假还剩下多少天(正确)
	summer_holiday_last_baifenbi = (((now_time - summer_holiday_start).days)/53)*100 #计算百分比
	summer_holiday_last_baifenbi_ture = math.floor(summer_holiday_last_baifenbi) #换成整数
	bfb = open("/home/redapple/.holiday/bfb.txt", "w") #打开百分比的写入文件(请按自己实际情况更改)
	bfb.write(str(summer_holiday_last_baifenbi_ture)) #写入百分比
	bfb.close() #关闭文件
	os.system("rm /home/redapple/.holiday/jdt.txt") #删除jdt文件
	os.system("python3 /home/redapple/.holiday/jdt.py >> /home/redapple/.holiday/jdt.txt") #把另外一个py程序输出的百分比进度条写入到文件里(路径自己修改)比
	file = open("/home/redapple/.holiday/homework.txt", "r") #打开作业列表(自己修改路径)
	jdt = open("/home/redapple/.holiday/jdt.txt", "r").read() #打开进度条文件(自己修改路径)
	summer_holiday_homework_monitor = open("/home/redapple/.holiday/homework.txt", "r").read()
	mark = re.compile('`') #设定要查找的内容(注意在作业前要加`)
	find = re.findall(mark, summer_holiday_homework_monitor) #查找
	find_mount = len(find) #显示有多少个
	finish_homework = 14-find_mount #用作业总数减去得到的结果(自己改作业总数)
	calc = math.floor((finish_homework/15)*100) #计算
	homework_baifenbi = open("/home/redapple/.holiday/homework_bfb.txt", "w") #打开一个百分比文件
	homework_baifenbi.write(str(calc)) #写入计算的百分比
	homework_baifenbi.close()
	os.system("rm /home/redapple/.holiday/homework_jdt.txt") #删掉已有的文件(自己改路径)
	os.system('python3 /home/redapple/.holiday/homework_jdt.py > /home/redapple/.holiday/homework_jdt.txt') #把进度条写入文件
	homework_jindutiao = open("/home/redapple/.holiday/homework_jdt.txt", "r").read() #读取文件
	tips = "今天是" + str(today) + "\n" + "距离暑假结束还有" + str(summer_holiday_last_ture) + "天" + "\n" + "暑假已经过去了" + str(jdt) + "\n" + "暑假作业已经完成了" + str(homework_jindutiao) #配置窗口要显示的内容
	tips_finally = easygui.codebox(tips,"倒计时小程序",file) #显示窗口
	file.close() #关闭文件
	if tips_finally == None: #如果用户按了关闭或取消
		break #退出程序
	else: #反之
		file = open("/home/redapple/.holiday/homework.txt", "w") #打开homework文档(自己修改路径)
		file.write(tips_finally) #写入用户输入新的内容
		file.close() #关闭文件
Exemple #60
0
def setup():
    
    msg = ("Welcome to the new employee notification tool.\n"
           "The tool allows you to send customized automated emails "
           "that contain information about all ActiveDirectory users "
           "created within the last 24h.\n"
           "You will be asked several questions and config filters. "
           "Searches may take a few seconds to complete.\n"
           )
    msg2 = ("\nPlease create a new filter or load an existing filter "
            "which you can then modify."
            )
    cfgs = os.listdir(cfgdir)
    if len(cfgs)==0:
        msg2 = ''
        easygui.msgbox(msg,__app__)
        pick='New Config'
    else:        
        pick = easygui.buttonbox(msg+msg2, __app__, ['New Config','Load Existing',
                                                     'Cancel'])
    if pick == 'Cancel':
        return False
    
    if pick != 'New Config':
        config = easygui.choicebox("Select an existing config:",__app__,cfgs)
        if not config:
            return False
        cfg = Settings(os.path.join(cfgdir,config))
        cfg.restore
    else:
        config=''
        while config == '':
            config = easygui.enterbox('Saving this filter. Please enter a name for this notification.', __app__)
            if not config:
                sys.exit()
        config=config.replace(' ','_')
        if not config.endswith('.txt'):
            config=config+'.txt'            
        cfg = Settings(os.path.join(cfgdir,config))
        cfg.store()    # persist the settings
        
        msg = ("Please select employee information you would like to filter.\n"
               "For example if you want to know about new staff in specific departments "
               "please pick 'Departments'. If you want to know about new users "
               "reporting to specific managers please pick 'Managers'. "
               "If you'd like to check for new users in specific Divisions and optionally "
               "filter by certain job titles please pick 'Divisions/Jobtitles'"
               )
        choi = [ "Departments", "Managers", "Divisions/Jobtitles" ]
        choival = [ "department", "manager", "division" ]

        pick = easygui.buttonbox(msg, __app__, choi)
        if not pick:
            return False
        idx = choi.index(pick)
        
        cfg.filter1=getUserAttrList (choival[idx])
        cfg.filter1_attr=choival[idx]

    cfg.filter1=easygui.multchoicebox(msg,"Select values from %s" % pick,cfg.filter1)
    if cfg.filter1_attr == 'division':
        alist=getUserAttrList ('title')
        filter2_attr='title'
        filter2=easygui.multchoicebox(msg,"Select values from 'Jobtitile'",alist)
    else:
        cfg.filter2_attr=''
        cfg.filter2=''

    msg = ("Please enter one or multiple email addresses (separated by comma) "
           "to which you want to send a notification when new users arrive"
           )
    cfg.to = easygui.enterbox(msg, __app__,cfg.to)


    msg = ("Please enter the email body you want to use for your notification "
           "email. A list of new users will be added below this text."
           )
    cfg.mailbody = easygui.textbox(msg, __app__, cfg.mailbody, codebox=False)

    msg = ("Optional: Please enter the command line of a script including full path "
           "and command options. This script will be executed when new users arrive.\n"
           "(Please leave this line empty to not execute anything.)"
           )
    cfg.run = easygui.enterbox(msg, __app__,cfg.run)
    
    cfg.store()    # persist the settings

    
    testdate=''
    out=''
    while True:
        if easygui.boolbox('Do you want to test this configuration (again) ?', __app__, ('Yes', 'No')):
            msg = ("If you want to test this config, please enter the creation date "
                         "(format: YYYYMMDD) you would like to test."
                        )
            testdate = easygui.enterbox(msg, __app__,testdate)
            if not testdate:
                break
            if testdate != '':
                exe=getMyFile()
                try:
                    out=subprocess.check_output(
                        '"%s" --debug --search-date %s %s' % (exe,testdate,config),
                        stderr=subprocess.STDOUT,
                        shell=True)
                except :
                    print "likely subproces CalledProcessError.output "
                easygui.codebox('Please see debugging output below:', __app__, out)
        else:
            break

    cmdline = '%s %s' % (getMyFile(),config)
    easygui.codebox('Please activate this command via cron:' , __app__,cmdline)