Exemplo n.º 1
0
def getFile(world):
    b = easygui.buttonbox("","PyCraft: Select a World", ("Load World","New World","Quit"))
    if b == "Quit":
        logdata("The user quitted immediatly.")
        quit()
    if b == "New World":
        logdata("The user created a new world.")
        name = easygui.enterbox("Pick a name for your world: ")
        logdata("They named it '"+name+"'.")
        gens = os.listdir("generators/")
        for gen in range(len(gens)):
            gens[gen] = gens[gen][:-3]
        gen = easygui.choicebox("Select a world generator: ","",gens)
        logdata("They used the generator '"+gen+"'.")
        exec open("generators/"+gen+".py").read()
        generateRandomMap(world)
        
        world.saveName = name
    if b == "Load World":
        worlds = os.listdir("worlds/")
        world_name = easygui.choicebox("Select a world","Pycraft: Select a World", worlds)
        logdata("They loaded the world named '"+world_name+"'.")
        world_data = open("worlds/"+world_name,"r").read()
        logdata("It contains "+str(len(world_data.split("\n"))-1)+" blocks.")
        parseMap(world,world_data)
        world.saveName = world_name
Exemplo n.º 2
0
def main(db):

    # ------------------
    # POPULATE CDMS LIST
    # ------------------
    pd.options.mode.chained_assignment = None
    print 'Pulling updates from CDMS...'
    update_list = pull_updates()
    choice_list = [CDMSChoiceList([str(i)]+update_list[i]) for i in range(len(update_list))]

    # RUN PROCESS

    CDMSLoop = True
    while CDMSLoop:
        cursor = db.cursor()

        choice = eg.choicebox("Choose a Molecule to Update", "Choice", choice_list)
        custom_cat_file = eg.buttonbox(msg='Would you like to supply a custom CAT file?', choices=['Yes', 'No'])
        if custom_cat_file == 'Yes':
            custom_path = eg.fileopenbox(msg='Please select a CAT file.', title='Custom CAT file')
            cat_entry = CDMSMolecule(update_list[int(choice[0:5])], custom=True, custom_path=custom_path)
        else:
            cat_entry = CDMSMolecule(update_list[int(choice[0:5])], custom=False)

        cmd = "SELECT * FROM species " \
            "WHERE SPLAT_ID LIKE '%s%%'" % str(cat_entry.tag[:3])

        cursor.execute(cmd)
        res = cursor.fetchall()
        splatmolresults = [SplatSpeciesResultList([i]+list(x)) for i, x in enumerate(res)]
        splatmolresults += [SplatSpeciesResultList([len(splatmolresults),999999999,0,'NEW MOLECULE',
                                                    'X', '', '', '', '', '', ''])]
        choice2 = eg.choicebox("Pick molecule from Splatalogue to update, or create a new molecule.\n "
                               "Current choice is:\n %s" % choice, "Splatalogue Search Results",
                               splatmolresults)
        cursor.close()

        if choice2[68] == 'X':
            linelist, species_final, metadata_final = new_molecule(cat_entry, db)
            push_molecule(db, linelist, species_final, metadata_final, update=0)

        else:  # Molecule already exists in Splatalogue database
            linelist, metadata_final = process_update(cat_entry, res[int(choice2[0:5])], db)
            push_molecule(db, linelist, {}, metadata_final, update=1)

        choice3 = eg.buttonbox(msg='Do you want to update another CDMS entry?', choices=['Yes', 'No'])

        if choice3 == 'No':
            CDMSLoop = False
Exemplo n.º 3
0
def main(db):
    pd.options.mode.chained_assignment = None

    # Get JPL update listing
    listing = get_updates()

    choice_list = ["%s  %s  %s" % (time.strftime('%Y/%m/%d', x[0]), x[1], x[2]) for x in listing]
    JPLLoop = True
    while JPLLoop:

        choice = eg.choicebox('Choose a Molecule to Update', 'Choice', choice_list)

        choice_idx = 0
        for idx, ent in enumerate(listing):
            if int(choice.split()[1]) == ent[1]:
                choice_idx = idx

        cat_entry = JPLMolecule(listing[choice_idx])

        tag_num = str(cat_entry.id)
        print tag_num, ''.join(('0',)*(6-len(tag_num)))+cat_entry.id[:(len(tag_num)-3)]
        cmd = "SELECT * FROM species " \
             "WHERE SPLAT_ID LIKE '%s%%'" % (''.join(('0',)*(6-len(tag_num)))+cat_entry.id[:len(tag_num)-3],)

        cursor = db.cursor()
        cursor.execute(cmd)
        res = cursor.fetchall()

        SplatMolResults = [SplatSpeciesResultList([i]+list(x)) for i, x in enumerate(res)]
        SplatMolResults += [SplatSpeciesResultList([len(SplatMolResults),999999999,0,'NEW MOLECULE',
                                                    'X','','','','','',''])]
        choice2 = eg.choicebox("Pick molecule from Splatalogue to update, or create a new molecule.\n "
                               "Current choice is:\n %s" %choice, "Splatalogue Search Results",
                               SplatMolResults)
        cursor.close()

        if choice2[68] == 'X':
            linelist, species_final, metadata_final = new_molecule(cat_entry, db)
            push_molecule(db, linelist, species_final, metadata_final, update=0)

        else:  # Molecule already exists in Splatalogue database
            linelist, metadata_final = process_update(cat_entry, res[int(choice2[0:5])], db)
            push_molecule(db, linelist, {}, metadata_final, update=1)

        choice3 = eg.buttonbox(msg='Do you want to update another JPL entry?', choices=['Yes', 'No'])

        if choice3 == 'No':
            JPLLoop = False
Exemplo n.º 4
0
 def gui_choose_person(self, message, title, persons=None):
   if persons == None:
     persons = self.persons()
   chosen = easygui.choicebox(message, title,
     [person.name for person in persons]
   )
   return self.name_to_person(chosen)
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
Exemplo n.º 6
0
def relatorio_projeto():
    projetos = [x.titulo for x in MProjeto.select().order_by(MProjeto.titulo)]

    msg = "Selecione o projeto para gerar o relatório."
    title = "Relatório - Projeto"
    projeto = choicebox(msg, title, projetos)

    if projeto == None:
        return

    projeto = MProjeto.get(MProjeto.titulo == projeto)

    relatorio = "Titulo: " + projeto.titulo + "\n\n"
    relatorio += "Coordenador: " + projeto.coordenador + "\n\n"
    relatorio += "Resumo: " + projeto.resumo + "\n\n"
    relatorio += "Palavras-chave: " + projeto.keywords + "\n\n"

    participantes = [
        x.participante
        for x in MParticipante.select()
        .where(MParticipante.projeto == projeto.titulo)
        .order_by(MParticipante.participante)
    ]

    if participantes:
        relatorio += "Participantes: \n"
        for i in participantes:
            relatorio += i + "\n"
        relatorio += "\n\n"

    textbox("Relatório de Projeto", "Relatorio - Projeto", (relatorio))

    return
 def _handle_cluster_run_options(self):
     valid_choices = [ 'Make Amino acid FASTA file', 
                       'Make nucleotide FASTA file', 
                       'Make a crude AA alignment', 
                       'Make a crude Newick tree from AA alignment',
                       'Make a crude Newick tree with ITEP IDs',
                       'Display a crude tree with neighborhoods attached',
                       'Get a presence and absence table',
                       'Get information on related genes',
                       'Make a GML file to import into Cytoscape',
                       'Get blast support for a protein family']
     option = easygui.choicebox("What do you want to do with the related genes?", "Choose an analysis", valid_choices)        
     if option is None:
         return False
     if option == 'Make Amino acid FASTA file':
         self._get_cluster_fasta(amino=True)
     elif option == 'Make nucleotide FASTA file':
         self._get_cluster_fasta(amino=False)
     elif option == 'Make a crude AA alignment':
         self._make_crude_alignment()
     elif option == 'Make a crude Newick tree from AA alignment':
         self._make_crude_tree()
     elif option == 'Make a crude Newick tree with ITEP IDs':
         self._make_crude_tree(replacename=False)
     elif option == 'Get a presence and absence table':
         self._get_presence_absence_table()
     elif option == 'Display a crude tree with neighborhoods attached':
         self._display_crude_neighborhood_tree()
     elif option == 'Get information on related genes':
         self._get_cluster_geneinfo()
     elif option == 'Get blast support for a protein family':
         self._get_cluster_blast()
     elif option == 'Make a GML file to import into Cytoscape':
         self._make_cluster_gml_file()
     return True
Exemplo n.º 8
0
def policy(s):
    ps = s.policies.list
    import sploitego.hacks.gui
    c = choicebox('Select a Nessus scanning policy', 'Nessus Policies', ps)
    if c is None:
        return None
    return filter(lambda x: str(x) == c, ps)[0]
