Example #1
0
 def goto_file_line(self, event=None):
     if self.file_line_progs is None:
         l = []
         for pat in self.file_line_pats:
             l.append(re.compile(pat, re.IGNORECASE))
         self.file_line_progs = l
     # x, y = self.event.x, self.event.y
     # self.text.mark_set("insert", "@%d,%d" % (x, y))
     line = self.text.get("insert linestart", "insert lineend")
     result = self._file_line_helper(line)
     if not result:
         # Try the previous line.  This is handy e.g. in tracebacks,
         # where you tend to right-click on the displayed source line
         line = self.text.get("insert -1line linestart",
                              "insert -1line lineend")
         result = self._file_line_helper(line)
         if not result:
             tkMessageBox.showerror(
                 "No special line",
                 "The line you point at doesn't look like "
                 "a valid file name followed by a line number.",
                 parent=self.text)
             return
     filename, lineno = result
     edit = self.flist.open(filename)
     edit.gotoline(lineno)
Example #2
0
	def save(self):
		""" сохраняем настройки """
		s=self.rb_var.get()
		if s==0:
			self.app.app.app.sets.sync_enable=False
		elif s==2:
			self.app.app.app.sets.sync_enable=True
			self.app.app.app.sets.sync_period=0
		elif s==1:
			try:t=int(self.cron_ent.get())
			except:
				box.showerror(title='Ошибка',message='Не корректное время!')
				self.app.win.deiconify()
				return	
			if t<15:
				box.showerror(title='Ошибка',message='Время должно быть больше 15 минут!')
				self.app.win.deiconify()
				return	
			self.app.app.app.sets.sync_enable=True
			self.app.app.app.sets.sync_period=t	
		point=self.points_var.get()
		passw=self.passw_ent.get()
		if passw=='*****':
			passw=self.app.app.app.sets.sync_passw
		else:
			passw=md5py.new(passw).hexdigest()
		self.app.app.app.sets.sync_login=self.login_ent.get()
		self.app.app.app.sets.sync_passw=passw	
		self.app.app.app.sets.sync_point=point
		self.app.reload=True
Example #3
0
 def filename_changed_edit(self, edit):
     edit.saved_change_hook()
     try:
         key = self.inversedict[edit]
     except KeyError:
         print "Don't know this EditorWindow object.  (rename)"
         return
     filename = edit.io.filename
     if not filename:
         if key:
             del self.dict[key]
         self.inversedict[edit] = None
         return
     filename = self.canonize(filename)
     newkey = os.path.normcase(filename)
     if newkey == key:
         return
     if self.dict.has_key(newkey):
         conflict = self.dict[newkey]
         self.inversedict[conflict] = None
         tkMessageBox.showerror(
             "Name Conflict",
             "You now have multiple edit windows open for %r" % (filename,),
             master=self.root)
     self.dict[newkey] = edit
     self.inversedict[edit] = newkey
     if key:
         try:
             del self.dict[key]
         except KeyError:
             pass
Example #4
0
	def analysis(self):
		
		try:
			inputFile1 = self.filelocation1.get()
			window1 =  self.w1_type.get()
			M1 = int(self.M1.get())
			N1 = int(self.N1.get())
			t1 = int(self.t1.get())
			minSineDur1 = float(self.minSineDur1.get())
			minf01 = int(self.minf01.get())
			maxf01 = int(self.maxf01.get())
			f0et1 = int(self.f0et1.get())
			harmDevSlope1 = float(self.harmDevSlope1.get())
			
			nH = int(self.nH.get())
			stocf = float(self.stocf.get())
			
			inputFile2 = self.filelocation2.get()
			window2 =  self.w2_type.get()
			M2 = int(self.M2.get())
			N2 = int(self.N2.get())
			t2 = int(self.t2.get())
			minSineDur2 = float(self.minSineDur2.get())
			minf02 = int(self.minf02.get())
			maxf02 = int(self.maxf02.get())
			f0et2 = int(self.f0et2.get())
			harmDevSlope2 = float(self.harmDevSlope2.get())

			self.inputFile1, self.fs1, self.hfreq1, self.hmag1, self.stocEnv1, \
				self.inputFile2, self.hfreq2, self.hmag2, self.stocEnv2 = hM.analysis(inputFile1, window1, M1, N1, t1, \
				minSineDur1, nH, minf01, maxf01, f0et1, harmDevSlope1, stocf, inputFile2, window2, M2, N2, t2, minSineDur2, minf02, maxf02, f0et2, harmDevSlope2)

		except ValueError as errorMessage:
			tkMessageBox.showerror("Input values error", errorMessage)
Example #5
0
 def _load():
     filename = askopenfilename(initialdir='accpy/exampledata/')
     if filename[-5::] != '.hdf5':
         filestr.set('error: {} is not hdf5 file-type'.format(filename))
         showerror('ERROR', 'THIS IS NOT A HDF5 FILE')
     else:
         filestr.set(filename)
 def applyUI(self):
     for field in self.stringVars.keys():
         updateValueFromStringVar(self,field)
     if self.name == None or len(self.name.strip()) == 0:
         messageBox.showerror("Name missing","Please enter a name into the name field.")
         return
     saveToFileUI(self)
Example #7
0
	def Conv(self):										# 转换图片
		n = 0
		if self.mstatus.get():
			path = self.entryDir.get()
			if path == '':
				tkMessageBox.showerror('Python Tkinter','请输入路径')
				return
			filenames = os.listdir(path)
			if self.fstatus.get():
				f = self.Image.get()
				for filename in filenames:
					if filename[-3:] in ('bmp','jpg','gif','png'):
			       			self.make(path + '/' + filename, f)
						n = n + 1
			else:
				for filename in filenames:
					if filename[-3:] in ('bmp','jpg','gif','png'):
			       			self.make(path + '/' + filename)
						n = n + 1
		else:
			file = self.entryFile.get()
			if file == '':
				tkMessageBox.showerror('Python Tkinter','请选择文件')
				return
			if self.fstatus.get():
				f = self.Image.get()
				self.make(file, f)
				n = n + 1
			else:
				self.make(file)
				n = n + 1
		self.status.set('成功转换%d图片' % n)
Example #8
0
def tkpanic(msg, exc=None, rc=1):
    text = u"ERROR: %s"%msg
    if exc:
        text += u"\nDetails: "
        text += (unicode(exc) or exc.__class__.__name__)
    tkMessageBox.showerror("Failure", text)
    sys.exit(rc)
Example #9
0
def SaveGeneratedBarcode():
 GenerateBarcode();
 upc_validate = entry1.get();
 if(listboxtxt1.get()=="UPC-A" or listboxtxt1.get()=="UPC-E" or listboxtxt1.get()=="EAN-13" or listboxtxt1.get()=="EAN-8"):
  if(re.findall("([0-9]+)([ |\|]{1})([0-9]{2})$", entry1.get())):
   upc_pieces = re.findall("([0-9]+)([ |\|]{1})([0-9]{2})$", entry1.get());
   upc_pieces = upc_pieces[0];
   upc_validate = upc_pieces[0];
  if(re.findall("([0-9]+)([ |\|]){1}([0-9]{5})$", entry1.get())):
   upc_pieces = re.findall("([0-9]+)([ |\|]){1}([0-9]{5})$", entry1.get());
   upc_pieces = upc_pieces[0];
   upc_validate = upc_pieces[0];
 savestate = False;
 savefname = "";
 tmpbarcode = upcean.oopfuncs.barcode(barcode_list[listboxtxt1.get()], entry1.get());
 tmpbarcode.size = magnify.get();
 tmpbarcode.barheight = (int(entry2.get()),int(entry3.get()));
 tmpbarcode.barcolor = barcode_bar_color;
 tmpbarcode.textcolor = barcode_text_color;
 tmpbarcode.bgcolor = barcode_bg_color;
 savefname = ShowSaveDialog();
 tmpbarcode.filename = savefname;
 if(savefname!=""):
  savestate = tmpbarcode.validate_create_barcode();
 if(not savestate and savefname!=""):
  tkMessageBox.showerror("PyUPC-EAN - Error", "Failed to save barcode.");
Example #10
0
	def saveMayaPreference(self):
		#Linux
		if os.name == 'posix':
			refFile = 'maya_Linux.env'
		#Windows
		else:
			refFile = 'maya_Nt.env'
		try:
			f = open( ( self.UserBatchToolDir + 'etc/' + refFile ),'w' )
		except IOError:
			tkMessageBox.showerror('save error...',('Could not save to '+f) )
		else:
			fContent = ''
			for x in self.envMaya.keys():
				#print self.preferenceEntry[i]
				if self.preferenceMayaEntry[x].get():
					self.envMaya[x] = self.preferenceMayaEntry[x].get().splitlines()[0]
					#print (x+':').rjust(30), self.preferenceEntry[i].get(),'\n'
					fContent +=  x + '=' + self.preferenceMayaEntry[x].get().splitlines()[0] + '\n'
					#print fContent
				else:
					fContent +=  x + '=' + '' + '\n'
			f.write(fContent)
			f.close()
			#close save preference window
			self.preferenceMayaRoot.destroy()
Example #11
0
 def login(self, event=None):
     "Check the user's input and allow access if it is correct"""
     usernameGiven = self.userEntry.get()
     passwordGiven = self.passEntry.get()
     userDetails = self.db.sql("""SELECT * FROM
                               users WHERE username='******'"""
                               %(usernameGiven.lower().strip()))
     #Check that the username exists
     if len(userDetails)==1:
         passHash = userDetails[0][2]
         #Check that the password is correct
         if (hashlib.sha1(passwordGiven).hexdigest() == passHash):
             #Details are correct, unlock application
             self.parent.login(User(userDetails[0]))
             loginFailed = False
         else:
             loginFailed = True
     else:
         loginFailed = True
     if loginFailed:
         #If details are incorrect show an error message
         tkMessageBox.showerror("Login Failed",
                                "Invalid username or password")
         self.userEntry.delete(0, END)
         self.passEntry.delete(0, END)
Example #12
0
def add_music(dic, item_name, item_url,entery, defult):
    if item_name not in dic.keys():
        dic[item_name] = item_url
        entery.delete(0, END)
        entery.insert(0, defult)
    else:
        tkMessageBox.showerror("error", item_name+" is already in the list ")
    def make_authorization(self):
        cashier_id, warehouse_id = workplace_authorization.get_workpace_data()
        #print cashier_id, warehouse_id
        success = True

        error_message = ""

        if None == cashier_id or None == warehouse_id or \
            "" == cashier_id or "" == warehouse_id:
            error_message = "Все указанные поля должны быть заполнены"
            success = False

        if success:
            try:
                res = cashier_workplace.authorization(cashier_id, warehouse_id)
            except Exception:
                res = False
                error_message = "Неверно заполнены поля авторизации"
            success = success and res
            if not res:
                error_message = "Вы не обладаете полномочиями для авторизации. " \
                                "Проверьте вводимые значение. А возможно, вы уже уволены"

        if success:

            self.auth_cashier_btn['command']     = self.make_logout
            self.auth_cashier_btn['text']        = "Деавторизация"
            self.compute_bonus_btn['state']      = 'normal'
            self.dismiss_cashier_btn['state']    = 'normal'
            self.get_goods_table_btn['state']    = 'normal'
            self.update_goods_info_btn['state']  = 'normal'
            self.change_cash_status_btn['state'] = 'normal'
        else:
            tkMessageBox.showerror("Ошибка авторизации", error_message)
        self.mainloop()