Exemplo n.º 9
0
def plot_data(data,stock):
  ticks = eg.choicebox(msg = 'choose ticks for the plot',choices = ['day','week','month'])
  if ticks == 'month':
    loc = MonthLocator()
  elif ticks == 'week':
    loc = WeekdayLocator(byweekday=MONDAY)
  elif ticks == 'day':
    loc = DayLocator()
  weekFormatter = DateFormatter('%b %d')
  dayFormatter = DateFormatter('%d')
    
#  if candle_chart == 1:
  fig = plt.figure()
  ax1 = fig.add_subplot(211)
  datelist = [matplotlib.dates.date2num(x) for x in data['Time']]
  Prices = []
  for idx in xrange(len(data)):
    Prices.append((datelist[idx],data['Open'].ix[idx],data['Close'].ix[idx],data['High'].ix[idx],data['Low'].ix[idx]))
#    candlestick(ax1,[datelist,data['Open'],data['Close'],data['High'],data['Low']])
  candlestick(ax1,Prices)
  ax1.set_xlabel('Date')
  ax1.set_ylabel('$')
  ax1.set_title('Candlestick plot for %s' %stock)
  ax2 = fig.add_subplot(212)
  ax2.plot(datelist,data['Adj Close'],'-r',label = 'Adj. Close')
  ax2.set_ylabel('$')
  ax2.legend()
  ax3 = ax2.twinx()
  ax3.bar(data['Time'],data['Volume'])
  ax3.set_ylabel('Shares')
  ax1.xaxis_date()
  ax2.xaxis_date()
  ax3.xaxis_date()
  plt.show()
  return
	def analyze(self,igroup):
		resultdatagrouped=self.gettmpdata('resultdatagrouped');
		spectra=resultdatagrouped[0]['datagroups'][igroup];
		spectranew=spectra.getemptyinstance();
		#print "spectranew type:",type(spectranew);
		
		# real analysis
		refchosen=easygui.choicebox("choose the reference","calculating diff",spectra.keys());
		if refchosen is not None:
			#spectra.plot();
			#pylab.grid(True);
			#print xmin,xmax
			spectref=spectra[refchosen];
			for k in spectra.keys():
				#if k!=refchosen:
				spect=spectra[k];
				spectnew=spect.copyxy();
				spectnew.subtract(spectref);
				#print "spectranew type after:", type(spectranew);
				spectranew.insert(spectnew,k);
			
			resultdatagrouped[0]['datagroups'][igroup]=spectranew;
			resultdatagrouped[0]['dataname']="";
			spectranew.plot();
			
	def analyze(self,igroup):
		database=self.gettmpdata('database');
		spectraspl=database[0]['resultdatatablegroups'][igroup];
		spectraref=database[1]['resultdatatablegroups'][igroup];
		
		spectranew=spectraspl.getemptyinstance();
		
		#spectra.plot();
		#print "spectranew type:",type(spectranew);
		print spectraref.keys()
		
		refchosen=easygui.choicebox("choose the second spectrum","binary calculation",spectraref.keys());
		if refchosen is not None:
			spectref=spectraref[refchosen];
			operatorstr=self['operatorstr'].get();
			for k in spectraspl.keys():
				spectnew=spectraspl[k];
				spectnew.binop(spectref,operatorstr);
				spectnew.log({"operation":"binop","operator":operatorstr});
				#spectnew.displog();
				spectranew.insert(spectnew,k);
				#spectranew[k].displog();
				
			database[0]['resultdatatablegroups'][igroup]=spectranew;
			database[1]['save']=False;
			
			XpyFigure();
			spectranew.plot('o');
Exemplo n.º 12
0
 def main():
     urlchoice = "Supply a url to turn into a pdf"
     filechoice = "Pick a single file to turn into a pdf"
     dirchoice = "Pick a directory, all .html or .htm files within will be converted to pdf"
     mainchoices = [urlchoice, filechoice, dirchoice]
     choice = easygui.choicebox(title="Options", msg="Please select an option", choices=mainchoices)
     if choice == urlchoice:
         filetype = "url"
         fileobject = easygui.enterbox("Please enter a url")
         try:
             if "http://" in fileobject or "https://" in fileobject:
                 html = urllib2.urlopen(fileobject).read()
                 convert(filetype, fileobject)
             else:
                 fileobject = "http://" + fileobject
                 html = urllib2.urlopen(fileobject).read()
                 convert(filetype, fileobject)
         except urllib2.HTTPError:
             easygui.msgbox("Invalid url")
             main()
     elif choice == filechoice:
         filetype = "file"
         fileobject = get_file(filetype)
         convert(filetype, fileobject)
     elif choice == dirchoice:
         filetype = "dir"
         fileobject = get_file(filetype)
         convert(filetype, fileobject)
Exemplo n.º 13
0
	def getForms(self):
		print "API Key : " + self.apiKey.get()
		self.jotform = JotformAPIClient(self.apiKey.get().strip())

		try:
			self.statusText["text"] = "Getting forms..."
			self.statusText.update()
			self.forms = self.jotform.get_forms()
			self.keyEntry.pack_forget()
			self.initButton.pack_forget()
		except Exception as e:
			print "Error: " + str(e)
			self.askAPIKey()

		formList = []
		for form in self.forms:
			item = form['id'] + " - " + form['title']
			item = item.encode('utf-8')
			formList.append(item)

		selection = easygui.choicebox(msg="Which form's uploads would you like to download?", title=self.title, choices=formList)
		self.formID = selection.split(" - ")[0]

		try:
			self.createFolder()
		except Exception as e:
			print("ERROR : " + str(e))
			easygui.msgbox(msg="Sorry, an error ocurred while creating form download folder : " + str(e), title=self.title)
			sys.exit(0)
Exemplo n.º 14
0
def room9():
    allvisited()
    r9.setacts(["Move: Up"])
    global actedcount
    global visitcount
    if r9.visited == False:
        r9.visited = True
        visitcount += 1
    choice = easygui.choicebox(r9.txtfile,title,r9.acts)
    if choice == "Action: Stone":
        player.items.remove("Action: Stone") #Deatils about items - \resources\items.txt
        easygui.msgbox("You threw your stone at the target.",title)
        easygui.msgbox("You found 50 coins!",title)
        easygui.msgbox("You now have 200 coins.",title)
        player.coins += 50
        r9.acted = True
        actedcount += 1
        room9()
    elif choice in player.items:
        nores()
        room9()
    elif choice == "Move: Up":
        room5()
    else:
        stop()
def currency_select():
	file_dict = {"USD to INR":'usdtoinr.csv', "USD to GBP":"usdgbp.csv","USD to EUR":'USDCAN.csv', "USD to CAN":"usdeuro.csv","USD to AUD":"usd_to_aud.csv","USD to CNY":"usdtocny.csv"}
	
	title = "Curreny Selection"
	msg = "Please select any currency from above:"
	choice = ["USD to INR","USD to GBP","USD to CAN","USD to EUR","USD to AUD","USD to CNY"]
	inputfile = eg.choicebox(msg,title,choice)
	if inputfile == None:
		flag = 1
		return (0,0,0,0,0,0,flag)
	
	inputfile = str(inputfile)		
	flag = 0
	dateparse = lambda dates: pd.datetime.strptime(dates, '%m/%d/%Y')	
	for keys in file_dict.keys():
		if inputfile == keys:
			file1 = pd.read_csv(file_dict[keys])
			myData = list ( csv.reader ( open (file_dict[keys])))
			plot_data = pd.read_csv(file_dict[keys],index_col='Date',date_parser=dateparse)
		else:
			pass	
	s = file_dict[inputfile]
	chosen_curr = Currencies_dict[s]
	end_date = file1["Date"].iloc[-1]
	start_date = file1["Date"].iloc[0]
	return (file1,myData,plot_data,chosen_curr,end_date,start_date,flag)
    def _get_run_id(self):
        msg = ''' 
Please choose one of the following methods for defining gene families.

OrthoMCL runs are useful for identifying orthologs (genes likely to share a function)

maxbit runs are useful for identifying broader
gene families. c_xxx in the following list means xxx was used as a cutoff. Higher 
cutoffs mean more stringent similarity to define a family of related genes.

Note that only the groups of organisms that contain your gene are listed here.
'''
        valid_choices = self.accumulated_data['run_to_cluster'].keys()

        if len(valid_choices) == 0:
            easygui.msgbox('The chosen gene is not found in any clustering results!')
            return True

        runid = easygui.choicebox(msg, 'Select a cluster run', valid_choices)

        # Canceling from here - just go back to the other menu
        if runid is None:
            return runid

        self.accumulated_data['runid'] = runid
        return runid
Exemplo n.º 17
0
def get_quality():
    q = ['mobile','low','medium','high','source']
    quality = eg.choicebox(msg='Choose video quality(mobile worst, source best)',title='Video quality',choices = q)
    if quality:
        return quality
    else:
        main()
Exemplo n.º 18
0
def browse_stream (ole, stream):
    """
    Browse a stream (hex view or save to file)
    """
    #print 'stream:', stream
    while True:
        msg ='Select an action for the stream "%s", or press Esc to exit' % repr(stream)
        actions = [
            'Hex view',
##                'Text view',
##                'Repr view',
            'Save stream to file',
            '~ Back to main menu',
            ]
        action = easygui.choicebox(msg, title='olebrowse', choices=actions)
        if action is None or 'Back' in action:
            break
        elif action.startswith('Hex'):
            data = ole.openstream(stream).getvalue()
            ezhexviewer.hexview_data(data, msg='Stream: %s' % stream, title='olebrowse')
##            elif action.startswith('Text'):
##                data = ole.openstream(stream).getvalue()
##                easygui.codebox(title='Text view - %s' % stream, text=data)
##            elif action.startswith('Repr'):
##                data = ole.openstream(stream).getvalue()
##                easygui.codebox(title='Repr view - %s' % stream, text=repr(data))
        elif action.startswith('Save'):
            data = ole.openstream(stream).getvalue()
            fname = easygui.filesavebox(default='stream.bin')
            if fname is not None:
                f = open(fname, 'wb')
                f.write(data)
                f.close()
                easygui.msgbox('stream saved to file %s' % fname)
Exemplo n.º 19
0
def main():
    """
    Main function
    """
    try:
        filename = sys.argv[1]
    except:
        filename = easygui.fileopenbox()
    try:
        ole = olefile.OleFileIO(filename)
        listdir = ole.listdir()
        streams = []
        for direntry in listdir:
            #print direntry
            streams.append('/'.join(direntry))
        streams.append(ABOUT)
        streams.append(QUIT)
        stream = True
        while stream is not None:
            msg ="Select a stream, or press Esc to exit"
            title = "olebrowse"
            stream = easygui.choicebox(msg, title, streams)
            if stream is None or stream == QUIT:
                break
            if stream == ABOUT:
                about()
            else:
                browse_stream(ole, stream)
    except:
        easygui.exceptionbox()
Exemplo n.º 20
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
Exemplo n.º 21
0
def main():
    msg = "Welcome to Old Sheets Flying. Please choose a service."
    title = "Old Sheets Flying : The Harvard Crimson"
    
    QUOTE_NEWS = "Quote Card : News"
    QUOTE_OPINION = "Quote Card : Opinion"
    GRAPHIC_DONUT = "Graphic : Donut - Simple"
    GRAPHIC_DONUT_CUSTOM = "Graphic : Donut - Custom"
    ABOUT = "About This Program"
    choices = [
        QUOTE_NEWS,
        QUOTE_OPINION,
        GRAPHIC_DONUT,
        GRAPHIC_DONUT_CUSTOM,
        ABOUT
    ]
    gain_focus()
    choice = gui.choicebox(msg, title, choices)
    if (choice == None):
        return
    elif (choice == QUOTE_NEWS):
        quote(False)
    elif (choice == QUOTE_OPINION):
        quote(True)
    elif (choice == GRAPHIC_DONUT):
        graphic_donut()
    elif (choice == GRAPHIC_DONUT_CUSTOM):
        graphic_donut_custom()
    elif (choice == ABOUT):
        about()
    else:
        return
Exemplo n.º 22
0
  def gui_choose_note(self, person, title):
    if person not in self.notes:
      return None

    chosen = easygui.choicebox("Which note?", title,
      ["- " + note for note in self.notes[person]]
    )
    return chosen[2: ]
	def uicolumn2xy(self,xcolumn=None,ycolumn=None):
		spect=None;
		rownames=self.keys();
		#print "1st rowname",rownames[0]
		numcolumns=self[rownames[0]].numerickeys();
		if xcolumn is None:
			answer=easygui.choicebox("Pick x column","Convert columns to XyPlotable",numcolumns);
			xcolumn=answer;
		if xcolumn is not None:
			#print "xcolumn"
			if ycolumn is None:
				answer=easygui.choicebox("Pick y column","Convert columns to XyPlotable",numcolumns);
				ycolumn=answer;
			if ycolumn is not None:
				spect=self.column2xy(xcolumn,ycolumn);
				spect.plot()
		return spect;
def viewRoot():
    global curRoom
    print(places)
    print(places.keys())
    rooms = [key for key in places]
    s = eg.choicebox(msg="Select a place:", choices=rooms)
    curRoom = places[s]
    editRoom()
Exemplo n.º 25
0
def cadastrar_projeto():

    # SEMELHANTE A LINHA ABAIXO.
    # pesquisadores = []
    # for x in MPesquisador.select().order_by(MPesquisador.nome):
    # 	pesquisadores.append(x.nome)

    pesquisadores = [x.nome for x in MPesquisador.select().order_by(MPesquisador.nome)]

    msg = "Selecione o(a) Coordenador(a) do Projeto."
    title = "Cadastro de Projeto"
    coordenador = choicebox(msg, title, pesquisadores)

    if coordenador == None:
        return

    msg = "Entre com os dados do Projeto: "
    fieldNames = ["Titulo: ", "Resumo: ", "Palavras-chave: ", "Ano de Início: ", "Ano de Término: "]
    fieldValues = []
    fieldValues = multenterbox(msg, title, fieldNames)

    while 1:
        if fieldValues == None:
            break
        errmsg = ""
        for i in range(len(fieldNames)):
            if fieldValues[i].strip() == "":
                errmsg = errmsg + ('"%s" e um campo requisido.\n\n' % fieldNames[i])
        if errmsg == "":
            break  # no problems found
        fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)

    if fieldValues == None:
        return
    else:
        # Tira acentos
        fieldValues = array_to_ascii(fieldValues)

        # Converte para Maiúsculo o Titulo do Projeto
        fieldValues[0] = fieldValues[0].upper()

        projeto = MProjeto.create(
            titulo=fieldValues[0],
            coordenador=coordenador,
            resumo=fieldValues[1],
            keywords=fieldValues[2],
            inicio=fieldValues[3],
            final=fieldValues[4],
        )
        projeto.save()
        msgbox(
            msg="Projeto: " + fieldValues[0] + " cadastrado com sucesso!",
            title=title,
            ok_button="Continuar",
            image=None,
            root=None,
        )
    return
Exemplo n.º 26
0
def show_svm_presets():
    """
    Shows a selection of preset running values for Suport Vector Machine and returns the user selection.
    """
    msg ="Select preset values for Support Vector Machines"
    title = "SVM presets"
    choices = ["something", "somethingsomething", "something else"]
    preset_choice = eg.choicebox(msg, title, choices)
    pass
Exemplo n.º 27
0
def show_me_presets():
    """
    Shows a selection of preset running values for Maximum Entropy and returns the user selection.
    """
    msg ="Select preset values for Maximum Entropy"
    title = "MaxEnt presets"
    choices = ["something", "something else", "aaand more"]
    preset_choice = eg.choicebox(msg, title, choices)
    pass
Exemplo n.º 28
0
    def gameflow(player):
        while Game.status is True:
            player.lap += 1
            cats = list()

            for category in Game.questions:
                cats.append(category)
            title = "Jeopardy SuperCool de ICC"
            category = eg.choicebox(Game.getMessage(player), title, cats)
            if not category:
                break
            choices = list()
            for quest in Game.questions[category]['preguntas']:
                if not quest['answered']:
                    choices.append(quest['value'])

            image = "Assets/imagenes/" + category + ".gif"
            msg = "Selecciona el valor que quieres ganar"
            if len(choices) > 0:
                chosen = eg.buttonbox(msg, image=image, choices=choices)

            for quest in Game.questions[category]['preguntas']:
                if not quest['answered'] and quest['value'] == chosen:
                    msg = quest['Pregunta']
                    options = list()
                    for option in quest['opciones']:
                        options.append(option['opcion'])
                        try:
                            Correcta = option['Correcta']
                            Correcta = option['opcion']
                        except KeyError:
                            pass
                    random.shuffle(options)
                    reply = eg.buttonbox(msg, image=image, choices=options)
                    quest['answered'] = True
                    if reply == Correcta:
                        eg.msgbox(random.choice(Game.correctAnswers) + "\n\nHaz ganado $" + str(quest['value']),
                                  ok_button="seguir...")
                        player.right += 1
                        player.money += quest['value']
                    else:
                        eg.msgbox(random.choice(Game.incorrectAnswers) + "\nLa respuesta es:\n"
                                  + Correcta + "\n\nHaz perdido $" + str(Game.LooseMoney), ok_button="okaaaay :(");
                        player.mistakes += 1
                        player.money -= Game.LooseMoney

                if player.mistakes > Game.ErrorLimit or player.money < Game.MoneyLimit:
                    Game.status = False
                    eg.msgbox("Has perdido, este jeopardy es mucho para ti...\n\n" + Game.getMessage(player),
                              ok_button="byeeeee :(")
                    exit()
                if player.lap > Game.GameLimit and player.money > Game.MoneyLimit and player.mistakes < Game.ErrorLimit:
                    Game.status = False
                    Game.Win = True
        if Game.Win:
            eg.msgbox("Has Ganado, te mereces el respeto de un pythonista...\ny te llevas $"
                      + str(player.money) + "\n" + Game.getMessage(player), ok_button="Salir")