Example #14
0
    def runMission( self, mission_spec, mission_record_spec, action_space ):
        '''Sets a mission running.
        
        Parameters:
        mission_spec : MissionSpec instance, specifying the mission.
        mission_record_spec : MissionRecordSpec instance, specifying what should be recorded.
        action_space : string, either 'continuous' or 'discrete' that says which commands to generate.
        '''
        sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)  # flush print output immediately
        self.world_state = None
        self.action_space = action_space
        total_reward = 0

        if mission_spec.isVideoRequested(0):
            self.canvas.config( width=mission_spec.getVideoWidth(0), height=mission_spec.getVideoHeight(0) )

        try:
            self.agent_host.startMission( mission_spec, mission_record_spec )
        except RuntimeError as e:
            tkMessageBox.showerror("Error","Error starting mission: "+str(e))
            return

        print "Waiting for the mission to start",
        self.world_state = self.agent_host.peekWorldState()
        while not self.world_state.is_mission_running:
            sys.stdout.write(".")
            time.sleep(0.1)
            self.world_state = self.agent_host.peekWorldState()
            for error in self.world_state.errors:
                print "Error:",error.text
        print
        if mission_spec.isVideoRequested(0) and action_space == 'continuous':
            self.canvas.config(cursor='none') # hide the mouse cursor while over the canvas
            self.canvas.event_generate('<Motion>', warp=True, x=self.canvas.winfo_width()/2, y=self.canvas.winfo_height()/2) # put cursor at center
            self.root.after(50, self.update)
        self.canvas.focus_set()

        while self.world_state.is_mission_running:
            self.world_state = self.agent_host.getWorldState()
            if self.world_state.number_of_observations_since_last_state > 0:
                self.observation.config(text = self.world_state.observations[0].text )
            if mission_spec.isVideoRequested(0) and self.world_state.number_of_video_frames_since_last_state > 0:
                frame = self.world_state.video_frames[-1]
                image = Image.frombytes('RGB', (frame.width,frame.height), str(frame.pixels) )
                photo = ImageTk.PhotoImage(image)
                self.canvas.delete("all")
                self.canvas.create_image(frame.width/2, frame.height/2, image=photo)
                self.canvas.create_line( frame.width/2 - 5, frame.height/2, frame.width/2 + 6, frame.height/2, fill='white' )
                self.canvas.create_line( frame.width/2, frame.height/2 - 5, frame.width/2, frame.height/2 + 6, fill='white' )
                self.root.update()
            for reward in self.world_state.rewards:
                total_reward += reward.getValue()
            self.reward.config(text = str(total_reward) )
            time.sleep(0.01)
        if mission_spec.isVideoRequested(0) and action_space == 'continuous':
            self.canvas.config(cursor='arrow') # restore the mouse cursor
        print 'Mission stopped'
        if not self.agent_host.receivedArgument("test"):
            tkMessageBox.showinfo("Ended","Mission has ended. Total reward: " + str(total_reward) )
        self.root.destroy()
Example #15
0
def openXML(mainApp, filename=''):
	if askSaveChanges(mainApp):
		label_filename = mainApp.frames.menu.dic['label_filename']
		if filename=='':
			filename = getFilename()
		
		if filename <> '':
			mainApp.frames.treeview.clean()
			mainApp.frames.buttons.clean()
			GL.filename = filename
			label_filename.config(text= GL.filename)
			
			root = xml_man.getXML(GL.filename)
			#root = xml_man.getXML('stylers.xml')
			
			if root == None:
				tkMessageBox.showerror('eXMLorer', 'El archivo %s no es un archivo XML valido' % GL.filename)
				label_filename.config(text= '')
			else:	
				GL.dicTagsInTree = {}
				GL.appTreeView = tk_treeview.getTreeView(mainApp.frames.treeview, mainApp.frames.buttons, GL.dicTagsInTree)
				
				GL.dicTagsInTree[root.tag] = TIG.TagInTree('', root.tag, root, None, GL.appTreeView)
				mainApp.rootTIG = GL.dicTagsInTree[root.tag]
				addXMLToTree(root, root.tag, GL.dicTagsInTree, GL.appTreeView)
Example #16
0
 def __excel2Plist__(self):
     
     if self.inputentry.get() == "" or self.outEntry.get() =="":
         tkMessageBox.showerror('Result',"input res or output res is requested!")
         return
     info =  self.scanExcel.sacnExcelDir(self.inputentry.get(),self.outEntry.get())
     tkMessageBox.showinfo('Result',info)        
Example #17
0
 def __plist2Excel__(self):
     
     if self.outEntry.get() == "" or self.plistEntry.get() == "":
         tkMessageBox.showerror('Result',"input res or plist res is requested!")
         return
     info = self.scanPlist.scanPlistDir(self.outEntry.get(),self.plistEntry.get())
     tkMessageBox.showinfo('Result',info)      
Example #18
0
def main():
	if sys.version_info[0] != 2 or sys.version_info[1] != 7:
			root.wm_withdraw()
			tkMessageBox.showerror('Version Error', 'Please run the program with Python 2.7')		
	else:
		app = Window(root)
		root.mainloop()
Example #19
0
 def getData(self):
     if self.inputFile.get() == self.outputFile.get() == "":
         tkMessageBox.showerror(
             "Error", "Please choose input and output files")
     else:
         responses = threading.Thread(target=self.wrap)
         responses.start()
Example #20
0
def setangle(root, amber_prmtop, messages):
   """ Sets (adds or changes) an angle in the topology file """
   # We need 3 masks, a force constant, and an equilibrium angle
   widget_list = [('MaskEntry', 'First atom in angle'),
                  ('MaskEntry', 'Second (middle) atom in angle'),
                  ('MaskEntry', 'Third atom in angle'),
                  ('Entry', 'Force constant (kcal/mol rad**2)'),
                  ('Entry', 'Equilibrium Angle (Degrees)')]
   # We need 5 variables
   var_list = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]
   description = ('Sets an angle in the topology file with the given Force ' +
                  'constant in kcal/mol/rad**2\nand the given equilibrium ' +
                  'angle in Degrees. All three masks must specify only a\n' +
                  'single atom. If the angle exists, it will be replaced. If ' +
                  'it doesn\'t, it will be added.')
   # Create the window, open it, then wait for it to close
   cmd_window = _guiwidgets.ActionWindow('setAngle', amber_prmtop, 
                     widget_list, var_list, description)
   cmd_window.wait_window()
   # See if we got any variables back
   vars_found = True in [bool(v.get()) for v in var_list]
   if not vars_found: return
   # If we did, pass them through
   var_list = [v.get() for v in var_list]
   try:
      action = ParmedActions.setangle(amber_prmtop, ArgumentList(var_list))
      messages.write('%s\n' % action)
      action.execute()
   except Exception, err:
      showerror('Unexpected Error!', '%s: %s' % (type(err).__name__, err))
      return
Example #21
0
def deletedihedral(root, amber_prmtop, messages):
   """ Deletes a dihedral between 4 given atoms """
   # We need 4 masks
   widget_list = [('MaskEntry', 'First (end) atom in dihedral'),
                  ('MaskEntry', 'Second (middle) atom in dihedral'),
                  ('MaskEntry', 'Third (middle) atom in dihedral'),
                  ('MaskEntry', 'Fourth (end) atom in dihedral')]
   # We need 4 variables
   var_list = [StringVar() for i in range(4)]
   description = ('Deletes dihedrals between the atoms specified in mask1, ' +
                  'mask2, mask3, and mask4.\nIt will try to match dihedrals ' +
                  'only in the order given or reverse order. Dihedrals are\n' +
                  'specified by atom N in mask1, mask2, mask3, and mask4,' +
                  'where N is the selected\natom in that mask.')
   # Create the window, open it, then wait for it to close
   cmd_window = _guiwidgets.ActionWindow('deleteDihedral', amber_prmtop, 
                     widget_list, var_list, description)
   cmd_window.wait_window()
   # See if we got any variables back
   vars_found = True in [bool(v.get()) for v in var_list]
   if not vars_found: return
   # If we did, pass them through
   var_list = [v.get() for v in var_list]
   try:
      action = ParmedActions.deletedihedral(amber_prmtop,ArgumentList(var_list))
      messages.write('%s\n' % action)
      action.execute()
   except Exception, err:
      showerror('Unexpected Error!', '%s: %s' % (type(err).__name__, err))
      return
Example #22
0
def changeljsingletype(root, amber_prmtop, messages):
   """ Changes radius/well depth of a single LJ type given by the mask """
   # We need a mask, radius, and well depth
   widget_list = [('MaskEntry', 'Mask to change LJ Type'),
                  ('Entry', 'New LJ Radius'), ('Entry', 'New LJ Depth')]
   var_list = [StringVar(), StringVar(), StringVar()]
   description = "Change a given atom type's LJ radius and well depth"
   # Create the window, open it, then wait for it to close
   cmd_window = _guiwidgets.ActionWindow('changeLJSingleType', amber_prmtop,
                     widget_list, var_list, description)
   cmd_window.wait_window()
   # See if we got any variables back
   vars_found = True in [bool(v.get()) for v in var_list]
   if not vars_found: return
   # addljtype expects any _non_specified variables to be None
   var_list = [v.get() for v in var_list]
   for i, v in enumerate(var_list):
      if not v: var_list[i] = None
   # If we did, store them and pass it to the class
   try:
      action = ParmedActions.changeljsingletype(amber_prmtop,
                                                ArgumentList(var_list))
   except Exception, err:
      showerror('Unexpected Error!', '%s: %s' % (type(err).__name__, err))
      return
Example #23
0
def strip(root, amber_prmtop, messages):
   """ Strips a mask from the topology file """
   if amber_prmtop.parm.chamber:
      showerror('Not Implemented', 'The strip command does not yet work with ' +
                'chamber topologies')
      return
   # We need a mask, new radius, new epsilon, and for chamber topologies,
   # a new radius-1-4 and epsilon-1-4. Don't add the latter ones until we
   # know if we have a chamber prmtop or not.
   widget_list = [('MaskEntry', 'Atoms to strip from topology')]
   # We need 5 string variables, then get the description. 
   var_list = [StringVar()]
   description=('Strips the selected atoms from the topology file. All\n' +
                'remaining atoms and parameters remain unchanged. Any\n' +
                'parameters associated with stripped atoms are removed.')
   # Create the window, open it, then wait for it to close
   cmd_window = _guiwidgets.ActionWindow('addLJType', amber_prmtop,
                     widget_list, var_list, description)
   cmd_window.wait_window()
   # See if we got any variables back
   var = var_list[0]
   if not var.get(): return
   try:
      action = ParmedActions.strip(amber_prmtop, ArgumentList(var.get()))
   except Exception, err:
      showerror('Unexpected Error!', '%s: %s' % (type(err).__name__, err))
      return
Example #24
0
def change(root, amber_prmtop, messages):
   """ Allows us to change a specific atomic property """
   # The spinbox is sent with the Spinbox, label, and then a list of all of the
   # values to give to it
   widget_list = [('Spinbox', 'Property to change', 'CHARGE', 'MASS',
                   'RADII', 'SCREEN', 'ATOM_NAME', 'AMBER_ATOM_TYPE',
                   'ATOM_TYPE_INDEX', 'ATOMIC_NUMBER'),
                  ('MaskEntry', 'Atoms to change'),
                  ('Entry', 'New Value for Property')]
   # We need 3 string variables, then get the description
   var_list = [StringVar(), StringVar(), StringVar()]
   description = 'Changes the property of given atoms to a new value'
   # Create the window, open it, then wait for it to close
   cmd_window = _guiwidgets.ActionWindow('change', amber_prmtop,
                     widget_list, var_list, description)
   cmd_window.wait_window()
   # See if we got any variables back
   vars_found = True in [bool(v.get()) for v in var_list]
   if not vars_found: return
   # If we did, store them and pass it to the class
   var_list = [v.get() for v in var_list]
   try:
      action = ParmedActions.change(amber_prmtop, ArgumentList(var_list))
   except Exception, err:
      showerror('Unexpected Error!', '%s: %s' % (type(err).__name__, err))
      return
Example #25
0
def printinfo(root, amber_prmtop, messages):
   """ Prints all of the info in a given FLAG """
   # Set up the window
   # variables we need for printInfo
   widget_list = [('Entry', '%FLAG you want info from')]
   # Variable list -- we need a single string
   var_list = [StringVar()]
   # description
   description = ' '.join(ParmedActions.printinfo.__doc__.split())
   cmd_window = _guiwidgets.ActionWindow('printInfo', amber_prmtop,
                             widget_list, var_list, description)
   cmd_window.wait_window()
   # Make sure we didn't cancel (or just press OK with no input), or just leave
   var = var_list[0].get()
   if not var: return
   # Now that we did something, do it
   action = ParmedActions.printinfo(amber_prmtop, ArgumentList(var))
   if not action.found:
      showerror('Not Found!', '%%FLAG %s not found!' % var.upper())
      return

   window = Toplevel(root)
   window.resizable(True, True)
   window.title('%%FLAG %s Info in %s' % (var.upper(), amber_prmtop))
   text = _guiwidgets.ExitingScrollText(window, None, spacing3=5, padx=5,
                                        pady=5, width=82, height=20)
   text.write(action)
   text.pack(fill=BOTH, expand=1)
   window.wait_window()

   messages.write('Wrote info for flag %s\n' % var.upper())
Example #26
0
	def plot_graph(self):
		self.pattern=re.compile(".*\.(xlsx|ods)")
		self.match = self.pattern.match(self.filename)
		if not self.match or self.filename is None:
        		tkMessageBox.showerror(title="Wrong Input",message="Invalid File Type")
			exit()

		self.wb=xlrd.open_workbook(self.filename)
		s=self.wb.sheet_by_index(0)
		top = Toplevel()
		self.varx=IntVar()
		self.vary=IntVar()
		top.title("Configuration")

		w=Label(top,text=str(s.ncols)+" columns found")
		w.pack()
		x=Label(top,text="Assign column to the x-axis")
		x.pack()
		for i in range(s.ncols):
			c=Radiobutton(top, text="Column "+str(i+1),variable=self.varx, value=i)
        		c.pack(anchor=W)
        	y=Label(top,text="Assign column to the y-axis")
        	y.pack()
        	for i in range(s.ncols):
        		d=Radiobutton(top,text="Column "+str(i+1),variable=self.vary,value=i)
        		d.pack(anchor=W)
		self.plott=Button(top,text="Plot Graph",command=self.sweg).pack()	
Example #27
0
def changelj14pair(root, amber_prmtop, messages):
   """ Changes specific 1-4 Lennard Jones pairs """
   # Only good for chamber topologies
   if not amber_prmtop.parm.chamber:
      showerror('Incompatible',
                'changeLJ14Pair is only valid for chamber topologies!')
      return
   # variables we need for changelj14pair
   widget_list = [('MaskEntry', 'Atom(s) Type 1 Mask'),
                  ('MaskEntry', 'Atom(s) Type 2 Mask'),
                  ('Entry', 'Combined Radius'),
                  ('Entry', 'Combined Well Depth')]
   # Variable list -- we need 2 masks and 2 floats
   var_list = [StringVar(), StringVar(), StringVar(), StringVar()]
   # description
   description = ' '.join(ParmedActions.changeljpair.__doc__.split())
   cmd_window = _guiwidgets.ActionWindow('changeLJ14Pair', amber_prmtop,
                             widget_list, var_list, description)
   cmd_window.wait_window()
   # Make sure we didn't cancel (or just press OK with no input), or just leave
   vars_exist = True in [bool(v.get()) for v in var_list]
   if not vars_exist: return
   # Now that we did something, do it
   var_list = [v.get() for v in var_list]
   try:
      action=ParmedActions.changelj14pair(amber_prmtop, ArgumentList(var_list))
      messages.write('%s\n' % action)
      action.execute()
   except Exception, err:
      showerror('Unexpected Error!', '%s: %s' % (type(err).__name__, err))
Example #28
0
def addexclusions(root, amber_prmtop, messages):
   """ Adds atoms to other atoms' exclusion list """
   # We need 2 masks
   widget_list = [('MaskEntry', 'Atoms to add excluded atoms to'),
                  ('MaskEntry', 'Atoms to exclude from other mask')]
   # We have 2 mask variables
   var_list = [StringVar(), StringVar()]
   # Description
   description=('Allows you to add arbitrary excluded atoms to exclusion\n' +
       'lists. This omits all non-bonded interactions in the direct-space\n' +
       'calculation, but does not omit interactions from adjacent cells in\n' +
       'periodic simulations')
   cmd_window = _guiwidgets.ActionWindow('addExclusions', amber_prmtop,
                     widget_list, var_list, description)
   cmd_window.wait_window()
   
   # Bail out if we didn't get any variables
   if not True in [bool(v.get()) for v in var_list]: return
   
   var_list = [v.get() for v in var_list]
   try:
      action = ParmedActions.addexclusions(amber_prmtop, ArgumentList(var_list))
   except Exception, err:
      showerror('Unexpected Error!', '%s: %s' % (type(err).__name__, err))
      return
Example #29
0
 def add_customer(self, event=None):
     # validate and show errors
     if self.fname.get() == '':
         showerror("Error!", "First name field blank!")
     elif self.lname.get() == '':
         showerror("Error!", "Last name field blank!")
     elif self.mname.get() == '':
         showerror("Error!", "Middle initial field blank!")
     elif self.payment.get() not in ("Drop In", "Punch Card", "Monthly", "Inactive"):
         showerror("Error!", "Incorect Customer type!")
     elif not re.compile(r'[01]?\d/[0123]?\d/[12]\d{1,3}').search(self.date.get()):
         showerror("Error!", "Bad entry for date, use format mm/dd/yyyy")
     else:
         # do work
         name = ' '.join([self.fname.get(),self.mname.get(),self.lname.get()])
         old, row = self.customers.find(str(self.lname.get()).strip(), str(self.fname.get()).strip(),
                                        str(self.mname.get()).strip())
         new = [str(self.lname.get()).strip(), str(self.fname.get()).strip(), str(self.mname.get()).strip(),
                str(self.payment.get()).strip(), datetime.strptime(self.date.get(), "%m/%d/%Y")]
         
         if not old: #add customer
             self.customers.add(new)
             self.output_text("+ - New Customer: " + name + " (" + self.payment.get() + ")\n")
             self.refresh()
         else:
             var = IntVar()
             
             diag = AlreadyExistsDialog(self.root, new, old, var)
             diag.show()
             if var.get() == 0: # edit
                 pass
             if var.get() == 1: # replace customer
                 self.customers.replace(row, new)
                 self.output_text("+ - Modified: " + name + " (" + self.payment.get() + ")\n")
                 self.refresh()
Example #30
0
def changeljpair(root, amber_prmtop, messages):
   """ Changes a pair-wise LJ interaction for pre-combined epsilon/Rmin """
   # The variables we need for changeljpair
   widget_list = [('MaskEntry', 'Atom(s) Type 1 Mask'),
                  ('MaskEntry', 'Atom(s) Type 2 Mask'),
                  ('Entry', 'Combined Radius'),
                  ('Entry', 'Combined Well Depth')]
   # Variable list -- we need 2 masks and 2 floats
   var_list = [StringVar(), StringVar(), StringVar(), StringVar()]
   # description
   description = ' '.join(ParmedActions.changeljpair.__doc__.split())
   cmd_window = _guiwidgets.ActionWindow('changeLJPair', amber_prmtop,
                             widget_list, var_list, description)
   cmd_window.wait_window()
   # Make sure we didn't cancel (or just press OK with no input), or just leave
   vars_exist = True in [bool(v.get()) for v in var_list]
   if not vars_exist: return
   # Now that we did something, do it
   var_list = [v.get() for v in var_list]
   try:
      action = ParmedActions.changeljpair(amber_prmtop, ArgumentList(var_list))
      messages.write('%s\n' % action)
      action.execute()
   except Exception, err:
      showerror('Unexpected Error!', '%s: %s' % (type(err).__name__, err))
def calcCommand(listacompra, unico, pendientes, log):
    '''Callback for the "cross files" button that validates files and process them'''

    listacompra = listacompra.file.get()
    pendientes = pendientes.file.get()
    unico = unico.file.get()

    # Some file validation
    if not listacompra:
        tkMessageBox.showerror(u"No se encontró fichero",
                               u"Seleccione lista de compra!")

    elif not unico:
        tkMessageBox.showerror(u"No se encontró fichero",
                               u"Seleccione el fichero único!")

    elif not pendientes:
        tkMessageBox.showerror(
            u"No se encontró fichero",
            u"Seleccione un fichero de pedidos pendientes!")

    elif 0 != common.readvalidate(listacompra):
        tkMessageBox.showerror(
            u"Problema de lectura",
            u"No se puede leer la lista de compra! Pruebe con otro archivo.")

    elif 0 != common.readvalidate(unico):
        tkMessageBox.showerror(
            u"Problema de lectura",
            u"No se puede leer el fichero único! Pruebe con otro archivo.")

    elif 0 != common.readvalidate(pendientes):
        tkMessageBox.showerror(
            u"Problema de lectura",
            u"No se puede leer el archivo de pedidos pendientes! Pruebe con otro archivo."
        )

    # if all files are valid, procede
    else:
        # read destination of output
        tkMessageBox.showinfo(
            u'Fichero de cruces',
            u'Escoja la ubicación donde escribir el fichero de cruces.')

        outputext = "xlsx"
        output = None
        output = tkFileDialog.asksaveasfilename(
            title="Seleccione la ubicación donde guardar el archivo final (.%s)"
            % outputext,
            filetypes=[('Microsoft Excel 2007', '.%s' % outputext)],
            defaultextension=outputext)

        if not output:
            tkMessageBox.showerror(
                "Error",
                u"Tiene que especificar un archivo!, vuelva a intentarlo escogiendo uno."
            )
        elif not common.wincheckwriteperm(output):
            tkMessageBox.showerror(
                "Error",
                u"El archivo está bloqueado por otro programa! Vuelva a intentarlo cuando no esté bloqueado."
            )
        else:
            try:
                programa_pedidos.processfiles(unico,
                                              pendientes,
                                              listacompra,
                                              output,
                                              log=lambda *args: log(*args))
            except Exception as e:
                if os.isatty(sys.stdin.fileno()):
                    traceback.print_exc()  # print traceback on console
                err = str(e).decode('utf-8')
                log("ERROR", err)

                functionmap = {
                    'writecrossxls': u"Error al escribir el archivo de cruce",
                    'xls2sqlite':
                    lambda e: u'Error al leer el archivo %s' % e.file
                }

                tb = sys.exc_info()[2]
                errmsg = u'Se produjo un error al procesar los archivos'
                for t in traceback.extract_tb(tb):
                    if t[2] in functionmap:
                        r = functionmap[t[2]]
                        if hasattr(r, "__call__"):
                            errmsg = r(e)
                        else:
                            errmsg = r

                tkMessageBox.showerror(
                    u"Fallo al procesar",
                    errmsg + u'\n\nMensaje de error: %s' % err)
                return

            msg_exito = u'Proceso de cruce finalizado con éxito!'
            tkMessageBox.showinfo('Proceso finalizado', msg_exito)
            log("INFO", msg_exito)