Exemplo n.º 29
0
def list_streams_ui(streams,game):
    msg = "choose your "+game+" stream"
    title = 'Choose stream'
    choices = streams
    choicebox = eg.choicebox(msg,title,choices)
    if choicebox:
        return choicebox
    else:
        main()
Exemplo n.º 30
0
def show_naivebayes_presets():
    """
    Shows a selection of preset running values for Naive Bayes and returns the user selection.
    """
    msg ="Select preset values for Naive Bayes"
    title = "Naive Bayes presets"
    choices = ["Multinomial Naive Bayes", "Support Vector Machines", "Maximum Entropy"]
    preset_choice = eg.choicebox(msg, title, choices)
    pass
Exemplo n.º 31
0
def bs():
    while True:
        appinfo = gui.buttonbox(
            msg="Application: Waterf0x",
            title="HUGEHARD System",
            choices=("Open", "Info", "Cancel"),
            image=
            "/Users/jacobduan/Desktop/WORK/MY_NAME_IS_HACK-BETA/Images/waterf0x.gif"
        )
        if appinfo == "Open":
            web = gui.enterbox(
                msg="Welcome to Waterf0X broswer, type the website here",
                title="HUGEHARD System -- Waterf0X")
            if web == "pylogin.com/has_been_locked":
                gui.textbox(
                    msg="The user has been locked",
                    text=
                    "The user has been locked might be you don't have a account or your account is not safe, or your account has been hacked"
                )
            if web == "10.10.10.14/23":
                gui.textbox(
                    msg="PROBLEM\nNo.8",
                    text=
                    "The account cannot be hack might because the account has protect by some encrypt system that we don't know, until this encrypt system's source code is open to us, the hack might be succed",
                    title="Waterf0X")
            if web == "tools.me":
                gui.textbox(
                    msg="tools.me\nCOPYRIGHT TOOLS.ME, TEMPLE MONKEY COMPANY",
                    text=
                    "Welcome to tools.me, there are a lot of free tools and fee-paying tools here",
                    title="HUGEHARD System -- Waterf0X")
                dl = gui.choicebox(
                    msg="Tools",
                    choices=[
                        "Waterf0X - Fast and simple broswer",
                        "Mail Box - Fast speed email tools",
                        "HTTP Catcher - Powerful HTTP catching tools"
                    ],
                    title="HUGEHARD System -- Waterf0X")
                if dl == "Waterf0X":
                    gui.msgbox(
                        msg=
                        "You already download this application in your computer",
                        title="HUGEHARD System -- Waterf0X")
                    continue
                else:
                    gui.msgbox(
                        msg=
                        "You already download this application in your computer",
                        title="HUGEHARD System -- Waterf0X")
                    continue
            else:
                chs = gui.buttonbox(msg="Can't found the server, continue?",
                                    choices=["continue searching", "exit"],
                                    title="HUGEHARD System -- Waterf0X")
                if chs == "continue searching":
                    continue
                if chs == "exit":
                    exit()
        if appinfo == "Info":
            gui.msgbox(
                msg=ve + "1.13" + "\n" + sp + "95.3M" + "\n" + de +
                "WATERF0X GRUOP",
                title="HUGEHARD System",
                image=
                "/Users/jacobduan/Desktop/WORK/MY_NAME_IS_HACK-BETA/Images/waterf0x.gif"
            )
Exemplo n.º 32
0
import sys

import easygui as g

while 1:
    print(g.msgbox('嘿,你好'))
    msg='这段时间你学到了什么?'
    title='互动选项'
    choices = ['编程','谈恋爱','玩游戏']
    choice = g.choicebox(msg,title,choices)
    g.msgbox('你选择的是'+str(choice),'结果')

    if g.ccbox(msg,title):
        pass
    else:
        sys.exit(0)
Exemplo n.º 33
0
import easygui
flavor=easygui.choicebox("What is your favorite ice cream flavor?"
                         ,choices=['Vanilla','Chocolate','Strawberry'])
easygui.msgbox("You picked"+flavor)

print(flavor)
Exemplo n.º 34
0
import easygui
a=easygui.choicebox("enter the choice","choices",["encryption","decryption"])
if a=="encryption":
	print "you have selected encryption"
if a=="decryption":
	print "you have selected decryption"
Exemplo n.º 35
0
 def parse_generic(self,lines):
     if lines:
         (amount,vat) = extract_amount_and_vat(lines,self.vat_rates)
     if lines and amount:    
         self.vat[self.default_vat] = vat
         self.totals[self.default_vat] = amount-self.vat[self.default_vat]
         self.shipping = 0.0
         self.date = extract_date(lines)
         self.no = extract_no(lines)
         self.supplier = extract_supplier(lines)
         if self.check_if_present():
             return None
     else:
         amount = ""
         self.vat[self.default_vat] = ""
         self.totals[self.default_vat] = ""
         self.shipping = 0.0
         self.date = ""
         self.no = ""
         self.supplier = ""
     suppliers = gui_api_wrapper(Api.api.get_list,"Supplier")
     supplier_names = [supp['name'] for supp in suppliers]+['neu']
     def_supp = self.supplier if self.supplier in supplier_names else "neu"
     def_new_supp = "" if self.supplier in supplier_names else self.supplier
     layout = [  [sg.Text('Lieferant')],
                 [sg.OptionMenu(values=supplier_names, k='-supplier-',
                                default_value = def_supp)],
                 [sg.Text('ggf. neuer Lieferant')],
                 [sg.Input(default_text = def_new_supp,
                           k='-supplier-name-')],
                 [sg.Text('Rechnungsnr.')],     
                 [sg.Input(default_text = self.no, k='-no-')],
                 [sg.Text('Datum')],     
                 [sg.Input(key='-date-',
                           default_text = utils.show_date4(self.date)),
                  sg.CalendarButton('Kalender', target='-date-',
                                    format = '%d.%m.%Y',
                                    begin_at_sunday_plus=1)],
                 [sg.Text('MWSt')],     
                 [sg.Input(default_text = str(self.vat[self.default_vat]),
                           k='-vat-')],
                 [sg.Text('Brutto')],     
                 [sg.Input(default_text = str(amount), k='-gross-')],
                 [sg.Checkbox('Schon selbst bezahlt',
                              default=False, k='-paid-')],
                 [sg.Text('Kommentar')],     
                 [sg.Input(k='-remarks-')],
                 [sg.Button('Speichern')] ]
     window1 = sg.Window("Einkaufsrechnung", layout, finalize=True)
     window1.bring_to_front()
     event, values = window1.read()
     #print(event, values)             
     window1.close()
     if values:
         if '-supplier-' in values:
             self.supplier = values['-supplier-']
             if self.supplier == 'neu' and '-supplier-name-' in values:
                 self.supplier = values['-supplier-name-']
         if '-no-' in values:
             self.no = values['-no-']
         if '-date-' in values:
             date = utils.convert_date4(values['-date-'])
             if date:
                 self.date = date
         if '-vat-' in values:
             self.vat[self.default_vat] = \
                 float(values['-vat-'].replace(",","."))
         if '-gross-' in values:
             self.totals[self.default_vat] = \
                 float(values['-gross-'].replace(",","."))\
                 -self.vat[self.default_vat]
         if '-paid-' in values and values['-paid-']:
             self.paid_by_submitter = True
         if '-remarks-' in values:
             self.remarks = values['-remarks-']
     else:
         return None
     self.compute_total()
     accounts = self.company.leaf_accounts_for_credit
     account_names = [acc['name'] for acc in accounts]
     pinvs = self.company.purchase_invoices[self.supplier]
     paccs = [pi['expense_account'] for pi in pinvs if 'expense_account' in pi]
     paccs = list(set(paccs))
     for acc in paccs:
         try:
             account_names.remove(j)
         except Exception:
             pass
     account_names = paccs + account_names
     title = 'Buchungskonto wählen'
     msg = 'Bitte ein Buchungskonto wählen\n'
     account = easygui.choicebox(msg, title, account_names)
     if not account:
         return None
     self.assign_default_e_items({self.default_vat:account})
     return self
Exemplo n.º 36
0
import numpy as np
import matplotlib.pyplot as plt  #plot function  library
import sys
import pandas as pd  #csv file deal function library
import os
from datetime import datetime
from datetime import timedelta

import tkinter as tk  #obtain the file path library
from tkinter import filedialog  #obtain the file path library