Example #32
0
 def summit(self):
     if self.id_input.get() == '':
         tkMessageBox.showerror('错误', '用户名不能为空!')
         return
     if self.passwd_input1.get() != self.passwd_input.get():
         tkMessageBox.showerror('错误', '两次输入的密码不一致!')
         return
     if self.passwd_input.get() == '':
         tkMessageBox.showerror('错误', '密码不能为空!')
         return
     if not self.nameValue(self.id_input.get()):
         tkMessageBox.showerror('错误', '用户名必须为字母数字以及下划线,且不能为system')
         return
     if not self.pwValue(self.passwd_input.get()):
         tkMessageBox.showerror('错误', '密码必须大于6位且为字母数字以及下划线')
         return
     try:
         self.client.conn_sock.connection()
         self.client.conn_sock.send_mess(
             '01',
             self.id_input.get() + '|' + self.passwd_input.get())
     except IOError:
         tkMessageBox.showerror('错误', '无法连接服务器')
         self.quit()
         return
     while self.client.stop_flag == None:
         time.sleep(0.1)
         print 'waiting...'
     if self.client.stop_flag == '12':
         tkMessageBox.showinfo('消息', '注册失败: ' + '用户名已存在')
     elif self.client.stop_flag == '11':
         tkMessageBox.showinfo('消息',
                               '注册成功\n' + '用户名:' + self.id_input.get())
     self.client.stop_flag = None
def gammaPreview():
    global gammaImg
    gammaWindow = Toplevel()
    ws = gammaWindow.winfo_screenwidth()
    hs = gammaWindow.winfo_screenheight()
    x = (ws / 2)
    y = (hs / 2)
    gammaWindow.geometry('%dx%d+%d+%d' % (600, 450, x, y))

    imgG = Image.open('start.gif')
    imgG = imgG.resize((480 / 2, 594 / 2), Image.ANTIALIAS)
    imgGc = ImageTk.PhotoImage(imgG)
    canvasframe2 = Frame(gammaWindow, width=600, height=400)
    canvasframe2.grid(row=0, column=2, sticky=W + E + N + S)
    canvas2 = Canvas(canvasframe2, width=510, height=383)
    img_canvas2 = canvas2.create_image(510 / 2,
                                       400 / 2,
                                       image=imgGc,
                                       anchor=CENTER)
    canvas2.grid(row=0, column=0)

    gframe2 = Frame(gammaWindow, width=600, height=50)
    gframe2.grid(row=1, column=2, sticky=W + E + N + S)
    gammalabel = Label(gframe2, text="Gamma Correction")
    gammalabel.grid(row=1, column=0)
    setGamma = Scale(gframe2,
                     from_=0,
                     to=3,
                     resolution=0.5,
                     orient=HORIZONTAL,
                     command=gamma_value)
    setGamma.grid(row=1, column=1)

    var8g = StringVar(gammaWindow)
    var8g.set("TIFF")  # initial value
    optionExp = OptionMenu(gframe2, var8g, 'TIFF', 'JPEG', 'PNG', 'BMP',
                           'DATA')
    optionExp.grid(row=1, column=3)
    var8label = Label(gframe2, text="File Options")
    var8label.grid(row=1, column=2)

    exportbtn_text = StringVar(gammaWindow)
    exportbtn = Button(gframe2,
                       textvariable=exportbtn_text,
                       command=export_image_corrected)
    exportbtn_text.set("Export Image")
    exportbtn.grid(row=1, column=4)

    try:
        gammaImg = gamma_correction(imgaux, 2.4)
        res = cv2.resize(gammaImg, (510, 384))
        gammaImg2 = cv2.cvtColor(res, cv2.COLOR_BGR2RGB)
        img2FromArrayG = Image.fromarray(gammaImg2)
        imgtk2 = ImageTk.PhotoImage(image=img2FromArrayG)
        canvas2.itemconfig(img_canvas2, imag=imgtk2)
        canvas2.imgtk2 = imgtk2

    except:
        messagebox.showerror(
            "Error", "Image has not been taken, please take an image.")
        gammaWindow.destroy()

    gammaWindow.mainloop()
Example #34
0
 def encode(self, chars):
     if isinstance(chars, str):
         # This is either plain ASCII, or Tk was returning mixed-encoding
         # text to us. Don't try to guess further.
         return chars
     # See whether there is anything non-ASCII in it.
     # If not, no need to figure out the encoding.
     try:
         return chars.encode('ascii')
     except UnicodeError:
         pass
     # If there is an encoding declared, try this first.
     try:
         enc = coding_spec(chars)
         failed = None
     except LookupError as msg:
         failed = msg
         enc = None
     if enc:
         try:
             return chars.encode(enc)
         except UnicodeError:
             failed = "Invalid encoding '%s'" % enc
     if failed:
         tkMessageBox.showerror("I/O Error",
                                "%s. Saving as UTF-8" % failed,
                                parent=self.text)
     # If there was a UTF-8 signature, use that. This should not fail
     if self.fileencoding == BOM_UTF8 or failed:
         return BOM_UTF8 + chars.encode("utf-8")
     # Try the original file encoding next, if any
     if self.fileencoding:
         try:
             return chars.encode(self.fileencoding)
         except UnicodeError:
             tkMessageBox.showerror(
                 "I/O Error",
                 "Cannot save this as '%s' anymore. Saving as UTF-8" \
                 % self.fileencoding,
                 parent = self.text)
             return BOM_UTF8 + chars.encode("utf-8")
     # Nothing was declared, and we had not determined an encoding
     # on loading. Recommend an encoding line.
     config_encoding = idleConf.GetOption("main", "EditorWindow",
                                          "encoding")
     if config_encoding == 'utf-8':
         # User has requested that we save files as UTF-8
         return BOM_UTF8 + chars.encode("utf-8")
     ask_user = True
     try:
         chars = chars.encode(encoding)
         enc = encoding
         if config_encoding == 'locale':
             ask_user = False
     except UnicodeError:
         chars = BOM_UTF8 + chars.encode("utf-8")
         enc = "utf-8"
     if not ask_user:
         return chars
     dialog = EncodingMessage(self.editwin.top, enc)
     dialog.go()
     if dialog.num == 1:
         # User asked us to edit the file
         encline = "# -*- coding: %s -*-\n" % enc
         firstline = self.text.get("1.0", "2.0")
         if firstline.startswith("#!"):
             # Insert encoding after #! line
             self.text.insert("2.0", encline)
         else:
             self.text.insert("1.0", encline)
         return self.encode(self.text.get("1.0", "end-1c"))
     return chars
Example #35
0
  def __init__(self,parent,filename):
    self.parent=parent
    self.modelName=""
    self.modelType=""
    self.modelList=[]
    self.click_result=""	
    
  # Collect model information from the circuit file
    try:
      self.FreeEDA_HOME=FreeEDA_HOME
    except NameError:
      try:
        self.FreeEDA_HOME=os.environ["FreeEDA_HOME"]
      except KeyError:
        tkMessageBox.showerror("Error FreeEDA_HOME is not set","Please set FreeEDA_HOME variable in .bashrc\n\nStep to set  FreeEDA_HOME variable:\n  1) Open ~/.bashrc using text editor (vi ~/.bash).\n   2) Add the line \"Export FreeEDA_HOME=<path_of_freeeda>\" to it.\n  3) source ~/.bashrc")
        exit(0)

    HOME=self.FreeEDA_HOME="/modelEditor/"
  # Open the circuit file 
    self.fileName=filename
  # Open parameter file
    if os.path.exists(self.fileName):
      try:
        f = open(self.fileName)
      except :
        tkMessageBox.showwarning("Bad input","Circuit netlist does not exit, please try again")
        return
    else:
        tkMessageBox.showwarning("Bad input","Circuit netlist does not exit, please try again")
        return

  # Read the data from file
    data=f.read()
  
  # Close the file
    f.close()
    netlist=data.splitlines()
  # Find the various model library required
    self.modelInfo={}
    
    for eachline in netlist:
      eachline=eachline.strip()
      if len(eachline)>1:
        eachline=eachline.lower()
        words=eachline.split()
        if eachline[0]=='d':
          modelName=words[3]
	  modelType=words[3]
          self.modelList.append(words[0]+":"+modelName)
	  self.modelInfo[modelName]=modelType
        elif eachline[0]=='q':
          modelName=words[4]
	  if words[4]=='npn':
          	modelType="NPN"
	  elif words[4]=='pnp':
	        modelType="PNP"
	  else:
	       modelType=words[4]	
	       				
          self.modelList.append(words[0]+":"+modelName)
	  self.modelInfo[modelName]=modelType
          
        elif eachline[0]=='m':
            modelName=words[4]
	    if words[4]=='nmos':
		modelType="NMOS"
	    elif words[4]=='pmos':
		modelType="PMOS"
	    else:
		modelType=words[4]
	    self.modelList.append(words[0]+":"+modelName)
	    self.modelInfo[modelName]=modelType
	
        elif eachline[0]=='j':
	    modelName=words[4]
	    if words[4]=='pjf':
		modelType='PJF'
	    elif words[4]=='njf':
		modelType='NJF'
	    else:
		modelType=words[4]	    
            self.modelList.append(words[0]+":"+modelName)
	    self.modelInfo[modelName]=modelType
        else:
	  continue
	  
  # Create the dialog.
      	
    self.dialog = Pmw.SelectionDialog(parent,
          	title = 'Model Selector',
          	buttons = ('OK', 'Cancel'),
          	defaultbutton = 'OK',
          	scrolledlist_labelpos = 'n',
          	label_text = 'Please select the model',
          	scrolledlist_items=self.modelList,
          	command = self.apply,
          	)
    self.dialog.pack(fill = 'both', expand=1, padx=5, pady=5)
    self.dialog.activate()

  # Protocol when window is deleted.
    self.dialog.protocol("WM_DELETE_WINDOW",self.cancel)