import easygui as fgui  #obtain the file path library with easygui

ModLabel = ['WindowsMod', 'ConsoleMod', 'Thank~U']
ModLabelReturn = fgui.choicebox('Select The Mod ?', choices=ModLabel)
if ModLabelReturn == 'WindowsMod':
    title = fgui.msgbox(msg='Select the BCGFile',
                        title=' ',
                        ok_button='OK',
                        image=None,
                        root=None)
    BCGFile = fgui.fileopenbox()
    title = fgui.msgbox(msg='Select the ECGFile',
                        title=' ',
                        ok_button='OK',
                        image=None,
                        root=None)
    ECGFile = fgui.fileopenbox()
    print(BCGFile)
    print(ECGFile)
            writer.writerow(line)
        writer.writerow([team, totRes])


def ask_question(tq):
    a = tq.possibles
    random.shuffle(a)
    q = easygui.buttonbox(tq.question, "?", choices=[a[0], a[1], a[2], a[3]])
    answer = tq.answer
    if q == answer:
        result = 1
        easygui.msgbox("Yay!")
    else:
        result = 0
        easygui.msgbox("Try again!")
    return result


ms = ['Leader board', 'Play', 'Quit']
mainMenu = ""
while mainMenu != "Quit":
    mainMenu = ""
    while not mainMenu in ms:
        mainMenu = easygui.choicebox(
            'Welcome! We are very excited to have you here to play the Acolympics!',
            'Pick what to do', ms)
    if mainMenu == 'Leader board':
        show_leader_board()
    elif mainMenu == 'Play':
        show_play()
Exemplo n.º 38
0
sem_string = c_programacao + r"\*" + sem + r"*"

c_sem = glob.glob(sem_string)
c_sem = c_sem[0]

#Seleciona arquivo com string "original"
for filename in os.listdir(c_sem):
    if fnmatch.fnmatch(filename, "*oficial*.xlsm"):
        L.append(filename)
        print(filename)

#Trata quando acha mais de um arquivo
if len(L) != 1:
    msg = "Mais de um arquivo foi encontrado. Selecione o arquivo desejado:"
    title = "Escolha um arquivo para carga"
    choice = g.choicebox(msg, title, L)
    L = choice
if type(L) == list:
    L = L[0]

#Abrir as ordens no pandas e copiar na área de transferência
c_arquivo = os.path.join(c_sem, L)
dados = pd.read_excel(c_arquivo,
                      skiprows=5,
                      sheet_name='Programação Semanal',
                      convert_float=False,
                      skip_blank_lines=True)
dados.dropna(subset=['CONFIRMAÇÃO'], inplace=True)
dados1 = dados.astype({"CONFIRMAÇÃO": "int32"})
dados1["CONFIRMAÇÃO"].to_clipboard(excel=True, index=False, header=None)
Exemplo n.º 39
0
    # Initialize user info, and data available based on that
    ###########################################################################
    users = ['dgranville', 'mmacpherson', 'dlarussa']
    user = easygui.enterbox('Enter your TOH username')
    while user not in users:
        user = easygui.enterbox('Username not found.\nEnter your TOH username')
    # read in previous user data if it exists, if not create fresh set of user data
    if user + '.p' in os.listdir(results_folder):
        user_data = pickle.load( open( results_folder + '\\' + user + ".p", "rb" ) )
    else:
        user_data = []
        
    ###########################################################################
    # Allow user to select structure to evaluate
    ###########################################################################
    structure_wanted_human = easygui.choicebox('Select the structure to evaluate:', 'Structure Options', structure_choices)
    structure_wanted_machine = structure_wanted_human.upper() + '_1'    
    
    # generate list of patient folder names
    patient_list = [dicom_data_folder + '//' + x for x in os.listdir(dicom_data_folder)]
    
    # generate list of structure dicom paths (patient + machine/human combinations)
    structure_dicom_list = [x + '//' + machine_rts_filename for x in patient_list] + \
                           [x + '//' + human_rts_filename for x in patient_list]
    structure_list = []
    for dicom in structure_dicom_list:
        for structure in structure_choices:
            structure_list.append({'rts filename': dicom, 'structure': structure})
    

   # delete structure sets that have already been tests from this user!
Exemplo n.º 40
0
                             batch_detection)
from easygui import choicebox, textbox, fileopenbox
from docx import Document
import os
import pyperclip

"""
Module that provides a destination language choice. Further languages can be
added from the following list under choices:
https://py-googletrans.readthedocs.io/en/latest/#googletrans-languages
"""

source_lang = "en"
choices = ["el"]
desti_lang = choicebox(
    "What is the Destination Language?", "translator", choices=choices
)


"""
Module that extracts text from MS XML Word document (.docx).
(Inspired by python-docx <https://github.com/mikemaccana/python-docx>)
"""

WORD_NAMESPACE = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
PARA = WORD_NAMESPACE + "p"
TEXT = WORD_NAMESPACE + "t"