Example #36
0
     pass
 # If there is an encoding declared, try this first.
 try:
     enc = coding_spec(chars)
     failed = None
 except LookupError, msg:
     failed = msg
     enc = None
 if enc:
     try:
         return chars.encode(enc)
     except UnicodeError:
         failed = "Invalid encoding '%s'" % enc
 if failed:
     tkMessageBox.showerror(
         "I/O Error",
         "%s. Saving as UTF-8" % failed,
         master = self.text)
 # If there was a UTF-8 signature, use that. This should not fail
 if self.fileencoding == BOM_UTF8 or failed:
     return BOM_UTF8 + chars.encode("utf-8")
 # Try the original file encoding next, if any
 if self.fileencoding:
     try:
         return chars.encode(self.fileencoding)
     except UnicodeError:
         tkMessageBox.showerror(
             "I/O Error",
             "Cannot save this as '%s' anymore. Saving as UTF-8" \
             % self.fileencoding,
             master = self.text)
         return BOM_UTF8 + chars.encode("utf-8")
Example #37
0
    def fill(self, path=None):
        self.fileList.delete(0, END)
        self.fileList.lists[0].resetSearch()

        if path is None: path = self.path

        # Populate list but sorted
        try:
            for fn in os.listdir(path):
                if not self.hidden and fn[0] == ".": continue
                filename = os.path.join(path, fn)
                ext, color = fileTypeColor(filename)

                try:
                    s = os.lstat(filename)
                except:
                    continue

                size = 0
                islnk = S_ISLNK(s[ST_MODE])
                if islnk:
                    try:
                        s = os.stat(filename)
                    except:
                        continue
                isdir = S_ISDIR(s[ST_MODE])

                if self.filter is not None and not isdir and not islnk:
                    match = False
                    for pat in self.filter:
                        if fnmatch.fnmatch(fn, pat):
                            match = True
                            break
                else:
                    match = True

                if isdir:
                    if not self.dirs: continue
                elif islnk:
                    if not self.links: continue
                else:
                    size = s[ST_SIZE]

                if match:
                    self.fileList.insert(
                        END, (fn, ext, size,
                              time.strftime(_TIME_FORMAT,
                                            time.localtime(s[ST_MTIME]))))
                    if not self.files and not isdir:
                        self.fileList.setColor(END, DISABLE_FILE)
                    elif color:
                        self.fileList.setColor(END, color)
        except OSError:
            messagebox.showerror(_("Error"),
                                 _("Error listing folder \"%s\"") % (path),
                                 parent=self)

        if FileDialog.sort is None:
            self.fileList.sort(0, False)  # First short by name
            # Move all directories to top
            self.fileList.sort(1, False)  # then by type
            FileDialog.sort = None
        else:
            self.fileList.restoreSort(FileDialog.sort)

        # Find item to select
        fn = self.filename.get()
        if self.seldir: fn = os.path.basename(fn)
        for i in range(self.fileList.size()):
            if fn == self.fileList.lists[0].get(i):
                self.fileList.see(i)
                self.fileList.activate(i)
                self.fileList.selection_set(i)
                break
        else:
            self.fileList.see(0)
            self.fileList.activate(0)
            self.fileList.selection_set(0)
Example #38
0
 def onError(self):
     box.showerror("Error", "Error : Maximum no of subjects exeed ")
Example #39
0
def getRawFolder(ui):

    try:
        ui.entMergSrc.insert(0, ui.raw_folder)
    except:
        showerror(message='Raw folder must be specified in metadata tab.')
Example #40
0
            from tkinter.messagebox import showerror
        except ImportError:
            raise Exception(
                "This version of Python has no tkMessageBox support!")

    # Don't show the root window
    root = tkinter.Tk()
    root.withdraw()

    if sys.version_info < (
            3,
            0,
    ):
        showerror(
            "Talos evilseed",
            "This program requires Python 3.6 or higher.\n" + "\n" +
            "Stop being a Python 2 pleb.\nGet Python 3.",
        )
    else:
        showerror("Talos evilseed",
                  "This program requires Python 3.6 or higher.")

    raise Exception("Update Python dammit")

#
# And now we return to your usual imports.
#

import talos_evilseed.app

if __name__ == "__main__":
from tkMessageBox import showinfo, showwarning, showerror

WARN = 'warn'
CRIT = 'crit'
REGU = 'regu'

SIGNS = {
    'do not enter': CRIT,
    'railroad crossing': WARN,
    '55\nspeed limit': REGU,
    'wrong way': CRIT,
    'merging traffic': WARN,
    'one way': REGU,
}

critCB = lambda: showerror('Error', 'Error Button pressed!')
warnCB = lambda: showerror('Warning', 'Warning Button Pressed!')
infoCB = lambda: showerror('Info', 'Info Button Pressed!')

top = Tk()
top.title('Road Signs')
Button(top, text='QUIT', command=top.quit, bg='red', fg='white').pack()

MyButton = pto(Button, top)
CritButton = pto(MyButton, command=critCB, bg='white', fg='red')
WarnButton = pto(MyButton, command=warnCB, bg='goldenrod1')
ReguButton = pto(MyButton, command=infoCB, bg='white')