def get_docx_text(filename):
    """
Exemplo n.º 41
0
pygame.init()

# offer user to choose resolution of the window
resolutions = {
    '640 × 480': [640, 480],
    '800 × 600': [800, 600],
    '1024 × 768': [1024, 768],
    '1280 × 1024': [1280, 1024],
    '1440 × 900': [1440, 900],
    '1680 × 1050': [1680, 1050],
    '1920 × 1080': [1920, 1080],
    '2560 × 1440': [2560, 1440]
}
resolution_choice = easygui.choicebox("Please select resolution",
                                      choices=resolutions.keys(),
                                      preselect=1)
resolution = resolution_x, resolution_y = resolutions[resolution_choice]
screen = pygame.display.set_mode(resolution)
screen.fill([255, 255, 255])

# resolution_x = resolution[0]
# resolution_y = resolution[1]

cell_size = 40
cell_size_work = copy(cell_size)

field0 = int(cell_size_work / 2)
step = cell_size_work
center_field_x = field0 + step * (int(resolution_x / step / 2) - 1)
center_field_y = field0 + step * (int(resolution_y / step / 2) - 1)
Exemplo n.º 42
0
def four():
    result = gui.choicebox(breadtext, title, choices)
    print(result)  # Returnere værdien
Exemplo n.º 43
0
 def choisebox(self, message, dictfiles):
     return g.choicebox(msg=message, choices=dictfiles)
# scriptWS = args.filepath
# aircraft = args.aircraft_type
# print("filepath:{0}".format(scriptWS))
# print("aircraft is {0}".format(aircraft))

easygui.msgbox(
    msg=
    "the next window will ask you to select the date_aircraft folder, hit the button to continue",
    title="hello!",
    ok_button="OK")
scriptWS = easygui.diropenbox(msg="date_aircraft folder")

msg = "select aircraft type"
title = "Aircraft Type"
choices = ['alta', 'lemhex']
aircraft = easygui.choicebox(msg, title, choices)

#set up folders
rootWS = os.path.dirname(scriptWS)
day_aircraft = os.path.split(scriptWS)[1]

#make lists
AllImgList = []
ImgList = []  #this list will contain all the image names
ImgTime = []  #this list will contain the original image time stamp
CorrTimeList = []  #this list will contain the corrected image time stamps
LaserList = []  #this list will contain the laser altitudes
LaserImg = []  #the image that the laser was pulled for
Time130List = [
]  #if the laser value was pulled from a different time, which time
BaroImg = []  #the image that the barometer was pulled for
Exemplo n.º 45
0
import easygui as ei

menu_options = [
    "Cadastrar cliente", "Remover cliente", "Consultar clientes", "Sair"
]
new_clients_fields = ["CPF/CNPJ", "Nome"]
cliente = dict()
clientes = dict()
result = ''
new_client = []
clientes_list = []

while True:
    result = ei.choicebox("Escolha uma opção", "Menu", menu_options)

    if result == menu_options[0]:  # Cadastrar Cliente
        new_cliente = ei.multenterbox("Informe os dados do cliente",
                                      "Cadastrar cliente", new_clients_fields)

        cliente["cpfcnpj"] = new_cliente[
            0]  #Salva o CPF em um objeto "Cliente"
        cliente["nome"] = new_cliente[
            1]  #Salva o Nome no mesmo objeto "Cliente"

        clientes[new_cliente[
            0]] = cliente  #Salva o objeto "Cliente" acima, em um objeto "Clientes", com vários outros

    elif result == menu_options[1]:
        if len(clientes) == 0:
            ei.msgbox("Não há clientes cadastrados", "Ops...")
        else:
Exemplo n.º 46
0
from pydub.utils import mediainfo
import easygui

__author__ = "Aaron Frank"
__copyright__ = "Copyright 2020"
__credits__ = ["Aaron Frank"]

__license__ = "MIT"
__version__ = "0.0.1"

# use easygui to get filepath and file name
fp = easygui.fileopenbox("Select Audio File",
                         "MP3 to TXT",
                         filetypes=['*.mp3'])
fl = easygui.choicebox("Select a Language",
                       "MP3 to TXT",
                       choices=['de-DE', 'en-US', 'en-CA', 'es-ES'])
fn = fp.split('/')[-1].split('.')[0]
fi = mediainfo(fp)

# Connect To storage client an upload file to bucket.
storage_client = storage.Client()
speech_client = speech_v1p1beta1.SpeechClient()

try:
    bucket_name = 'mp3-to-speech-audio'  # TODO: Set unique bucket name. [within your organisation]
    bucket = storage_client.create_bucket(bucket_name)
except Conflict:
    bucket = storage_client.get_bucket(bucket_name)
finally:
    blob = bucket.blob('%s.mp3' % fn)
Exemplo n.º 47
0
import easygui
title = "Cuantas lineas de conteo?"
msg = "Seleccione el numero de lineas de conteo que quiere poner, se recomiendan maximo 6 lineas de conteo"
choices = ["1", "2", "3", "4", "5", "6"]
choice = easygui.choicebox(msg, title, choices)
type(choice)
lineasDeConteo = int(choice)
print "usted ha seleccionado ", lineasDeConteo, " lineas de conteo"
Exemplo n.º 48
0
 def _choicebox(msg='', choices=[], title=''):
     return eg.choicebox(msg, title, choices)
Exemplo n.º 49
0
files = (file for file in files
         if os.path.isfile(path=os.path.join(dir_path, file)))
files = sorted(files,
               key=lambda fn: os.path.getatime(os.path.join(dir_path, fn)))

hash_table = dict()
duplicates = []

for filename in files:
    file_path = os.path.join(dir_path, filename)

    with open(file_path, 'rb') as filepointer:
        content = filepointer.read()

    hasher = hashlib.sha256()
    hasher.update(content)
    _hash = hasher.hexdigest()

    if _hash in hash_table.keys():
        duplicates.append(file_path)
    else:
        hash_table[_hash] = file_path

for dup in duplicates:
    filename = os.path.split(dup)[1]
    selection = easygui.choicebox(
        title="Delete Duplicates?",
        msg="Delete file permanently {FILENAME}?".format(FILENAME=filename),
        choices=['delete-it', 'keep-it'])
    if selection == 'delete-it':
        os.remove(dup)
Exemplo n.º 50
0
def on_press(key):
    global brightness, contrast, EV, saturation, zoom
    global speed, LEDintensity
    global arrowkey_mode, path, filename, recording_mode

    ### F1: keyboard shortcuts

    if key == Key.f1:
        shortcuts()

######## CAMERA

### Camera preview modes, video or photo

    if key == Key.tab:
        if recording_mode == False:
            camera.resolution = (1920, 1080)
            camera.annotate_text = "Video mode"
            recording_mode = True
        elif recording_mode == True:
            if HighResolution == True:
                camera.resolution = (3280, 2464
                                     )  # Pi camera v2 max resolution, 8MP
            else:
                camera.resolution = (1920, 1080)  # reduced resolution, Full HD
            camera.annotate_text = "Photo mode"
            recording_mode = False

### Reset camera settings
    if key == KeyCode(char='0'):
        camera_reset()

### digital zoom

    if key == KeyCode(char='+'):
        if zoom > 0.2:
            zoom = zoom - 0.1
            camera.zoom = (0, 0, zoom, zoom)
            annotate_text = "Digital zoom:" + str(round(1 / zoom, 2)) + "X"
            camera.annotate_text = annotate_text

    if key == KeyCode(char='-'):
        if zoom < 1.0:
            zoom = zoom + 0.1
            camera.zoom = (0, 0, zoom, zoom)
            annotate_text = "Digital zoom:" + str(round(1 / zoom, 2)) + "X"
            camera.annotate_text = annotate_text

### start and stop camera preview

    if key == KeyCode(char='P'):
        camera.start_preview()

    if key == KeyCode(char='p'):
        camera.stop_preview()

### brightness

    if key == KeyCode(char='B'):
        if brightness != 100:
            brightness += 5
            camera.brightness = brightness
            annotate_text = "Brightness:" + str(brightness) + "%"
            camera.annotate_text = annotate_text

    if key == KeyCode(char='b'):
        if brightness != 0:
            brightness -= 5
            camera.brightness = brightness
            annotate_text = "Brightness:" + str(brightness) + "%"
            camera.annotate_text = annotate_text

### contrast

    if key == KeyCode(char='C'):
        if contrast != 100:
            contrast += 5
            camera.contrast = contrast
            annotate_text = "Contrast:" + str(contrast) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='c'):
        if contrast != -100:
            contrast -= 5
            camera.contrast = contrast
            annotate_text = "Contrast:" + str(contrast) + "%"
            camera.annotate_text = annotate_text

### EV compensation

    if key == KeyCode(char='V'):
        if EV != 25:
            EV += 1
            camera.exposure_compensation = EV
            annotate_text = "EV:" + str(EV)
            camera.annotate_text = annotate_text
    if key == KeyCode(char='v'):
        if EV != -25:
            EV -= 1
            camera.exposure_compensation = EV
            annotate_text = "EV:" + str(EV)
            camera.annotate_text = annotate_text

### saturation

    if key == KeyCode(char='S'):
        if saturation != 100:
            saturation += 5
            camera.saturation = saturation
            annotate_text = "Saturation:" + str(saturation) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='s'):
        if saturation != -100:
            saturation -= 5
            camera.saturation = saturation
            annotate_text = "Saturation:" + str(saturation) + "%"
            camera.annotate_text = annotate_text

### ISO

    if key == KeyCode(char='i'):
        camera.preview_alpha = 0
        ISO_choices = ["0", "100", "200", "320", "400", "500", "640", "800"]
        ISO_selected = easygui.choicebox("Select ISO (default: 0 for auto)",
                                         "ISO", ISO_choices)
        if ISO_selected is not None:
            camera.iso = int(ISO_selected)
        camera.preview_alpha = 255

### white balance

    if key == KeyCode(char='W'):
        camera.preview_alpha = 0
        WB_choices = [
            "off", "auto", "sunlight", "cloudy", "shade", "tungsten",
            "fluorescent", "flash", "horizon"
        ]
        WB_selected = easygui.choicebox(
            "Select white balance mode (default: auto)", "White Balance",
            WB_choices)
        if WB_selected is not None:
            camera.awb_mode = WB_selected
        if WB_selected == "off":
            WB_gain = easygui.enterbox(
                "White balance gain - typical values between 0.9 and 1.9",
                "White balance gain", "1.0")
            if WB_gain is not None:
                camera.awb_gains = float(WB_gain)
        camera.preview_alpha = 255

### frame rate

    if key == KeyCode(char='r'):
        camera.preview_alpha = 0
        Framerate_choices = [
            "30", "20", "15", "10", "5", "2", "1", "0.5", "0.1", "manual"
        ]
        Framerate_selected = easygui.choicebox("Select framerate", "Framerate",
                                               Framerate_choices)
        if Framerate_selected == "manual":
            Framerate_selected = easygui.enterbox("Framerate", "Input", "")
        if Framerate_selected is not None:
            camera.framerate = float(Framerate_selected)
        camera.preview_alpha = 255

### exposure time (shutter speed)

    if key == KeyCode(char='e'):
        camera.preview_alpha = 0
        Exposure_choices = [
            "0", "10", "20", "50", "100", "200", "500", "1000", "manual"
        ]
        Exposure_selected = easygui.choicebox(
            "Select exposure time in ms (default: 0, auto)\n\
Maximum exposure time is determined by the framerate",
            "Exposure time (shutter speed)", Exposure_choices)
        if Exposure_selected == "manual":
            Exposure_selected = easygui.enterbox("Exposure time (ms)", "Input",
                                                 "")
        if Exposure_selected is not None:
            camera.shutter_speed = int(Exposure_selected) * 1000
        camera.preview_alpha = 255

### exposure modes

    if key == KeyCode(char='E'):
        camera.preview_alpha = 0
        ExposureMode_choices = [
            "off", "auto", "night", "nightpreview", "backlight", "spotlight"
        ]
        ExposureMode_selected = easygui.choicebox("Exposure mode",
                                                  "Exposure mode",
                                                  ExposureMode_choices)
        if ExposureMode_selected is not None:
            camera.exposure_mode = ExposureMode_selected
        camera.preview_alpha = 255

### select folder and set filename prefix

    if key == KeyCode(char='F'):
        camera.preview_alpha = 0
        path = easygui.diropenbox()
        camera.preview_alpha = 255
    if key == KeyCode(char='f'):
        camera.preview_alpha = 0
        filename = easygui.enterbox("Filename prefix", "Input", "")
        camera.preview_alpha = 255

######## MOTORIZED STAGE

### Ctrl: change motor speed

    if key == Key.ctrl_l or key == Key.ctrl_r:
        if speed == slow:
            speed = medium
            camera.annotate_text = "Motor speed = medium"
        elif speed == medium:
            speed = fast
            camera.annotate_text = "Motor speed = fast"
        elif speed == fast:
            speed = slow
            camera.annotate_text = "Motor speed = slow"

### keyboard arrow keys, Alt key toggles between X-Y and Rotate-Tilt
### send Arduino a string to control the motors, e.g. "-100X," or "500Y,"
### the integer defines the direction and the speed of the motor, the letter selects the motor

    if key == Key.alt_l or key == Key.alt_r:
        if arrowkey_mode == True:
            arrowkey_mode = False
            camera.annotate_text = "X-Y"
        elif arrowkey_mode == False:
            arrowkey_mode = True
            camera.annotate_text = "Rotate-Tilt"

    if key == Key.left:
        if arrowkey_mode == False:
            data = str(speed * -1) + "X,"
        else:
            data = str(speed * -1) + "R,"
        ser.write(data.encode())

    if key == Key.right:
        if arrowkey_mode == False:
            data = str(speed) + "X,"
        else:
            data = str(speed) + "R,"
        ser.write(data.encode())

    if key == Key.down:
        if arrowkey_mode == False:
            data = str(speed * -1) + "Y,"
        else:
            data = str(speed * -1) + "T,"
        ser.write(data.encode())

    if key == Key.up:
        if arrowkey_mode == False:
            data = str(speed) + "Y,"
        else:
            data = str(speed) + "T,"
        ser.write(data.encode())

### Z up and down, Page up and Page down

    if key == Key.page_up:
        data = str(speed) + "Z,"
        ser.write(data.encode())

    if key == Key.page_down:
        data = str(speed * -1) + "Z,"
        ser.write(data.encode())

### Camera up and down, Home and End

    if key == Key.home:
        data = str(speed) + "C,"
        ser.write(data.encode())

    if key == Key.end:
        data = str(speed * -1) + "C,"
        ser.write(data.encode())


######## LED

### LED intensity, max. value in the data is set to 20 to make it compatible with the joystick
### PWM of the LED driver works in the opposite direction
### Intensity is controlled in 5% increments

    if key == KeyCode(char='L'):
        if LEDintensity != 20:
            LEDintensity += 1
            data = str(20 - LEDintensity) + "L,"
            ser.write(data.encode())
            annotate_text = "LED intensity:" + str(LEDintensity * 5) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='l'):
        if LEDintensity != 0:
            LEDintensity -= 1
            data = str(20 - LEDintensity) + "L,"
            ser.write(data.encode())
            annotate_text = "LED intensity:" + str(LEDintensity * 5) + "%"
            camera.annotate_text = annotate_text
Exemplo n.º 51
0
def TesteRapido():
    Variaveis.TesteRapido = 'N'
    Variaveis.NQtdProd = 0
    if Variaveis.CodLoja != '0':
        msg = "Tipo do Teste"
        title = "Optar por um Teste Rapido"

        if Variaveis.DocFiscal == 'NFCE':
            choices = [
                "1 | Informar um Produto e um Vendedor (Teste Rapido)",
                "2 | Validação com Varios Produtos (Teste Lento)",
                "99 | Tratar Rejeiçoes"
            ]
        else:
            choices = [
                "1 | Informar um Produto e um Vendedor (Teste Rapido)",
                "2 | Informar Quantidade de produtos e um Vendedor (Teste Rapido 2)",
                "3 | Validação com Varios Produtos (Teste Lento)"
            ]

        Lista = easygui.choicebox(msg, title, choices)
        if Lista != None:
            sSelecao = str((Lista[:Lista.find('|')].strip()))
        else:
            sSelecao = '0'

        if sSelecao == '1':
            Variaveis.TesteRapido = 'S'
        if sSelecao == '2':
            Variaveis.TesteRapido = 'Q'
        if sSelecao == '3':
            Variaveis.TesteRapido = 'N'
        if sSelecao == '99':
            Variaveis.TesteRapido = 'R'

        if Variaveis.DocFiscal == 'NFCE' and Variaveis.TesteRapido == 'R':
            Tela.TratamentoRejeicoes()
            Variaveis.TesteRapido = 'S'

        if Variaveis.TesteRapido == 'S':
            msg = "Informe o Produto"
            title = "VSM - Automação"
            fieldNames = ["Informao Código do Produto"]
            fieldValues = easygui.multenterbox(msg, title, fieldNames)
            if fieldValues == None:
                sCod = 0
                sys.exit()
            else:
                sCod = int(''.join(fieldValues))  # Converte Vetor para String
            Variaveis.CodProd = str(sCod)

        if Variaveis.TesteRapido == 'Q':
            msg = "Informe a Quantidade de Produtos"
            title = "VSM - Automação"
            fieldNames = ["Informe a Quantidade"]
            fieldValues = easygui.multenterbox(msg, title, fieldNames)
            if fieldValues == None:
                sCod = 0
                sys.exit()
            else:
                sCod = int(''.join(fieldValues))  # Converte Vetor para String
            Variaveis.NQtdProd = str(sCod)

        sCod = 0
        if Variaveis.DocFiscal == 'NFE' or Variaveis.TesteRapido == 'Q':
            msg = "Informe o Cliente"
            title = "VSM - Automação"
            fieldNames = ["Informao Código do Cliente"]
            fieldValues = easygui.multenterbox(msg, title, fieldNames)
            if fieldValues == None:
                sCod = 0
                sys.exit()
            else:
                sCod = int(''.join(fieldValues))  # Converte Vetor para String

        Variaveis.Cli = str(sCod)

        if Variaveis.VendedorAutomatico == 'N':
            msg = "Informe o Vendedor"
            title = "VSM - Automação"
            fieldNames = ["Informao Código do Vendedor"]

            fieldValues = easygui.multenterbox(msg, title, fieldNames)
            if fieldValues == None:
                sCod = 0
                sys.exit()
            else:
                sCod = int(''.join(fieldValues))  # Converte Vetor para String
                Variaveis.VendedorAutomatico = 'N'
            Variaveis.CodVendedor = str(sCod)
Exemplo n.º 52
0
    CAMERA = webCam(id=cam_id, videofile=simulate, size=webcam_size)

    defect_file = new_log_filename()
    logDefects = recordDefects(os.path.join(log_folder, defect_file),
                               defect_count)

    last_long, last_lati = 00, 0.0
    count_waiting, count_upload = 0, 0
    (s_upload, s_gps, s_cam, msg) = check_env((upload_host, \
        upload_port, recv_bit, upload_interval))
    if (len(msg) > 0):
        choices = [
            "1) re-scan", "2) continue", "3) exit ap", "4) reboot",
            "5) poweroff"
        ]
        ans = choicebox(msg, title='環境檢查', choices=choices)
        print("ans=", ans[0])
        chk_env_actions(ans[0])
        print("ans=", ans[0])
        while ans[0] == '1' and len(msg) > 0:
            gpsDevice = GPS(comport=comPort, portrate=baudRate, test=False)
            last_gps_logging = time.time()
            try:
                CAMERA.release()
                CAMERA = webCam(id=cam_id,
                                videofile=simulate,
                                size=webcam_size)
            except:
                pass

            (s_upload, s_gps, s_cam, msg) = check_env((upload_host, \
Exemplo n.º 53
0
import easygui as eg
import physics4u as phy4
eg.msgbox(
    "Thank you for choosing Vector Calculator\nPlease input the value as instructed to avoid unexpected error\nClick [Continue] to start",
    "Vector Calculator", "Continue")
anotherloop = 1
while anotherloop == 1:
    msg = "Please select the mode you want"
    title = "Mode selecting"
    modes = ["Total Vector", "Force Resolution"]
    confirm = 0
    while confirm == 0:
        sdmode = eg.choicebox(msg, title, modes)
        msg = "Are you sure to choose " + sdmode + "?"
        confirm = eg.boolbox(msg=msg,
                             title="Confirm your choice",
                             choices=("Yes", "No"),
                             image=None)
    mulcho = []
    mulchof = []
    nvct = int(
        eg.enterbox(msg="Number of Vectors",
                    title="",
                    default="",
                    strip=True,
                    image=None,
                    root=None))
    for i in range(1, nvct + 1):
        magn = "Magnitude" + str(i) + "="
        mulcho.append(magn)
        mulchof.append("")
Exemplo n.º 54
0
def newbatch():
    manufacturedate = datetime.today(
    )  #the date the batch is manufctured which is todays date
    with open(
            "batchindex.json", "r"
    ) as f:  #reads in the "batchindex" json file to append newly created batch numbers
        indata = json.load(f)
        f.close()
    mylist = indata["UsedBatches"]
    if len(
            mylist
    ) == 0:  #if there is no batch number, create one, otherwise, start with the first batch number
        batchindex = 1
    else:
        batchindex = len(mylist) + 1
    print("List of numbers extracted from dictionary :",
          mylist)  #prints existing batch numbers
    batchno = int(
        (manufacturedate.strftime("%d%m%y") + "{0:04}".format(batchindex))
    )  #formats the batch number of DDMMYY0001 (formatting of manufacturedate: https://docs.python.org/2/library/datetime.html)
    mylist.append(batchno)  #appends the batch number to a list
    outdata = {"UsedBatches": mylist}
    with open("batchindex.json",
              "w") as f:  #writes in the batch list into the json file
        json.dump(outdata, f)
    f.close()
    newbatch = Batch(batchno)

    #allows a user to select how many components they want
    newbatch.noofcomponents = (easygui.integerbox(
        msg="How many components in this batch?(1-9999)",
        default=1,
        lowerbound=1,
        upperbound=9999))

    #allows user to select the component type they want which prints the choice they select
    newbatch.type = easygui.choicebox(
        msg="Select Component Type",
        choices=["Winglet Strut", "Door Handle", "Rudder Pin"])
    if newbatch.type == "Winglet Strut":
        print("Winglet Strut")
    elif newbatch.type == "Door Handle":
        print("Door Handle")
    elif newbatch.type == "Rudder Pin":
        print("Rudder Pin")

    #Allows a user to select a component size out of the two options
    newbatch.size = easygui.buttonbox(msg="Select Component Size",
                                      choices=["A320 Series", "A380 Series"])
    if newbatch.size == "A320 Series":
        print("A320 Series")
    elif newbatch.size == "A380 Series":
        print("A380 Series")

    newcomplist = []  #a list for the new components
    componentstatus = []  #list of the component status
    for n in range(
            1, newbatch.noofcomponents + 1
    ):  #creates selected number of components based on how many components the user wants
        batchnostr, strn = batchno, "{0:04}".format(n)
        number = "{0}-{1}".format(
            batchno, strn
        )  #formats the new component numbers as a string.  Source used to format as a strong: https://stackoverflow.com/questions/15593775/python-joining-string-expressions-with-a-hyphen
        newcomp = Component(number)
        newcomp.printcomponent()  #prints the new copmonent numbers
        newcomplist.append(
            number
        )  #appends the new component numbers to the new component list
        componentstatus.append(
            number + ": Unfininshed Work"
        )  #prints the component number with their unfinished status

    #result asking the user to verify the right input, while formatting these variables into a string
    result = ("This batch contains %d %s %s is this correct? Y/N") % (
        newbatch.noofcomponents, newbatch.type, newbatch.size)
    yn = easygui.ynbox(
        result)  #input the result varliable message into an easygui yes/no box
    if yn is False:  #if the user selects no, it returns them to the main menu
        main()
    else:
        hhmm = str(manufacturedate)
        ddmmyy = str(datetime.now().strftime("%H:%M"))
        dt = ("Batch and Component records created at %s on %s") % (
            ddmmyy, hhmm
        )  #prints the date and time of when the users new batch was created
        easygui.msgbox(
            dt
        )  #input the date time message into an easygui message box to be displayed to the user

    #asks the user if they want to see their batch details
    showdetails = "Show batch details? Y/N"
    yn = easygui.ynbox(msg=showdetails)
    if yn is False:  #if the user selects no, it returns them to the main menu
        main()
    else:  #if the user selects yes, this prints out their batch details
        batchno = "Batch Number: %s" % newbatch.batchno
        type = "\nComponent Type: %s" % newbatch.type  #\n makes the message take a new line after each batch attribute to be displayed to the user properly
        size = "\nComponent Size: %s" % newbatch.size  #%s inserts the new batch attribute into the string without any awkward or additional formatting to the variable
        noofcomponents = "\nNumber of Components: %s" % newbatch.noofcomponents
        serialnos = "\nSerial Numbers: %s" % newcomplist
        componentstatus = "\nComponent Status: %s" % componentstatus
        easygui.msgbox(
            msg=batchno + type + size + noofcomponents + serialnos +
            componentstatus
        )  #prints the batch details into a user friendly easygui message box
    main(
    )  #returns the user to the main menu after completion of batch details
Exemplo n.º 55
0
import easygui
smak = easygui.choicebox("Jaki jest Twój ulubiony smak lodów?",
                         choices = ['Waniliowy', 'Czekoladowy', 'Truskawkowy'] )
easygui.msgbox ("Wybra³eœ " + smak)
Exemplo n.º 56
0
        MYSQL.insert(self.IP, self.TIME(), sh)  #保存在数据库
# 事件

    def BTN3(self, event):  # 事件触发删除历史命令
        if easygui.ccbox("你确定要删除本地和数据库的历史记录吗?"):
            pass
        else:
            cccccccc
        MYSQL.delete()
# 事件

    def ACM(self, event):
        if MYSQL.active() == "ok":
            easygui.msgbox("数据库连接成功,操作历史可以保存到数据库!!", "提示")
        else:
            easygui.msgbox("数据库连接失败!!", "提示")


#TIME

    def TIME(self):
        return (time.strftime("%m-%d %H:%M:%S", time.localtime(time.time())))

if __name__ == "__main__":
    IP = easygui.choicebox('选择要修改的服务器\n', '选择你需要管理的服务器', ['192.168.116.200'])
    if IP == None:
        sys.exit(1)
    Start = Tk()
    MY_GUI(Start, IP).XIAOXUE()
    Start.mainloop()
Exemplo n.º 57
0
 def searchfileface(self):
     defaultdir = easygui.enterbox(msg="请输入你想查找的文件目录:")
     target = easygui.enterbox(msg=("请输入你想要查找的文件名:"))
     choice = SearchFile().searchfile(defaultdir, target)
     resultbox = easygui.choicebox(
         msg="在{}路径下搜索到的符合条件的文档如下:".format(defaultdir), choices=choice)
import os
import sys
import easygui as g
title1 = '小唐制作'
path = g.enterbox(
    '输入你工作文件夹的存放路径(请直接去文件管理器复制)',
    title=title1)  #r"C:\Users\Administrator\Desktop"  # 工作文件夹存放路径
filename1 = '一种专利文案'  # 你的模板名称,全部一致
filename2 = g.enterbox('输入你分配的案件名称', title=title1)  # 分配的案件名称
user_choice = g.choicebox(msg='确定运行?', title=title1, choices=('yes', 'no'))
if user_choice == 'no':
    g.msgbox(msg='按任意键退出', title=title1)
    sys.exit(0)
elif user_choice == 'yes':

    path1 = path + '\\' + filename1
    path2 = path + '\\' + filename2
    path2_1 = path2 + '\\' + filename1
    path2_2 = path2 + '\\' + filename2
    path2_2_1 = path2_2 + '\\' + filename1
    path2_2_2 = path2_2 + '\\' + filename2
    os.rename(path1, path2)  # 重命名第一层文件夹

    os.rename(path2_1, path2_2)  # 重命名第二层文件夹

    os.rename(path2_2_1 + '————说明书附图.pdf', path2_2_2 + '————说明书附图.pdf')

    os.rename(path2_2_1 + '————摘要附图.pdf',
              path2_2_2 + '————摘要附图.pdf')  # 重命名两个pdf文件

    os.rename(path2 + '\\' + '图' + '\\' + filename1 + '.spolt',
Exemplo n.º 59
0
def escolher(msg, opcoes):
    '''escolher(msg, opcoes) -> opção

    Exibe uma janela que permite que o usuário escolha uma dentre várias opções
    e retorna a opção escolhida.'''
    return eg.choicebox(msg, TITLE, opcoes)
Exemplo n.º 60
0
fieldValues = []  # we start with blanks for the values
fieldValues = g.multenterbox(msg, title, fieldNames)
n = int(fieldValues[0])

for i in range(0, n):
    msg = "必修课%d-输入分数" % (i + 1)
    title = "必修课:分数"
    fieldNames = ["分数"]
    fieldValues = []  # we start with blanks for the values
    fieldValues = g.multenterbox(msg, title, fieldNames)
    a_1.append(int(fieldValues[0]))
    msg_2 = "必修课%d-选择绩点" % (i + 1)
    title_2 = "必修课:绩点"
    choices = list(range(1, max_g + 1))
    if max_g != 1:
        choice = g.choicebox(msg_2, title_2, choices)
        b_1.append(int(choice))
    else:
        b_1.append(1)

a_1_tot = sum(np.array(a_1) * np.array(b_1))
b_1_tot = sum(np.array(b_1))
# print(a_1_tot,b_1_tot)
ave_1 = a_1_tot / b_1_tot

msg = "选修课"
title = "选修课数目"
fieldNames = ["数目"]
fieldValues = []  # we start with blanks for the values
fieldValues = g.multenterbox(msg, title, fieldNames)
m = int(fieldValues[0])