for eachSign in SIGNS:
    signType = SIGNS[eachSign]
    cmd = '%sButton(text=%r%s).pack(fill=X,expand=True)' % (signType.title(
Example #42
0
    def browse_folder(self, controller, br):

        if br == 0:
            self.filepath = tkFileDialog.askdirectory()
            arr = glob.glob(self.filepath + '/*/')
            arr.sort()
            self.dirs = {
                1: 'N.A.',
                2: 'N.A.',
                7: 'N.A.',
                30: 'N.A.',
                90: 'N.A.'
            }
            if arr != None:
                for f in arr:
                    f1 = f.lower()
                    if f1.find('day1') != -1:

                        self.dirs[1] = f

                    elif f1.find('day2') != -1:

                        self.dirs[2] = f

                    elif f1.find('day7') != -1:

                        self.dirs[7] = f

                    elif f1.find('day30') != -1:

                        self.dirs[30] = f

                    elif f1.find('day90') != -1:

                        self.dirs[90] = f

            if (self.dirs[1] == 'N.A.' and self.dirs[2] == 'N.A.'
                    and self.dirs[7] == 'N.A.' and self.dirs[30] == 'N.A.'
                    and self.dirs[90] == 'N.A.'):
                tkMessageBox.showerror("Error",
                                       'NO Directory of Patient Data Found')

        else:
            self.filepath = tkFileDialog.askdirectory()
            self.dirs[br] = self.filepath
            if br == 1:
                self.e1.delete(0, 'end')
            elif br == 2:
                self.e1.delete(0, 'end')
            elif br == 3:
                self.e1.delete(0, 'end')

            elif br == 4:
                self.e1.delete(0, 'end')
            else:
                self.e5.delete(0, 'end')

        controller.dirs = self.dirs
        controller.filepath = self.filepath
        self.e1.delete(0, 'end')
        self.e2.delete(0, 'end')
        self.e3.delete(0, 'end')
        self.e4.delete(0, 'end')
        self.e5.delete(0, 'end')
        self.e1.insert(0, self.dirs[1])
        self.e2.insert(0, self.dirs[2])
        self.e3.insert(0, self.dirs[7])
        self.e4.insert(0, self.dirs[30])
        self.e5.insert(0, self.dirs[90])

        print controller.dirs
        controller.dirs = self.dirs
        controller.filepath = self.filepath
Example #43
0
 def onError(self):
     tkMessageBox.showerror(
         "Error", "Could not determine file type from magic header.")
Example #44
0
    def set_plot(self, plot_type, xrange_=(0, 1000), yrange=(0, 20)):
        """
        Draws to the canvas according to the *plot_type* specified in the arguments. Accepts one of
        the attributes below

        .. py:attribute:: BASE_PLOT
        .. py:attribute:: BACKSCATTERED
        .. py:attribute:: DEPOLARIZED
        .. py:attribute:: VFM
        .. py:attribute:: IWP
        .. py:attribute:: HORIZ_AVG
        .. py:attribute:: AEROSOL_SUBTYPE

        :param int plot_type: accepts ``BASE_PLOT, BACKSCATTERED, DEPOLARIZED, VFM, IWP, HORIZ_AVG
        :param list xrange\_: accepts a range of time to plot
        :param list yrange: accepts a range of altitude to plot
        """
        self.xrange = xrange_
        self.yrange = yrange
        if plot_type == Plot.baseplot:
            # Hide the axis and print an image
            self.__shapemanager.set_plot(Plot.baseplot)

            im = mpimg.imread(PATH + '/dat/CALIPSO.jpg')
            self.__fig.get_yaxis().set_visible(False)
            self.__fig.get_xaxis().set_visible(False)
            self.__fig.imshow(im)
        elif plot_type == Plot.backscattered:
            try:
                # Clear any references to the current figure, construct a new figure
                # and render the backscattered plot to it
                logger.info('Setting plot to backscattered xrange: ' +
                            str(xrange_) + ' yrange: ' + str(yrange))
                self.__file = self.__data_block.get_file_name(1)
                logger.info('Using file ' + self.__file)
                # Reset if the file is not empty AND we are using granules from different time/place
                if self.__shapemanager.get_hdf() != '' and \
                                self.__file[-25:-4] != self.__shapemanager.get_hdf()[-25:-4]:
                    self.__shapemanager.reset(all_=True)
                else:
                    self.__shapemanager.clear_refs()
                self.__shapemanager.set_hdf(self.__file)
                self.__parent_fig.clear()
                self.__fig = self.__parent_fig.add_subplot(1, 1, 1)
                self.__fig = render_backscattered(self.__file, xrange_, yrange,
                                                  self.__fig,
                                                  self.__parent_fig)
                self.__shapemanager.set_current(Plot.backscattered, self.__fig)
                self.__drawplot_canvas.show()
                self.__toolbar.update()
                self.plot = Plot.backscattered
            except IOError:
                logger.error('IOError, no file exists')
                tkMessageBox.showerror('File Not Found', 'No File Exists')
            except IndexError:
                tkMessageBox.showerror('Backscattered Plot',
                                       'Index out of bounds')

        elif plot_type == Plot.depolarized:
            try:
                # Clear any references to the current figure, construct a new figure
                # and render the depolarized plot to it
                logger.info('Setting plot to depolarized xrange: ' +
                            str(xrange_) + ' yrange: ' + str(yrange))
                self.__file = self.__data_block.get_file_name(1)
                logger.info('Using file ' + self.__file)
                # Reset if the file is not empty AND we are using granules from different time/place
                if self.__shapemanager.get_hdf() != '' and \
                                self.__file[-25:-4] != self.__shapemanager.get_hdf()[-25:-4]:
                    self.__shapemanager.reset(all_=True)
                else:
                    self.__shapemanager.clear_refs()
                self.__shapemanager.set_hdf(self.__file)
                self.__parent_fig.clear()
                self.__fig = self.__parent_fig.add_subplot(1, 1, 1)
                self.__fig = render_depolarized(self.__file, xrange_, yrange,
                                                self.__fig, self.__parent_fig)
                self.__shapemanager.set_current(Plot.depolarized, self.__fig)
                self.__drawplot_canvas.show()
                self.__toolbar.update()
                self.plot = Plot.depolarized
            except IOError:
                logger.error('IOError, no file exists')
                tkMessageBox.showerror('File Not Found', "No File Exists")

        elif plot_type == Plot.vfm:
            try:
                # Clear any references to the current figure, construct a new figure
                # and render the depolarized plot to it
                logger.info('Setting plot to vfm xrange: ' + str(xrange_) +
                            ' yrange: ' + str(yrange))
                self.__file = self.__data_block.get_file_name(2)
                logger.info('Using file ' + self.__file)
                # Reset if the file is not empty AND we are using granules from different time/place
                if self.__shapemanager.get_hdf() != '' and \
                                self.__file[-25:-4] != self.__shapemanager.get_hdf()[-25:-4]:
                    self.__shapemanager.reset(all_=True)
                else:
                    self.__shapemanager.clear_refs()
                self.__shapemanager.set_hdf(self.__file)
                self.__parent_fig.clear()
                self.__fig = self.__parent_fig.add_subplot(1, 1, 1)
                self.__fig = render_vfm(self.__file, xrange_, yrange,
                                        self.__fig, self.__parent_fig)
                self.__shapemanager.set_current(Plot.vfm, self.__fig)
                self.__drawplot_canvas.show()
                self.__toolbar.update()
                self.plot = Plot.vfm
            except IOError:
                logger.error('IOError, no file exists')
                tkMessageBox.showerror('File Not Found', "No File Exists")

        elif plot_type == Plot.iwp:
            try:
                # Clear any references to the current figure, construct a new figure
                # and render the depolarized plot to it
                logger.info('Setting plot to iwp xrange: ' + str(xrange_) +
                            ' yrange: ' + str(yrange))
                self.__file = self.__data_block.get_file_name(2)
                logger.info('Using file ' + self.__file)
                # Reset if the file is not empty AND we are using granules from different time/place
                if self.__shapemanager.get_hdf() != '' and \
                                self.__file[-25:-4] != self.__shapemanager.get_hdf()[-25:-4]:
                    self.__shapemanager.reset(all_=True)
                else:
                    self.__shapemanager.clear_refs()
                self.__shapemanager.set_hdf(self.__file)
                self.__parent_fig.clear()
                self.__fig = self.__parent_fig.add_subplot(1, 1, 1)
                self.__fig = render_iwp(self.__file, xrange_, yrange,
                                        self.__fig, self.__parent_fig)
                self.__shapemanager.set_current(Plot.iwp, self.__fig)
                self.__drawplot_canvas.show()
                self.__toolbar.update()
                self.plot = Plot.iwp
            except IOError:
                logger.error('IOError, no file exists')
                tkMessageBox.showerror('File Not Found', "No File Exists")

        elif plot_type == Plot.horiz_avg:
            try:
                # Clear any references to the current figure, construct a new figure
                # and render the depolarized plot to it
                logger.info('Setting plot to horiz_avg xrange: ' +
                            str(xrange_) + ' yrange: ' + str(yrange))
                self.__file = self.__data_block.get_file_name(2)
                logger.info('Using file ' + self.__file)
                # Reset if the file is not empty AND we are using granules from different time/place
                if self.__shapemanager.get_hdf() != '' and \
                                self.__file[-25:-4] != self.__shapemanager.get_hdf()[-25:-4]:
                    self.__shapemanager.reset(all_=True)
                else:
                    self.__shapemanager.clear_refs()
                self.__shapemanager.set_hdf(self.__file)
                self.__parent_fig.clear()
                self.__fig = self.__parent_fig.add_subplot(1, 1, 1)
                self.__fig = render_horiz_avg(self.__file, xrange_, yrange,
                                              self.__fig, self.__parent_fig)
                self.__shapemanager.set_current(Plot.horiz_avg, self.__fig)
                self.__drawplot_canvas.show()
                self.__toolbar.update()
                self.plot = Plot.horiz_avg
            except IOError:
                logger.error('IOError, no file exists')
                tkMessageBox.showerror('File Not Found', "No File Exists")

        elif plot_type == Plot.aerosol_subtype:
            try:
                # Clear any references to the current figure, construct a new figure
                # and render the depolarized plot to it
                logger.info('Setting plot to aerosol_subtype xrange: ' +
                            str(xrange_) + ' yrange: ' + str(yrange))
                self.__file = self.__data_block.get_file_name(2)
                logger.info('Using file ' + self.__file)
                # Reset if the file is not empty AND we are using granules from different time/place
                if self.__shapemanager.get_hdf() != '' and \
                                self.__file[-25:-4] != self.__shapemanager.get_hdf()[-25:-4]:
                    self.__shapemanager.reset(all_=True)
                else:
                    self.__shapemanager.clear_refs()
                self.__shapemanager.set_hdf(self.__file)
                self.__parent_fig.clear()
                self.__fig = self.__parent_fig.add_subplot(1, 1, 1)
                self.__fig = render_aerosol_subtype(self.__file, xrange_,
                                                    yrange, self.__fig,
                                                    self.__parent_fig)
                self.__shapemanager.set_current(Plot.aerosol_subtype,
                                                self.__fig)
                self.__drawplot_canvas.show()
                self.__toolbar.update()
                self.plot = Plot.aerosol_subtype
            except IOError:
                logger.error('IOError, no file exists')
                tkMessageBox.showerror('File Not Found', "No File Exists")

        else:
            logger.warning('Plot Type not yet supported')
Example #45
0
    def VirtualProbe(self):
        netList = self.parent.Drawing.schematic.NetList()
        netListText = netList.Text()
        import SignalIntegrity.Lib as si
        cacheFileName = None
        if SignalIntegrity.App.Preferences['Cache.CacheResults']:
            cacheFileName = self.parent.fileparts.FileNameTitle()
        si.sd.Numeric.trySVD = SignalIntegrity.App.Preferences[
            'Calculation.TrySVD']
        snp = si.p.VirtualProbeNumericParser(si.fd.EvenlySpacedFrequencyList(
            SignalIntegrity.App.Project['CalculationProperties.EndFrequency'],
            SignalIntegrity.App.
            Project['CalculationProperties.FrequencyPoints']),
                                             cacheFileName=cacheFileName)
        snp.AddLines(netListText)
        progressDialog = ProgressDialog(self.parent,
                                        "Transfer Parameters",
                                        snp,
                                        snp.TransferMatrices,
                                        granularity=1.0)
        try:
            self.transferMatrices = progressDialog.GetResult()
        except si.SignalIntegrityException as e:
            messagebox.showerror('Virtual Probe',
                                 e.parameter + ': ' + e.message)
            return

        self.transferMatriceProcessor = si.td.f.TransferMatricesProcessor(
            self.transferMatrices)
        si.td.wf.Waveform.adaptionStrategy = 'SinX' if SignalIntegrity.App.Preferences[
            'Calculation.UseSinX'] else 'Linear'

        try:
            self.inputWaveformList = self.parent.Drawing.schematic.InputWaveforms(
            )
            self.sourceNames = netList.MeasureNames()
        except si.SignalIntegrityException as e:
            messagebox.showerror('Virtual Probe',
                                 e.parameter + ': ' + e.message)
            return

        progressDialog = ProgressDialog(self.parent, "Waveform Processing",
                                        self.transferMatriceProcessor,
                                        self._ProcessWaveforms)
        try:
            outputWaveformList = progressDialog.GetResult()
        except si.SignalIntegrityException as e:
            messagebox.showerror('Virtual Probe',
                                 e.parameter + ': ' + e.message)
            return

        self.outputWaveformLabels = netList.OutputNames()

        for outputWaveformIndex in range(len(outputWaveformList)):
            outputWaveform = outputWaveformList[outputWaveformIndex]
            outputWaveformLabel = self.outputWaveformLabels[
                outputWaveformIndex]
            for device in self.parent.Drawing.schematic.deviceList:
                if device['partname'].GetValue() in [
                        'Output', 'DifferentialVoltageOutput', 'CurrentOutput'
                ]:
                    if device['ref'].GetValue() == outputWaveformLabel:
                        # probes may have different kinds of gain specified
                        gainProperty = device['gain']
                        gain = gainProperty.GetValue()
                        offset = device['offset'].GetValue()
                        delay = device['td'].GetValue()
                        if gain != 1.0 or offset != 0.0 or delay != 0.0:
                            outputWaveform = outputWaveform.DelayBy(
                                delay) * gain + offset
                        outputWaveformList[
                            outputWaveformIndex] = outputWaveform
                        break
        userSampleRate = SignalIntegrity.App.Project[
            'CalculationProperties.UserSampleRate']
        outputWaveformList = [
            wf.Adapt(
                si.td.wf.TimeDescriptor(
                    wf.td.H, int(wf.td.K * userSampleRate / wf.td.Fs),
                    userSampleRate)) for wf in outputWaveformList
        ]
        self.SimulatorDialog().title('Virtual Probe: ' +
                                     self.parent.fileparts.FileNameTitle())
        self.SimulatorDialog().ExamineTransferMatricesDoer.Activate(True)
        self.SimulatorDialog().SimulateDoer.Activate(True)
        self.UpdateWaveforms(outputWaveformList, self.outputWaveformLabels)
Example #46
0
def report_callback_exception(self, *args):
    exception = traceback.format_exception(*args)
    tkMessageBox.showerror("Error", exception)
 def errorbox(self, title, message):
     tkMessageBox.showerror(title, message, master=self.editwin.text)
     self.editwin.text.focus_set()
Example #48
0
def error(msg):
    tkMessageBox.showerror("Error", msg)
Example #49
0
        path = os.path.abspath(os.path.dirname(__file__))
    except:
        # probably running inside py2exe which doesn't set __file__
        # Thx to http://www.pyweek.org/d/746/ XD
        path = ""
        pass

    done = False
    speechrec = captainsays is not None
    msg = None

    while not done:
        RESMAN.load_stuff(path)
        app = launcher.App(speechrec=speechrec)
        if msg:
            tkMessageBox.showerror(title="A mysterious error has occurred.",
                                   message=msg)
            msg = None

        app.mainloop()
        if not app.next_app:
            done = True
        else:
            cmd, opt = app.next_app
            if cmd == "edit":
                app = configcaptainsays.App(filename=opt)
                app.mainloop()
            elif cmd == "launch" and captainsays:
                msg = captainsays.main(filename=opt)
            else:
                done = True
            cmd = None
Example #50
0
 def onHelp(self):
     if Doer.helpKeys is None:
         messagebox.showerror('Help System',
                              'Cannot find or open this help element')
         return
     Doer.helpKeys.Open('sec:Simulator-Dialog')
Example #51
0
 def calculate(self):
     if len(self.points) < 4:
         return
     self.show_animation = False
     self.on_clear()
     for x in self.epicycles_id:
         self.canvas.delete(x)
     self.epicycles_id = []
     for x in self.through_lines_id:
         self.canvas.delete(x)
     self.through_lines_id = []
     self.listbox_epicycles.delete(0, tk.END)
     if self.interpolation == 1:
         _z = (np.append(self.points[::2], [self.points[0]]) + \
                     np.append(self.points[1::2], [self.points[1]]) * 1.0j)/window.SIZE
         _t = np.arange(len(_z))
         f = interp1d(_t, _z)
         t = np.linspace(0, len(_z) - 1, window.L_BIN)
         array = f(t)
     elif self.interpolation == 2:
         try:
             ax = np.append(self.points[::2], [self.points[0]])
             ay = np.append(self.points[1::2], [self.points[1]])
             tck, u = splprep([ax, ay], s=0)
             unew = np.linspace(0, 1, window.L_BIN)
             out = splev(unew, tck)
             array = out[0] / window.SIZE + out[1] * 1.0j / window.SIZE
         except SystemError:
             msgbox.showerror(
                 'Error', 'Bad input points: \n'
                 'Did you click somewhere more than once?\n'
                 'Try change input points or use another interpolation algorithm.',
                 icon='error')
             self.button_animation.configure(state=tk.DISABLED)
             return
     else:
         array = np.append(self.points[::2], [self.points[0]])/window.SIZE + \
             np.append(self.points[1::2], [self.points[1]])/window.SIZE*1.0j
     acircle = fft2circle.get_circle_fft(array[:-1])
     self.r = []
     self.p = []
     self.n = []
     self.v = []
     self.max_through_lines = 0
     if self.sorted_flag:
         acircle = sorted(acircle, key=lambda _: -_[0])
     tmp = 0
     for k, (r, n, l, p) in enumerate(acircle):
         if r * window.SIZE < window.MIN_CIRCLE_SIZE:
             tmp += 1
             continue  # filter the circles which are too small
         elif r * window.SIZE > window.LINED_CIRCLE_MIN:
             self.max_through_lines += 1
             self.through_lines_id.append(
                 self.canvas.create_line(0, 0, 0, 0, fill='blue'))
         self.r.append(r * window.SIZE)
         self.p.append(p)
         self.n.append(n)
         self.v.append(l)
         self.epicycles_id.append(self.canvas.create_oval(0, 0, 0, 0))
         self.listbox_epicycles.insert(
             tk.END,
             'circle[%d] radius=%3.3f phi=%3.3f frequency=%3d %sclockwise' %
             (k - tmp, self.r[-1], self.p[-1], n, l == 1 and 'counter'
              or ''))
     export_flag and self.button_export.configure(state=tk.NORMAL)
     self.button_animation.configure(state=tk.NORMAL)
Example #52
0
def exportAddon(xmlAddonStructure, settings, calcFiles, afile=None):
    def verifyDestDir(dstFile, afile):
        if afile == None:
            dstDirectory, dstName = os.path.split(dstFile)
            if not os.path.exists(dstDirectory):
                os.makedirs(dstDirectory)

    def calcStringFiles(srcFile, dstFile, calcFiles, afile=None):
        verifyDestDir(dstFile, afile)
        srcString = calcFiles[srcFile]
        if not srcString: return
        if afile == None:
            with open(dstFile, 'w') as wfile:
                wfile.write(srcString)
        else:
            afile.writestr(dstFile, srcString)

    def copySrcFile(srcFile, dstFile, afile=None):
        verifyDestDir(dstFile, afile)
        if afile == None:
            shutil.copyfile(srcFile, dstFile)
        else:
            afile.write(srcFile, dstFile)

    root = ET.parse(xmlAddonStructure).getroot()
    lastDirectory = ''
    for elem in root.iter():
        if elem.tag == 'structure':
            path = elem.get('path')
            path = settings[path]
            if not afile:
                baseDirectory = translatePath('special://home/addons')
                baseDirectory = os.path.join(baseDirectory, path)
                if os.path.exists(baseDirectory):
                    if tkMessageBox.askokcancel(
                            'Export addon',
                            'El directorio propuesto ya existe, desea sobreescribirlo'
                    ):
                        try:
                            shutil.rmtree(baseDirectory, ignore_errors=True)
                        except:
                            tkMessageBox.showerror('Error',
                                                   'Directory acces dennied')
                            return
            else:
                afile = zipfile.ZipFile(addonzip, 'w')
                baseDirectory = path
            lastDirectory = os.path.normpath(baseDirectory)
        elif elem.tag == 'folder':
            nameId = elem.get('id')
            path = elem.get('path')
            if not path: continue
            if elem.get('optional') == 'false' or (
                    settings.has_key(nameId)
                    and not elem.attrib.has_key('name')):
                path = os.path.join(baseDirectory, path)
                lastDirectory = os.path.normpath(path)
            elif settings.has_key(nameId) and elem.attrib.has_key('name'):
                name = elem.get('name')
                if name in settings[nameId]:
                    resourceFiles = [
                        kElem.split(',')
                        for kElem in settings[nameId].split('|')
                    ]
                    path = os.path.join(baseDirectory, path)
                    for ka in resourceFiles:
                        if name not in ','.join(ka): continue
                        srcName = ka[0]
                        dstName = os.path.normpath(os.path.join(path, srcName))
                        copySrcFile(srcName, dstName, afile)
            else:
                continue
        elif elem.tag == 'file':
            nameId = elem.get('id')
            if elem.get('optional') == 'false':
                srcName = settings.get(nameId, None) or elem.get('name')
                dstName = os.path.join(lastDirectory, srcName)
                calcStringFiles(srcName, dstName, calcFiles, afile)
            else:
                if settings.has_key(nameId):
                    srcName = settings[nameId]
                    if not os.path.exists(srcName): continue
                    dstName = elem.get('name')
                    dstName = os.path.join(lastDirectory, dstName)
                    copySrcFile(srcName, dstName, afile)
                else:
                    continue
    if afile: afile.close()
Example #53
0
def get_dir(folder_name=None):
    """get_dir returns the top-level directory of the package as an absolute path if :attr:`folder_name` is not
    specified [1]. If an exiting sub directory is specified as `str` into the field :attr:`folder_name` then the
    return of get_dir will be absolute path to this sub directory [2]. Usage with file names inside a directory is also
    possible, see example below [3]

    :param folder_name: The name of a folder, file, or relative path
    :type folder_name: basestring

    :return: The absolute path to the root directory or, if specified, to a sub directory within the root
    :rtype: unicode


    [1] Obtaining Root Directory:

    >>> get_dir() # This will return the absolute path to root directory
    C:/Python27/KBE

    [2] Obtaining a Sub-Directory:

    >>> get_dir('icons') # This will return the absolute path to the subdirectory /icons
    C:/Python27/KBE\icons

    [3] Obtaining File-Directory:

    >>> get_dir('user/userinput.xlsx') # This will return the absolute path to the file userinput.xlsx
    C:/Python27/KBE\user\userinput.xlsx

    """

    encoding = sys.getfilesystemencoding()  # A variable that returns encoding of the user's machine

    if is_frozen():  # Checks if the user is running through an .exe or from Python, Refer to is_frozen definition above
        root = os.path.join(os.path.dirname(unicode(sys.executable, encoding)),
                            "KBE")
    else:
        root = os.path.dirname(unicode(__file__, encoding))

    if folder_name is None:  # Checks if user has specified a value for field :attr:`folder_name`
        return root
    else:
        if isinstance(folder_name, str) or isinstance(folder_name, unicode):  # Check if folder_name has valid input
            subdir = os.path.join(root, folder_name)
            if os.path.isdir(subdir) or os.path.isfile(subdir):  # Check to see if folder_name is a valid path or file
                return subdir
            else:
                # TODO (TBD) Properly distinguish between folder and file type
                if subdir.find('.') != -1:  # Error handling to see if user was looking for a file or directory
                    msg = ('Specified file %s does not exist' % subdir)
                    root = Tk()
                    root.withdraw()
                    tkMessageBox.showerror("Warning", msg)
                    root.destroy()
                    raise NameError('Specified file %s does not exist' % subdir)
                else:
                    msg = ('Specified directory %s does not exist' % subdir)
                    root = Tk()
                    root.withdraw()
                    tkMessageBox.showerror("Warning", msg)
                    root.destroy()
                    raise NameError('Specified directory %s does not exist' % subdir)
        else:
            msg = ('Please enter a valid string or unicode path into folder_name, %s is %s' % (folder_name,
                                                                                               type(folder_name)))
            raise TypeError(msg)
Example #54
0
    def chemicals_error(self):

        tkmb.showerror(title=self.version,
                       message='This chemical has already been selected!')
        self.focusbutton = self.okbutton
        self.master.tk.lift()
Example #55
0
def message_box(title, Message):
    root.iconbitmap(path_dir_root + "\\images\\" + "folder.ico")
    root.attributes("-topmost", True)
    tkMessageBox.showerror(title, Message)
    formConvert.Focus()
Example #56
0
 def errorbox(self, title, message):
     # XXX This should really be a function of EditorWindow...
     tkMessageBox.showerror(title, message, master=self.editwin.text)
     self.editwin.text.focus_set()
Example #57
0
    def processEcuacion(self):
        """
        Procesamos los datos de la ecuacion
        """

        ec = self.txtEcuacion.get()
        h = self.txtH.get()
        inicio = self.txtInicio.get()
        pares = self.comboPares.get()

        # verificamos que los input esten llenos
        if len(ec) > 0 and len(h) > 0 and len(pares) > 0 and len(inicio) > 0:
            # creamos la rejilla
            width = 780 / (int(pares) + 1)
            dato1 = []
            dato2 = []

            # desactivamos el boton y campo de entrada
            self.txtEcuacion.config(state="disabled")
            self.txtInicio.config(state="disabled")
            self.txtH.config(state="disabled")
            self.comboPares.config(state="disabled")

            # Campos por default
            lblTemp = tk.Label(self.parent,
                               text="Puntos",
                               anchor=tk.W,
                               justify=tk.CENTER)
            lblTemp.place(x=10, y=70, width=width, height=20)
            lblTemp.config(font=self.font, bg=self.bg)

            lblTemp1 = tk.Label(self.parent, text="F(x)")
            lblTemp1.place(x=10, y=90, width=width, height=20)
            lblTemp1.config(font=self.font, bg=self.bg)

            lblTemp2 = tk.Label(self.parent, text="X")
            lblTemp2.place(x=10, y=110, width=width, height=20)
            lblTemp2.config(font=self.font, bg=self.bg)

            dato1.append(lblTemp1)
            dato2.append(lblTemp2)

            inicio = int(inicio)

            for i in range(0, int(pares)):
                # Etiqueta de puntos
                lblTemp = tk.Label(self.parent,
                                   text="" + str(i),
                                   anchor=tk.W,
                                   justify=tk.CENTER)
                lblTemp.place(x=(10 + (width * (i + 1))),
                              y=70,
                              width=width,
                              height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                # datos 1
                val = self.f(ec, inicio)
                v = tk.StringVar(self.parent, value=val)
                txtTemp1 = tk.Entry(self.parent, textvariable=v)
                txtTemp1.place(x=(10 + (width * (i + 1))),
                               y=90,
                               width=width,
                               height=20)

                # datos 2
                v = tk.StringVar(self.parent, value=inicio)
                txtTemp2 = tk.Entry(self.parent, textvariable=v)
                txtTemp2.place(x=(10 + (width * (i + 1))),
                               y=110,
                               width=width,
                               height=20)
                inicio += int(h)

                dato1.append(txtTemp1)
                dato2.append(txtTemp2)
            #guardamos los datos
            self.dato1 = dato1
            self.dato2 = dato2

            btnCalcular = tk.Button(
                self.parent,
                text="Procesar",
                command=lambda: self.processEcuacionTable())
            btnCalcular.place(x=10, y=140, width=150, height=20)
            btnCalcular.config(font=self.font)
        else:
            # Mensaje de error
            text = "Por favor llene todos los campos"
            tkMessageBox.showerror(title="Error", message=text)
Example #58
0
    def send_message(self, info):
        
        uu = info["uu"]
        ww = info["ww"]

        FROM = info["uu"]
        TO = [info["recipient1"], info["recipient2"], info["recipient3"], info["recipient4"], info["recipient5"], ]  # must be a list
        TO =[recipent for recipent in TO if recipent.replace(" ","")] 
        
        

        s = cfg['General']['LOCATION'][1:-1]
        SUBJECT = "Location: "+s+"; "+info["subject"] 

        s = cfg['Engine0']['IP']
        TEXT = info["message"] + "\n" + \
                "Engine IP = " + s
       
        # Prepare actual message   """\From: %s\nTo: %s\nSubject: %s\n\n%s     
        message = """From: %s\nTo: %s\nSubject: %s\n\n%s     
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
        ans = tkMessageBox.askokcancel("Send Email", 
            "The following test Message will be sent out :\r\r%s" % message[1:])

        
        if ans != True:
            tkMessageBox.showinfo("Send Email", "Action has been cancelled.")
            return False

        try:
            if smtp_ssl == "Yes":
                server = smtplib.SMTP_SSL(info["server"], info["port"])
               
            else:
                smtp_host = info["server"]
                smtp_port = info["port"]
                server = smtplib.SMTP()
                print 'server:',server
        except:
            dbg.printDBG1(file_name, "Failed to access smtp server!")
            tkMessageBox.showerror("Send Email", "Not able to access the smtp server") 
            return False
        try:
            if smtp_ssl != "Yes":
                server.connect(smtp_host,smtp_port)
#                server.settimeout(10)
                server.ehlo()
                server.starttls()
            server.login(uu,ww)
            
        except:
            print 'cannot connect...'
            dbg.printDBG1(file_name, "Wrong ID or PW")
            tkMessageBox.showerror("Send Email", "Wrong ID or PW!")
            return False
        try:    
            server.sendmail(FROM, TO,message)       

        except:
            dbg.printDBG1(file_name, "Failed to sent email")
            tkMessageBox.showerror("Send Email", "Not able to send email!")
            return False

        server.close()
        dbg.printDBG1(file_name, "Successfully sent email")
        
        return True
Example #59
0
    def processValuePares(self, dif):
        """
        Procesamos el valor, recivimos clase de diferencias
        """

        # Obtenemos N pares
        val = self.txtValor.get()

        if len(val) > 0:
            # verificamos con que diferencias trabajar
            if self.control:
                # Mostramos por diferencias finitas

                # volvemos a procesar los valores
                dif.processValueFinitas(val)

                # Obtenemos valores
                ec = dif.ecRed
                valor = dif.value
                res = dif.res
                # Mostramos la ecuacion
                areaExpr = tk.Text(self.parent)
                areaExpr.place(x=10, y=330, width=780, height=80)
                areaExpr.insert(tk.END, ec)
                areaExpr.config(font=self.font, bg=self.bg)
                areaExpr.config(state="disabled")

                # Mostramos los resultados
                lblTemp = tk.Label(self.parent,
                                   text="Valor interpolado: ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=420, width=280, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                v = tk.StringVar(self.parent, value=valor)
                txtValor = tk.Entry(self.parent, textvariable=v)
                txtValor.place(x=300, y=420, width=400, height=20)
                txtValor.focus()

                lblTemp = tk.Label(self.parent,
                                   text="Valor R" + str(len(res) - 1) + "(" +
                                   str(val) + "): ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=450, width=280, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                v = tk.StringVar(self.parent, value=res[0])
                txtValor = tk.Entry(self.parent, textvariable=v)
                txtValor.place(x=300, y=450, width=400, height=20)
                txtValor.focus()

                lblTemp = tk.Label(self.parent,
                                   text="Valor d" + str(len(res) - 1) + "R" +
                                   str(len(res) - 1) + "(" + str(val) +
                                   ")/dx: ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=480, width=280, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                v = tk.StringVar(self.parent, value=res[len(res) - 1])
                txtValor = tk.Entry(self.parent, textvariable=v)
                txtValor.place(x=300, y=480, width=400, height=20)
                txtValor.focus()
            else:
                # Mostramos por diferencias divididas

                # volvemos a procesar los valores
                dif.processValueDivididas(val)

                # Obtenemos valores
                ec = dif.ecRed
                valor = dif.value
                res = dif.res
                # Mostramos la ecuacion
                areaExpr = tk.Text(self.parent)
                areaExpr.place(x=10, y=330, width=780, height=80)
                areaExpr.insert(tk.END, ec)
                areaExpr.config(font=self.font, bg=self.bg)
                areaExpr.config(state="disabled")

                # Mostramos los resultados
                lblTemp = tk.Label(self.parent,
                                   text="Valor interpolado: ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=420, width=280, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                v = tk.StringVar(self.parent, value=valor)
                txtValor = tk.Entry(self.parent, textvariable=v)
                txtValor.place(x=300, y=420, width=400, height=20)
                txtValor.focus()

                lblTemp = tk.Label(self.parent,
                                   text="Valor R" + str(len(res) - 1) + "(" +
                                   str(val) + "): ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=450, width=280, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                v = tk.StringVar(self.parent, value=res[0])
                txtValor = tk.Entry(self.parent, textvariable=v)
                txtValor.place(x=300, y=450, width=400, height=20)
                txtValor.focus()

                lblTemp = tk.Label(self.parent,
                                   text="Valor d" + str(len(res) - 1) + "R" +
                                   str(len(res) - 1) + "(" + str(val) +
                                   ")/dx: ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=480, width=280, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                v = tk.StringVar(self.parent, value=res[len(res) - 1])
                txtValor = tk.Entry(self.parent, textvariable=v)
                txtValor.place(x=300, y=480, width=400, height=20)
                txtValor.focus()

            btnGraph = tk.Button(self.parent,
                                 text="Graficar",
                                 command=lambda: self.graficar(dif))
            btnGraph.place(x=380, y=570, width=200, height=20)
            btnGraph.config(font=self.font)
        else:
            # Mensaje de error
            text = "Ingrese el valor a interpolar"
            tkMessageBox.showerror(title="Error", message=text)
Example #60
0
    def crearPares(self):
        """
        Creamos la tabla para el ingreso de datos pares
        """
        grado = self.txtPares.get()

        # verificamos que todos los campos esten llenos
        if len(grado) != 0:
            if int(grado) >= 2 and int(grado) <= 10:
                width = 780 / (int(grado) + 1)
                dato1 = []
                dato2 = []

                # desactivamos el boton y campo de entrada
                self.txtPares.config(state="disabled")
                self.btnPares.config(state="disabled")

                # Campos por default
                btnReset = tk.Button(self.parent,
                                     text="Limpiar",
                                     command=lambda: self.reset())
                btnReset.place(x=640, y=570, width=150, height=20)
                btnReset.config(font=self.font)

                lblTemp = tk.Label(self.parent,
                                   text="Puntos",
                                   anchor=tk.W,
                                   justify=tk.CENTER)
                lblTemp.place(x=10, y=10, width=width, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                txtTemp1 = tk.Entry(self.parent)
                txtTemp1.place(x=10, y=30, width=width, height=20)
                txtTemp1.focus()

                txtTemp2 = tk.Entry(self.parent)
                txtTemp2.place(x=10, y=50, width=width, height=20)

                dato1.append(txtTemp1)
                dato2.append(txtTemp2)

                for i in range(0, int(grado)):
                    # Etiqueta de puntos
                    lblTemp = tk.Label(self.parent,
                                       text="" + str(i),
                                       anchor=tk.W,
                                       justify=tk.CENTER)
                    lblTemp.place(x=(10 + (width * (i + 1))),
                                  y=10,
                                  width=width,
                                  height=20)
                    lblTemp.config(font=self.font, bg=self.bg)

                    # datos 1
                    txtTemp1 = tk.Entry(self.parent)
                    txtTemp1.place(x=(10 + (width * (i + 1))),
                                   y=30,
                                   width=width,
                                   height=20)

                    # datos 2
                    txtTemp2 = tk.Entry(self.parent)
                    txtTemp2.place(x=(10 + (width * (i + 1))),
                                   y=50,
                                   width=width,
                                   height=20)

                    dato1.append(txtTemp1)
                    dato2.append(txtTemp2)
                #guardamos los datos
                self.dato1 = dato1
                self.dato2 = dato2

                # Seleccion del intervalo
                lblTemp = tk.Label(self.parent,
                                   text="Grado de la ecuación:",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=80, width=240, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                self.comboGrado = ttk.Combobox(self.parent, state="readonly")
                self.comboGrado.place(x=260, y=80, width=100, height=20)
                self.comboGrado["values"] = range(1, int(grado))
                self.comboGrado.bind("<<ComboboxSelected>>",
                                     self.selection_changed)
            elif int(grado) == 0:
                lblTemp = tk.Label(self.parent,
                                   text="Ingrese la ecuación:",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=10, width=280, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                self.txtEcuacion = tk.Entry(self.parent)
                self.txtEcuacion.place(x=290, y=10, width=380, height=20)
                self.txtEcuacion.focus()

                # Para borrar contenido
                lblTemp = tk.Label(self.parent,
                                   text="",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=40, width=780, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                lblTemp = tk.Label(self.parent,
                                   text="valor de h: ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=10, y=40, width=160, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                self.txtH = tk.Entry(self.parent)
                self.txtH.place(x=150, y=40, width=70, height=20)

                lblTemp = tk.Label(self.parent,
                                   text="Datos Inicial: ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=230, y=40, width=180, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                self.txtInicio = tk.Entry(self.parent)
                self.txtInicio.place(x=420, y=40, width=100, height=20)

                lblTemp = tk.Label(self.parent,
                                   text="Datos pares: ",
                                   anchor=tk.W,
                                   justify=tk.LEFT)
                lblTemp.place(x=530, y=40, width=180, height=20)
                lblTemp.config(font=self.font, bg=self.bg)

                self.comboPares = ttk.Combobox(self.parent, state="readonly")
                self.comboPares.place(x=690, y=40, width=100, height=20)
                self.comboPares["values"] = range(2, 5)
                self.comboPares.bind("<<ComboboxSelected>>",
                                     self.selection_changed_ec)

                btnReset = tk.Button(self.parent,
                                     text="Limpiar",
                                     command=lambda: self.reset())
                btnReset.place(x=640, y=570, width=150, height=20)
                btnReset.config(font=self.font)
            else:
                # Mensaje de error
                text = "Ingrese un número entre 2 y 10."
                tkMessageBox.showerror(title="Error", message=text)
        else:
            # Mensaje de error
            text = "Por favor ingrese la cantidad de datos pares"
            tkMessageBox.showerror(title="Error", message=text)