def on_startStopButton_mouseClick(self,event):  
     if not self.on_runName_loseFocus():
         return False
     try:
         isCorrectFilename(self.filename);
     except:
         dialog.alertDialog(self,"The filename is not correct".\
             format(self.filename),'Check you filename')
         return
     if not self._testSerialDevice(self.serialAr,' AR DEVICE'):
         return False
     if not self._testSerialDevice(self.serialArduino,' ARDUINO DEVICE'):
         return False
     if not self._testSerialDevice(self.serialImu,' IMU DEVICE'):
         return False
     if self.components.startStopButton.checked:
         #------- dialog.alertDialog(self,'Startng RUN','Check you run name')
         #------------------------------------ self._setRunMeta(self.runName)
         self.components.startStopButton.label = STARTBUTTON_STOP
         self.components.startStopButton.backgroundColor = STARTBUTTON_BACKGROUNDCOLOR_STOP
         self.running = True;
     elif self.running:
         #------ dialog.alertDialog(self,'Stopping RUN','Check you run name')
         self.running = False;
         self.components.startStopButton.label = STARTBUTTON_WAIT
         self.components.startStopButton.enabled = False;
 def on_startStopButton_mouseClick(self, event):
     if not self.on_runName_loseFocus():
         return False
     try:
         isCorrectFilename(self.filename)
     except:
         dialog.alertDialog(self, "The filename is not correct".format(self.filename), "Check you filename")
         return
     if not self._testSerialDevice(self.serialAr, " AR DEVICE"):
         return False
     if not self._testSerialDevice(self.serialArduino, " ARDUINO DEVICE"):
         return False
     if not self._testSerialDevice(self.serialImu, " IMU DEVICE"):
         return False
     if self.components.startStopButton.checked:
         # ------- dialog.alertDialog(self,'Startng RUN','Check you run name')
         # ------------------------------------ self._setRunMeta(self.runName)
         self.components.startStopButton.label = STARTBUTTON_STOP
         self.components.startStopButton.backgroundColor = STARTBUTTON_BACKGROUNDCOLOR_STOP
         self.running = True
     elif self.running:
         # ------ dialog.alertDialog(self,'Stopping RUN','Check you run name')
         self.running = False
         self.components.startStopButton.label = STARTBUTTON_WAIT
         self.components.startStopButton.enabled = False
Пример #3
0
 def on_cmdSizeOK_mouseClick(self, evt):
     comps = self.components
     save = self.saveChanges()
     if save == "Cancel":
         # don't do anything, just go back to editing
         return
     elif save == "No":
         # any changes will be lost
         pass
     else:
         self.on_cmdSave_mouseClick(event)
     case = comps.mapSize.stringSelection
     print case
     if case == '150x150':
         self.WIDTH = self.HEIGHT = 150
     if case == '100x100':
         self.WIDTH = self.HEIGHT = 100
     if case == '50x50':
         self.WIDTH = self.HEIGHT = 50
     if case == 'custom':
         xxx = comps.txtMapSize.text
         ddd = splitfields(xxx,'x')
         if int(ddd[0]) >= screen_w and int(ddd[1]) >= screen_h:
             self.WIDTH = int(ddd[0])
             self.HEIGHT = int(ddd[1])
         else:
             dialog.alertDialog(self, 'Map size is not supported.','Error')
             return
     comps.sliderX.max = self.WIDTH - screen_w
     comps.sliderY.max = self.HEIGHT - screen_h
     comps.sliderX.value = 0
     comps.sliderY.value = 0
     print 'New dimensions',self.WIDTH, self.HEIGHT
     self.newMap()
     self.drawMap()
Пример #4
0
 def wrong_guess(self):
     dialog.alertDialog(self, "WRONG!!!", 'Hangman')
     if self.components.head.visible == True:
         if self.components.body.visible == True:
             if self.components.arm1.visible == True:
                 if self.components.arm2.visible == True:
                     if self.components.foot1.visible == True:
                         if self.components.foot2.visible == True:
                             dialog.alertDialog(
                                 self,
                                 "You lost! Word was " + self.currentword,
                                 'Hangman')
                             self.new_game()
                         else:
                             self.components.foot2.visible = True
                     else:
                         self.components.foot1.visible = True
                 else:
                     self.components.arm2.visible = True
             else:
                 self.components.arm1.visible = True
         else:
             self.components.body.visible = True
     else:
         self.components.head.visible = True
Пример #5
0
 def on_btnGuessWord_mouseClick(self, event):
     result = dialog.textEntryDialog(self, 'What is the word', 'Hangman',
                                     'the word')
     self.components.stYourGuesses.text = \
         self.components.stYourGuesses.text + "  " + result.text + " "
     if (result.text).strip() == (self.currentword).strip():
         dialog.alertDialog(self, 'You did it!', 'Hangman')
         self.new_game()
     else:
         self.wrong_guess()
Пример #6
0
 def on_btnGuessWord_mouseClick(self, event):
     result = dialog.textEntryDialog(self,
      'What is the word','Hangman','the word')
     self.components.stYourGuesses.text = \
         self.components.stYourGuesses.text + "  " + result.text + " "
     if (result.text).strip() == (self.currentword).strip():
         dialog.alertDialog(self, 'You did it!', 'Hangman')
         self.new_game()
     else:
         self.wrong_guess()
    def _testSerialDevice(self, device, errorString):
        if device:
            try:

                if not os.path.exists(device):
                    dialog.alertDialog(self, "The " + errorString + " is not a serial device", "Device Problem")
                    return False
            except:
                dialog.alertDialog(self, "The " + errorString + " cannot be opened." + str(device), "Device Problem")
                return False
        return True
 def on_runName_loseFocus(self, event=None):
     self.runName = self.components.runName.getLineText(0)
     if not self.runName:
         dialog.alertDialog(self, "The Run Name is not set.", "Check you run name")
         return False
     self._setRunMeta(self.runName)
     if self.filename:
         theRuns = [self._getBaseRunName(runName) for runName in SofiePyTableAccess.getRunsInTheFile(self.filename)]
         if self.runName in theRuns:
             dialog.alertDialog(self, "The Run Name already exists.", "Check you run name")
             return False
     return True
 def _testSerialDevice(self,device,errorString):
     if device:
         try:
             
             if not os.path.exists(device):
                 dialog.alertDialog(self,'The '+errorString+' is not a serial device','Device Problem')
                 return False
         except:
             dialog.alertDialog(self,'The '+errorString+' cannot be opened.'+\
                                str(device),'Device Problem')
             return False
     return True
 def on_runName_loseFocus(self, event=None):
     self.runName = self.components.runName.getLineText(0)
     if not self.runName:
         dialog.alertDialog(self,'The Run Name is not set.','Check you run name')
         return False
     self._setRunMeta(self.runName)
     if self.filename:
         theRuns = [self._getBaseRunName(runName) for runName in SofiePyTableAccess.getRunsInTheFile(self.filename)];
         if self.runName in theRuns:
             dialog.alertDialog(self,'The Run Name already exists.','Check you run name')
             return False
     return True
 def on_viewVideo_mouseClick(self, event):
     if not self.runName:
         dialog.alertDialog(self, "The Run Name is not set.", "Check you run name")
         return
     if not self.filename:
         dialog.alertDialog(self, "The filename is not correct".format(self.filename), "Check you filename")
         return
     if self.components.viewVideo.checked:
         self.videoExporting = True
     else:
         self.videoExporting = False
         self.components.viewVideo.enabled = False
Пример #12
0
 def on_Calculate_mouseClick(self, event):
     comp = self.components
     try:
         principal = float(comp.Principal.text)
         interestRate = float(comp.InterestRate.text)
         if interestRate > 1:
             interestRate = interestRate / 100.0
         payment15 = pyfi.amortization(principal, interestRate, 12, 15 * 12)
         payment30 = pyfi.amortization(principal, interestRate, 12, 30 * 12)
         comp.Result.text = "15 year monthly payment: %.2f\n30 year monthly payment: %.2f" % (payment15, payment30)
     except ValueError:
         dialog.alertDialog(self, 'Please enter valid values', 'Input Value(s) Error')
Пример #13
0
 def on_okbutton_mouseClick(self, event):
     novelurls = self.components.novellinks.text
     if not novelurls:
         result = dialog.alertDialog(self, 'Novel link needed', 'ERROR')
         return
     savedir = self.components.savedir.text
     if not savedir or savedir =='':
         result = dialog.alertDialog(self, 'Save to dir needed', 'ERROR')
         return
     novelProcessThread = NovelProcess(self, novelurls, savedir)
     novelProcessThread.start()
     self.disableComponent()
Пример #14
0
 def on_btnOK_mouseClick(self, event):
     if self.components.sessionName.text == 'Defaults':
         self.parent.cfg.set(self.components.sessionName.text, 'port',
                             self.components.portNumber.text)
         self.parent.cfg.set(self.components.sessionName.text, 'user',
                             self.components.userName.text)
         self.parent.cfg.set(self.components.sessionName.text,
                             'identityfile',
                             self.components.identityFile.text)
         self.parent.cfg.set(self.components.sessionName.text, 'command',
                             self.components.connectCmd.text)
         event.skip()
     elif self.components.sessionName.text == 'NewSession':
         bull = dialog.alertDialog(self, 'Invalid session name', 'Oops!')
     else:
         if self.components.hostName.text == '' and self.components.sessionName.text != 'Defaults':
             bull = dialog.alertDialog(self,
                                       'You must enter a valid host name',
                                       'Oops!')
         else:
             accept = 1
             try:
                 bull = socket.gethostbyname(self.components.hostName.text)
             except socket.gaierror:
                 msgtxt = '"%s" may not be a valid DNS hostname. ' % self.components.hostName.text
                 msgtxt += 'This may be because you do not currently have a connection to the internet, '
                 msgtxt += 'or it may be that the name you have entered really is invalid. Do you '
                 msgtxt += 'want to accept it anyway?'
                 result = dialog.messageDialog(
                     self, wrap_string(msgtxt, 50), 'Warning:',
                     wx.ICON_EXCLAMATION | wx.YES_NO | wx.NO_DEFAULT)
                 accept = result.accepted
             if accept:
                 if not self.parent.cfg.has_section(
                         self.components.sessionName.text):
                     self.parent.cfg.add_section(
                         self.components.sessionName.text)
                 self.parent.cfg.set(self.components.sessionName.text,
                                     'hostname',
                                     self.components.hostName.text)
                 self.parent.cfg.set(self.components.sessionName.text,
                                     'port',
                                     self.components.portNumber.text)
                 self.parent.cfg.set(self.components.sessionName.text,
                                     'user', self.components.userName.text)
                 self.parent.cfg.set(self.components.sessionName.text,
                                     'identityfile',
                                     self.components.identityFile.text)
                 self.parent.cfg.set(self.components.sessionName.text,
                                     'command',
                                     self.components.connectCmd.text)
                 event.skip()
 def on_viewVideo_mouseClick(self,event):
     if not self.runName:
         dialog.alertDialog(self,'The Run Name is not set.','Check you run name')
         return
     if not self.filename:
         dialog.alertDialog(self,"The filename is not correct".\
             format(self.filename),'Check you filename')
         return
     if self.components.viewVideo.checked:
         self.videoExporting = True
     else:
         self.videoExporting = False
         self.components.viewVideo.enabled = False;
Пример #16
0
 def on_btnPlay_mouseClick(self, event):
     filename = self.components.fldFilename.text
     async = self.components.chkAsync.checked
     loop = self.components.chkLoop.checked
     # I don't know how to stop a looped sound playing!
     try:
         snd = sound.Sound(filename)
         snd.play(async, loop)
     except sound.SoundFileError:
         base = os.path.basename(filename)
         dialog.alertDialog(
             self,
             'The sound file "%s" is not in a format I can understand.' %
             base, 'Unknown File Type')
 def on_filename_closeField(self, event=None):
     self.filename = self.components.filename.getLineText(0)
     try:
         isCorrectFilename(self.filename);
     except OutFileMustBeh5Extention:
         dialog.alertDialog(self,"The filename ({0}) must be specified with an '.h5' extension.".\
             format(self.filename),'Check you filename')
         return
     except OutFileMustBeAbsolutePath:
         dialog.alertDialog(self,"The filename ({0}) must be an absolute path.".\
             format(self.filename),'Check you filename')
         return
     self.title = os.path.split(self.filename)[-1] + ' - ' + self.startTitle
     self.statusBar.text = self.filename
     self._updateRunList()  
 def on_menuHelpHelp_select(self, event):
     try:
         f = open('_READ_ME_FIRST.txt', "r")
         msg = f.read()
         result = dialog.scrolledMessageDialog(self, msg, 'readme.txt')
     except:
         result = dialog.alertDialog(self, 'Help file missing', 'Problem with the Help file')
Пример #19
0
 def on_initialize(self, event):
     import ConfigParser
     self.parser = ConfigParser.ConfigParser()
     self.parser.read(configFile)
     "put the company list into the listbox"
     self.dataFile = self.parser.get('ConfigData', 'data')
     rows = open(self.dataFile, 'r').readlines()
     self.selected = self.parser.getint('ConfigData', 'selected')
     self.rowsDict = []
     line = 0
     for r in rows:
         line += 1
         r = r[:-1]  # remove the \n here
         r = r.replace(r'\012', '\n')  # convert coded 012 back to \n
         if r.count(',') == 18:
             d = {}
             i = 0
             values = r.split(',')
             for k in columns:
                 d[k] = values[i].replace(
                     r'\054',
                     ',')  # kk convert octal coded comma to real comma
                 i += 1
             self.rowsDict.append(d)
         else:
             msg = "Data inconsistent: number of commas = %s in line: %s in file: %s" % (
                 r.count(','), line, self.dataFile)
             dlg = dialog.alertDialog(self, msg,
                                      '%s inconsistent' % self.dataFile)
             self.close()
     self.components.companyList.insertItems(self.getCompanyList(), 0)
     self.components.sortBy.stringSelection = self.parser.get(
         'ConfigData', 'sortBy')
     self.showSelected()
Пример #20
0
 def on_menuHelpHelp_select(self, event):
     try:
         f = open('_READ_ME_FIRST.txt', "r")
         msg = f.read()
         result = dialog.scrolledMessageDialog(self, msg, 'readme.txt')
     except:
         result = dialog.alertDialog(self, 'Help file missing', 'Problem with the Help file')
Пример #21
0
 def on_initialize(self, event):
     if not FOUND_SOAP:
         # alert user, then exit cleanly
         result = dialog.alertDialog(
             self, "Can't find SOAP.py module, exiting application...",
             'Error: Missing module')
         self.close()
    def GetOutputFileBaseName(self):
        """Get base name of the corpus files

        @expr: variable containing the base name of the output files
        @wildcard: list of wildcards used in the dialog window to filter types of files
        @result: object returned by the Open File dialog window with attributes accepted (true if user clicked OK button, false otherwise) and
            path (list of strings containing the full pathnames to all files selected by the user)
        @self.inputdir: directory where TMX files to be processed are (and where output files will be written)
        @location: variable containing the full path to the base name output file
        @self.outputpath: base directory of output files
        @self.outputfile: base name of the output files
        """
        
        # Default base name of the corpora files that will be produced. If you choose as base name "Corpus.txt", as starting language "EN-GB" and as destination
        # language "FR-FR" the corpora files will be named "Corpus_EN-GB.txt" and "Corpus_FR-FR.txt"
        expr='Corpus'
        #open a dialog that lets you choose the base name of the corpora files that will be produced. 
        wildcard = "Text files (*.txt;*.TXT)|*.txt;*.TXT"
        result = dialog.openFileDialog(None, "Name of corpus file", self.inputdir,expr,wildcard=wildcard)
        if result.accepted:
            location=os.path.split(result.paths[0])
            self.outputpath=location[0]
            self.outputfile = location[1]
            if not os.path.exists(self.outputpath+'\\_processing_info'):
                try:
                    os.mkdir(self.outputpath+'\\_processing_info')
                except:
                    result1 = dialog.alertDialog(self, "The program can't create the directory " + self.outputpath+r'\_processing_info, which is necessary for ' + \
                        'the creation of the output files. The program will now close.','Error')
                    sys.exit()
Пример #23
0
    def on_Undo_command(self, event):
        # if we are at the end - i.e. no redo info yet, then we should take a snapshot
        #  right now so that we can get back to this point
        if len(self.redo) == 0:
            self.saveUndoPosition()
            st = self.undo[-1]
            self.redo.append(st)
            del self.undo[-1]
            
##        print "undo", len(self.undo), len(self.redo)
        if len(self.undo) == 0:
            result = dialog.alertDialog(self, 'No more to Undo', 'Undo Alert')
            return
        st = self.undo[-1]
##        for k,v in self.undo[-1].iteritems():
##            print k, v.state, v.values
        for i in range(9):
            for j in range(9):
                sqr = self.squares[i,j]
                sqr.values = copy.copy(st[i,j].values)
                sqr.state = st[i,j].state
                self.updateList(sqr)
                
        self.redo.append(st)
        del self.undo[-1]
        t = self.count()
        self.statusBar.text = "Possible choices left %d" % t
Пример #24
0
    def GetOutputFileBaseName(self):
        """Get base name of the corpus files

        @expr: variable containing the base name of the output files
        @wildcard: list of wildcards used in the dialog window to filter types of files
        @result: object returned by the Open File dialog window with attributes accepted (true if user clicked OK button, false otherwise) and
            path (list of strings containing the full pathnames to all files selected by the user)
        @self.inputdir: directory where TMX files to be processed are (and where output files will be written)
        @location: variable containing the full path to the base name output file
        @self.outputpath: base directory of output files
        @self.outputfile: base name of the output files
        """

        # Default base name of the corpora files that will be produced. If you choose as base name "Corpus.txt", as starting language "EN-GB" and as destination
        # language "FR-FR" the corpora files will be named "Corpus_EN-GB.txt" and "Corpus_FR-FR.txt"
        expr = 'Corpus'
        #open a dialog that lets you choose the base name of the corpora files that will be produced.
        wildcard = "Text files (*.txt;*.TXT)|*.txt;*.TXT"
        result = dialog.openFileDialog(None,
                                       "Name of corpus file",
                                       self.inputdir,
                                       expr,
                                       wildcard=wildcard)
        if result.accepted:
            location = os.path.split(result.paths[0])
            self.outputpath = location[0]
            self.outputfile = location[1]
            if not os.path.exists(self.outputpath + '\\_processing_info'):
                try:
                    os.mkdir(self.outputpath + '\\_processing_info')
                except:
                    result1 = dialog.alertDialog(self, "The program can't create the directory " + self.outputpath+r'\_processing_info, which is necessary for ' + \
                        'the creation of the output files. The program will now close.','Error')
                    sys.exit()
Пример #25
0
 def on_btnGuessLetter_mouseClick(self, event):
     result = dialog.textEntryDialog(self, 
       'enter the letter here:', 'Hangman', '')
     guess = result.text
     if len(guess) == 1:
         self.components.stYourGuesses.text = \
           self.components.stYourGuesses.text + "  " + guess + " "
         if result.text in self.currentword:
             locations = find_letters(guess, self.currentword)
             self.components.stDisplayWord.text = replace_letters \
               (self.components.stDisplayWord.text, locations, guess)
             if self.components.stDisplayWord.text.find('-') == -1:
                 dialog.alertDialog(self, 'You win!!!!!', 'Hangman')
                 self.new_game()
         else:
             self.wrong_guess()
     else:
         dialog.alertDialog(self, 'Type one letter only', 'Hangman')
Пример #26
0
 def on_btnGuessLetter_mouseClick(self, event):
     result = dialog.textEntryDialog(self, 'enter the letter here:',
                                     'Hangman', '')
     guess = result.text
     if len(guess) == 1:
         self.components.stYourGuesses.text = \
           self.components.stYourGuesses.text + "  " + guess + " "
         if result.text in self.currentword:
             locations = find_letters(guess, self.currentword)
             self.components.stDisplayWord.text = replace_letters \
               (self.components.stDisplayWord.text, locations, guess)
             if self.components.stDisplayWord.text.find('-') == -1:
                 dialog.alertDialog(self, 'You win!!!!!', 'Hangman')
                 self.new_game()
         else:
             self.wrong_guess()
     else:
         dialog.alertDialog(self, 'Type one letter only', 'Hangman')
 def on_filename_closeField(self, event=None):
     self.filename = self.components.filename.getLineText(0)
     try:
         isCorrectFilename(self.filename)
     except OutFileMustBeh5Extention:
         dialog.alertDialog(
             self,
             "The filename ({0}) must be specified with an '.h5' extension.".format(self.filename),
             "Check you filename",
         )
         return
     except OutFileMustBeAbsolutePath:
         dialog.alertDialog(
             self, "The filename ({0}) must be an absolute path.".format(self.filename), "Check you filename"
         )
         return
     self.title = os.path.split(self.filename)[-1] + " - " + self.startTitle
     self.statusBar.text = self.filename
     self._updateRunList()
Пример #28
0
 def on_btnOK_mouseClick(self, event):
     if self.components.buildTool.stringSelection == 'pyInstaller':
         if self.components.installerPath.text == '':
             title = 'Preferences not saved!'
             txt = 'You must specify the directory where the pyInstaller components can be found'
             bull = dialog.alertDialog(self, wrap_string(txt, 60), title)
             return
     if self.components.compilerPath.text == '' and sys.platform.startswith(
             'win'):
         title = 'Preferences not saved!'
         txt = 'You must specify the directory where the Inno Setup compiler can be found'
         bull = dialog.alertDialog(self, wrap_string(txt, 60), title)
         return
     if self.components.projectsPath.text == '':
         title = 'Preferences not saved!'
         txt = 'You must specify your base projects directory'
         bull = dialog.alertDialog(self, wrap_string(txt, 60), title)
         return
     self.parent.cfg.set('ConfigData', 'reseditor',
                         self.components.resEditPath.text)
     self.parent.cfg.set('ConfigData', 'codeeditor',
                         self.components.srcEditPath.text)
     self.parent.cfg.set('ConfigData', 'texteditor',
                         self.components.txtEditPath.text)
     self.parent.cfg.set('ConfigData', 'pixmapeditor',
                         self.components.pixmapEditPath.text)
     self.parent.cfg.set('ConfigData', 'installerpath',
                         self.components.installerPath.text)
     self.parent.cfg.set('ConfigData', 'buildtool',
                         self.components.buildTool.stringSelection)
     self.parent.cfg.set('ConfigData', 'compilerpath',
                         self.components.compilerPath.text)
     self.parent.cfg.set('ConfigData', 'publisher',
                         self.components.appPublisher.text)
     self.parent.cfg.set('ConfigData', 'projects',
                         self.components.projectsPath.text)
     fd = open(self.CONFIG_FILE, 'w')
     self.parent.cfg.write(fd)
     fd.close()
     event.Skip()
Пример #29
0
    def on_initialize(self, event):
        """Initialize values

        
        @self.inputdir: directory whose files will be treated
        @self.outputfile: base name of the resulting corpora files
        @self.outputpath: root directory of the resulting corpora files
        @currdir: program's current working directory
        @self.languages: list of languages whose segments can be processed
        @self.startinglanguage: something like 'EN-GB'
        @self.destinationlanguage: something like 'FR-FR'
        @self.components.cbStartingLanguage.items: list of values of the Starting Language combobox of the program's window
        @self.components.cbDestinationLanguage.items: list of values of the Destination Language combobox of the program's window
        @self.numtus: number of translation units extracted so far
        @self.presentfile: TMX file being currently processed
        @self.errortypes: variable that stocks the types of errors detected in the TMX file that is being processed
        @self.wroteactions: variable that indicates whether the actions files has already been written to
        """

        self.inputdir = ''
        self.outputfile = ''
        self.outputpath = ''
        #Get directory where program file is and ...
        currdir = os.getcwd()
        #... load the file ("LanguageCodes.txt") with the list of languages that the program can process
        try:
            self.languages = open(currdir + r'\LanguageCodes.txt',
                                  'r+').readlines()
        except:
            # If the languages file doesn't exist in the program directory, alert user that it is essential for the good working of the program and exit
            result = dialog.alertDialog(
                self,
                'The file "LanguageCodes.txt" is missing. The program will now close.',
                'Essential file missing')
            sys.exit()
        #remove end of line marker from each line in "LanguageCodes.txt"
        for lang in range(len(self.languages)):
            self.languages[lang] = self.languages[lang].rstrip()
        self.startinglanguage = ''
        self.destinationlanguage = ''
        #Insert list of language names in appropriate program window's combo boxes
        self.components.cbStartingLanguage.items = self.languages
        self.components.cbDestinationLanguage.items = self.languages
        self.tottus = 0
        self.numtus = 0
        self.numequaltus = 0
        self.presentfile = ''
        self.errortypes = ''
        self.wroteactions = False
        self.errors = ''
Пример #30
0
 def on_buildTool_select(self, event):
     if self.components.buildTool.stringSelection == 'py2exe':
         try:
             from distutils.core import setup as wibble
         except ImportError:
             title = '*** ERROR ***'
             txt = 'You do not appear to have a copy of the distutils '
             txt += 'package installed. This is required in order to allow '
             txt += 'building with py2exe.'
             bull = dialog.alertDialog(self, wrap_string(txt, 60), title)
             self.components.buildTool.stringSelection = 'pyInstaller'
         else:
             try:
                 import py2exe as wibble
             except ImportError:
                 title = '*** ERROR ***'
                 txt = 'You do not appear to have a '
                 txt += 'copy of the py2exe package installed. Please install '
                 txt += 'the package and then re-configure your preferences.'
                 bull = dialog.alertDialog(self, wrap_string(txt, 60),
                                           title)
                 self.components.buildTool.stringSelection = 'pyInstaller'
             else:
                 self.components.installerPath.text = ''
                 self.components.installerPath.enabled = False
                 self.components.installerPathBtn.enabled = False
                 self.components.installerPathHelpBtn.enabled = False
     else:
         self.components.installerPath.enabled = True
         self.components.installerPathBtn.enabled = True
         self.components.installerPathHelpBtn.enabled = True
         # see if we can find pyInstaller
         # C:\Python23\pyInstaller\Build.py
         want = os.path.join('pyInstaller', 'Build.py')
         installer = self.parent.lookFor(want)
         #self.parent.cfg.set('ConfigData', 'installerpath', installer)
         self.components.installerPath.text = installer
Пример #31
0
 def createTMXs(self):
     try:
         # Get a list of all TMX files that need to be processed
         fileslist=self.locate('*.moses',self.inputdir)
     except:
         # if any error up to now, add the name of the TMX file to the output file @errors
         self.errortypes=self.errortypes+'   - Get All Segments: creation of output files error\n'
     if fileslist:
         # For each relevant TMX file ...
         for self.presentfile in fileslist:
             filename=self.presentfile[:-9]
             #print filename
             self.CreateTMX(filename)
     print 'Finished at '+strftime('%H-%M-%S')
     result = dialog.alertDialog(self, 'Processing done.', 'Processing Done')
Пример #32
0
 def wrong_guess(self):
     dialog.alertDialog(self, "WRONG!!!", 'Hangman')
     if self.components.head.visible == True:
         if self.components.body.visible == True:
             if self.components.arm1.visible == True:
                 if self.components.arm2.visible == True:
                     if self.components.foot1.visible == True:
                         if self.components.foot2.visible == True:
                             dialog.alertDialog(self, 
                               "You lost! Word was "+self.currentword, 
                               'Hangman')
                             self.new_game()
                         else:
                             self.components.foot2.visible = True
                     else:
                         self.components.foot1.visible = True
                 else:
                     self.components.arm2.visible = True
             else:
                 self.components.arm1.visible = True
         else:
             self.components.body.visible = True
     else:
         self.components.head.visible = True
Пример #33
0
 def createTMXs(self):
     try:
         # Get a list of all TMX files that need to be processed
         fileslist = self.locate('*.moses', self.inputdir)
     except:
         # if any error up to now, add the name of the TMX file to the output file @errors
         self.errortypes = self.errortypes + '   - Get All Segments: creation of output files error\n'
     if fileslist:
         # For each relevant TMX file ...
         for self.presentfile in fileslist:
             filename = self.presentfile[:-9]
             #print filename
             self.CreateTMX(filename)
     print 'Finished at ' + strftime('%H-%M-%S')
     result = dialog.alertDialog(self, 'Processing done.',
                                 'Processing Done')
    def on_initialize(self, event):
        """Initialize values

        
        @self.inputdir: directory whose files will be treated
        @self.outputfile: base name of the resulting corpora files
        @self.outputpath: root directory of the resulting corpora files
        @currdir: program's current working directory
        @self.languages: list of languages whose segments can be processed
        @self.startinglanguage: something like 'EN-GB'
        @self.destinationlanguage: something like 'FR-FR'
        @self.components.cbStartingLanguage.items: list of values of the Starting Language combobox of the program's window
        @self.components.cbDestinationLanguage.items: list of values of the Destination Language combobox of the program's window
        @self.numtus: number of translation units extracted so far
        @self.presentfile: TMX file being currently processed
        @self.errortypes: variable that stocks the types of errors detected in the TMX file that is being processed
        @self.wroteactions: variable that indicates whether the actions files has already been written to
        """
        
        self.inputdir=''
        self.outputfile=''
        self.outputpath=''
        #Get directory where program file is and ...
        currdir=os.getcwd()
        #... load the file ("LanguageCodes.txt") with the list of languages that the program can process
        try:
            self.languages=open(currdir+r'\LanguageCodes.txt','r+').readlines()
        except:
            # If the languages file doesn't exist in the program directory, alert user that it is essential for the good working of the program and exit
            result = dialog.alertDialog(self, 'The file "LanguageCodes.txt" is missing. The program will now close.', 'Essential file missing')
            sys.exit()
        #remove end of line marker from each line in "LanguageCodes.txt"
        for lang in range(len(self.languages)):
            self.languages[lang]=self.languages[lang].rstrip()
        self.startinglanguage=''
        self.destinationlanguage=''
        #Insert list of language names in appropriate program window's combo boxes
        self.components.cbStartingLanguage.items=self.languages
        self.components.cbDestinationLanguage.items=self.languages
        self.tottus=0
        self.numtus=0
        self.numequaltus=0
        self.presentfile=''
        self.errortypes=''
        self.wroteactions=False
        self.errors=''
Пример #35
0
    def on_Redo_command(self, event):
##        print "redo", len(self.undo), len(self.redo)
        if len(self.redo) == 0:
            result = dialog.alertDialog(self, 'No more to Redo', 'Redo Alert')
            return
        st = self.redo[-1]
        for i in range(9):
            for j in range(9):
                sqr = self.squares[i,j]
                sqr.values = copy.copy(st[i,j].values)
                sqr.state = st[i,j].state
                self.updateList(sqr)
                
        self.undo.append(st)
        del self.redo[-1]
        t = self.count()
        self.statusBar.text = "Possible choices left %d" % t
Пример #36
0
 def on_initialize(self, event):
     self.inputdir=''
     #Get directory where program file is and ...
     currdir=os.path.abspath(os.path.dirname(os.path.realpath(sys.argv[0])))
     #... load the file ("LanguageCodes.txt") with the list of languages that the program can process
     try:
         self.languages=open(currdir+os.sep+r'LanguageCodes.txt','r+').readlines()
     except:
         # If the languages file doesn't exist in the program directory, alert user that it is essential for the good working of the program and exit
         result = dialog.alertDialog(self, 'The file "LanguageCodes.txt" is missing. The program will now close.', 'Essential file missing')
         sys.exit()
     #remove end of line marker from each line in "LanguageCodes.txt"
     for lang in range(len(self.languages)):
         self.languages[lang]=self.languages[lang].rstrip()
     self.lang1code=''
     self.lang2code=''
     #Insert list of language names in appropriate program window's combo boxes
     self.components.cbStartingLanguage.items=self.languages
     self.components.cbDestinationLanguage.items=self.languages
Пример #37
0
 def on_baseDirBtn_mouseClick(self, event):
     title = 'Select project base directory'
     basepath = str(self.parent.cfg.get('ConfigData', 'projects'))
     result = dialog.directoryDialog(self, title, basepath,
                                     wx.DD_NEW_DIR_BUTTON)
     if result.accepted:
         # need an error here if the directory selected is not a subdirectory
         # of basepath...
         plist = []
         plist.append(basepath)
         plist.append(str(result.path))
         if os.path.commonprefix(plist) != basepath:
             title = 'Invalid project base directory'
             txt = 'This version of standaloneBuilder does not allow creation '
             txt += 'of projects which reside outside of the projects directory '
             txt += 'specified in your preferences. This issue will be addressed '
             txt += 'in the next version. Yes, it\'s lame - sorry! :-('
             bull = dialog.alertDialog(self, wrap_string(txt, 60), title)
             self.components.baseDir.SetFocus()
         else:
             self.components.baseDir.text = result.path
             self.components.nextBtn.enabled = True
Пример #38
0
    def on_initialize(self, event):
        self.cfg = ConfigParser.ConfigParser()

        # first job is to see we have any config info
        if not os.path.exists(CONFIG_FILE):
            title = 'Initial setup'
            
            txt = 'Since this is the first time you have run PySSHed, you need to configure '
            txt += 'your default SSH preferences. Most users should find that the '
            txt += 'default settings are satisfactory. On this system, settings will be stored '
            txt += 'in "%s". Click OK to begin configuring PySSHed.' % CONFIG_FILE
            
            bull = dialog.alertDialog(self, customDialogs.wrap_string(txt, 70), title)
            
            self.cfg.add_section('Defaults')

            # set some (hopefully!) reasonable defaults
            self.cfg.set('Defaults', 'port', '22')
            if sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
                self.cfg.set('Defaults', 'user', pwd.getpwuid(os.getuid())[0])
                self.cfg.set('Defaults', 'identityfile', os.path.join(os.path.join(os.path.expanduser('~'), '.ssh'), 'identity'))
                self.cfg.set('Defaults', 'command', '/usr/X11R6/bin/xterm -e ssh')
            else: 
                self.cfg.set('Defaults', 'user', '')
                self.cfg.set('Defaults', 'identityfile', os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), 'identity'))
                self.cfg.set('Defaults', 'command', '"C:\\Program files\\putty\\putty.exe"')

            dlg = customDialogs.prefsDialog(self, 'Defaults')
            if dlg.ShowModal() == wx.ID_OK:
                fd = open(CONFIG_FILE, 'w')
                self.cfg.write(fd)
                fd.close()
            dlg.destroy()
            
        self.cfg.read(CONFIG_FILE)
        self.updateSessionList()
        if len(self.components.sessionList.items) > 0:
            self.components.sessionList.stringSelection = self.components.sessionList.items[0]
Пример #39
0
 def on_initialize(self, event):
     self.inputdir = ''
     #Get directory where program file is and ...
     currdir = os.getcwd()
     #... load the file ("LanguageCodes.txt") with the list of languages that the program can process
     try:
         self.languages = open(currdir + r'\LanguageCodes.txt',
                               'r+').readlines()
     except:
         # If the languages file doesn't exist in the program directory, alert user that it is essential for the good working of the program and exit
         result = dialog.alertDialog(
             self,
             'The file "LanguageCodes.txt" is missing. The program will now close.',
             'Essential file missing')
         sys.exit()
     #remove end of line marker from each line in "LanguageCodes.txt"
     for lang in range(len(self.languages)):
         self.languages[lang] = self.languages[lang].rstrip()
     self.lang1code = ''
     self.lang2code = ''
     #Insert list of language names in appropriate program window's combo boxes
     self.components.cbStartingLanguage.items = self.languages
     self.components.cbDestinationLanguage.items = self.languages
Пример #40
0
 def show_invalid(self):
     self.statusBar.text = 'invalid url'
     result = dialog.alertDialog(self, 'Invalid URL', 'Error')
Пример #41
0
    def updateComponent(self):
        wName, wClass = self.components.wComponentList.stringSelection.split(
            "  :  ")
        propName = self.components.wPropertyList.stringSelection

        if propName in self.checkItems:
            value = self.components.wChecked.checked
        elif propName in self.popItems:
            value = self.components.wPop.stringSelection
        elif propName in ('items', 'userdata') or (wClass == 'TextArea'
                                                   and propName == 'text'):
            value = self.components.wTextArea.text
        else:
            #value = self.components.wField.GetValue()
            value = self.components.wField.text

        if propName not in [
                'label', 'stringSelection', 'text', 'toolTip', 'userdata'
        ]:
            try:
                value = eval(value)
            except:
                pass

        # KEA 2004-05-10
        # need to figure out where to stick validation code
        # but for now just need to make sure that if we're changing the name
        # attribute that it is valid, but similar checks will be necessary for
        # integer fields, a list of items, etc.
        # also maybe each attribute should have a doc or help string displayed
        # saying what the attribute does, example values, etc.
        if propName == 'name':
            badValue = False
            # if it isn't valid then display an alert and exit
            # must start with a letter and only contain alphanumeric characters
            if value == "" or value[0] not in string.ascii_letters:
                badValue = True
            else:
                alphanumeric = string.ascii_letters + string.digits
                for c in value:
                    if c not in alphanumeric:
                        badValue = True
                        break
            if badValue:
                dialog.alertDialog(
                    None,
                    "Name must start with a letter and only contain letters and numbers.",
                    'Error: Name is invalid')
                self.components.wField.setFocus()
                self.components.wField.setSelection(-1, -1)
                return
            # check for duplicate names is done below

        ##widget = self.components[wName]
        widget = self._comp[wName]

        # KEA 2002-02-23
        # I can't remember why this is actually necessary
        if propName == 'size':
            width, height = value
            if wClass not in ['BitmapCanvas', 'HtmlWindow']:
                bestWidth, bestHeight = widget.GetBestSize()
                if width == -1:
                    width = bestWidth
                if height == -1:
                    height = bestHeight
            widget.size = (width, height)
            #setattr(widget, propName, (width, height))
            #print widget.size, propName, width, height
        else:
            if (propName in self.cantModify) or \
               (propName == 'items' and wClass == 'RadioGroup'):
                order = self._comp.order.index(wName)
                desc = resourceOutput.widgetAttributes(self._parent, widget)
                if desc.endswith(',\n'):
                    desc = eval(desc[:-2])
                else:
                    desc = eval(desc)

                if propName == 'name':
                    if value == wName:
                        # user didn't actually change the name
                        return
                    elif value in self._comp:
                        # we already have a component with that name
                        dialog.alertDialog(
                            self,
                            'Another component already exists with the name ' +
                            value, 'Error: unable to rename component')
                        return
                if value is None:
                    desc[propName] = 'none'
                elif propName in ['min', 'max']:
                    desc[propName] = int(value)
                else:
                    desc[propName] = value

                # need to experiment with freeze and thaw to avoid
                # a lot of update events
                startTime = time.time()

                # this is going to trigger a changed event
                # as we delete the old component
                self._updatingComponent = True
                del self._comp[wName]
                if propName == 'name':
                    wName = value
                # this is going to trigger another changed event
                # as we create a new component with the changed attribute
                self._comp[wName] = desc
                c = self._comp[wName]
                wx.EVT_LEFT_DOWN(c, self._parent.on_mouseDown)
                wx.EVT_LEFT_UP(c, self._parent.on_mouseUp)
                wx.EVT_MOTION(c, self._parent.on_mouseDrag)

                # now restore the order of the component
                # have to update the startName in case the name was updated
                if propName == 'name':
                    self._parent.startName = wName
                self._comp.order.remove(wName)
                self._comp.order.insert(order, wName)

                self._parent.fixComponentOrder(wName)

                self._updatingComponent = False

                endTime = time.time()
                #print "attribute change took:", endTime - startTime
            else:
                if wClass in ['Image', 'ImageButton'] and propName == 'file':
                    cwd = os.getcwd()
                    try:
                        os.chdir(self._parent.filename)
                    except:
                        pass
                    setattr(widget, propName, value)
                    os.chdir(cwd)
                else:
                    setattr(widget, propName, value)
                    #print propName, value
        # KEA 2002-02-23
        self._parent.showSizingHandles(wName)
Пример #42
0
    def on_compileStatsButton_mouseClick(self, event):
        #exports compiled stats as a CSV
        playerDict = dict()
        printed = ""
        wildcard = "csv Files (*.csv)|*.csv"
        result = dialog.fileDialog(self,
                                   'Open',
                                   "",
                                   '',
                                   wildcard )
        games = result.paths
        if not(result.accepted):
            return
        for i in range(0,len(games)):
            f = open(os.path.abspath(games[i]),'r')
            try:
                lines = f.readlines()
                lines = lines[2:]
                for j in range(0,len(lines)):
                    line = lines[j].strip('\n').split(",")
                    if (line[0] in playerDict.keys()):
                        for s in range(2,10):
                            playerDict[line[0]][s] = str(int(playerDict[line[0]][s])+int(line[s]))
                    else:
                        playerDict[line[0]] = line
            finally:
                f.close()
        for key in playerDict.keys():
            playerDict[key].insert(3,str(float(playerDict[key][2])/len(games)))#goals per game
            playerDict[key].insert(5,str(float(playerDict[key][4])/len(games)))#assists per game
            playerDict[key].insert(7,str(float(playerDict[key][6])/len(games)))#shots per game
            playerDict[key].insert(9,str(float(playerDict[key][8])/len(games)))#groundballs per game
        playerNames = sorted(playerDict.keys())#sorts the keys (names of the players) so the stats can be printed in order
        printed = 'Player, Number, Total Goals, Goals per Game, Total Assists, Assists per Game, Total Shots, Shots per Game, Total Groundballs, Groundballs per Game, Total Faceoffs Won, Total Faceoffs Lost, Total Saves, Total Minutes\n'
        for k in range(0,len(playerNames)):
            printed += ','.join(playerDict[playerNames[k]])+"\n"
        result = dialog.alertDialog(self,
                                              'Statistics were saved to the compiled statistics folder.',
                                              "Compiled Statistics")

        #WRITING COMPILED STATS FILE
        v = 1 #Initialize VERSION Constant
        #Checks if file already exists
        saveDirectory = self.gameStats+"/Compiled_Stats"
        if not(os.path.exists(saveDirectory)):
               os.makedirs(saveDirectory)
        if(os.path.isfile(os.path.abspath(saveDirectory+'/Compiled Stats.csv'))):
            while(os.path.isfile(os.path.abspath(saveDirectory+'/Compiled Stats'+str(v)+'.csv'))):
                v=v+1
            filename = saveDirectory+'/Compiled Stats'+str(v)+'.csv'
            
            #creates v1,v2,etc file
            f = open(os.path.abspath(filename),'w')
            try:
                f.write(printed)
            finally:
                f.close()
        #else creates file
        else:
            f = open(os.path.abspath(saveDirectory+'/Compiled Stats.csv'),'w')
            try:
                f.write(printed)

            finally:
                f.close()
Пример #43
0
    def on_menuHelpAbout_select(self,event):
	result = dialog.alertDialog(self, 'Hafuch Al Hafuch \n \n Shavit Ilan\n    Ver 0.1', 'About: Hafuch Al Hafuch')
    def ExtractCorpus(self):
        """Get the directory where TMX files to be processed are, get the choice of the pair of languages that will be treated and launch the extraction
        of the corpus

        @self.errortypes: variable that stocks the types of errors detected in the TMX file that is being processed
        @self.presentfile: TMX file being currently processed
        @self.numtus: number of translation units extracted so far
        @self.startinglanguage: something like 'EN-GB'
        @self.destinationlanguage: something like 'FR-FR'
        @self.inputdir: directory whose files will be treated
        @self.components.cbStartingLanguage.items: list of values of the Starting Language combobox of the program's window
        @self.components.cbDestinationLanguage.items: list of values of the Destination Language combobox of the program's window
        @self.outputfile: base name of the resulting corpora files
        @self.errors:output file indicating the types of error that occurred in each processed TMX file
        @self.numtus: number of translation units extracted so far
        """

        print 'Extract corpus: started at '+strftime('%H-%M-%S')
        self.errortypes=''
        self.presentfile=''
        self.numtus=0
        #get the startinglanguage name (e.g.: "EN-GB") from the program window
        self.startinglanguage=self.components.cbStartingLanguage.text
        #get the destinationlanguage name from the program window
        self.destinationlanguage=self.components.cbDestinationLanguage.text
        #if the directory where TMX files (@inputdir) or the pair of languages were not previously chosen, open a dialog box explaining
        #the conditions that have to be met so that the extraction can be made and do nothing...
        if (self.inputdir=='') or (self.components.cbStartingLanguage.text=='') or (self.components.cbDestinationLanguage.text=='') or (self.outputfile=='') \
           or (self.components.cbStartingLanguage.text==self.components.cbDestinationLanguage.text):
            result = dialog.alertDialog(self, 'In order to extract a corpus, you need to:\n\n 1) indicate the directory where the TMX files are,\n 2)' \
                        +' the starting language,\n 3) the destination language (the 2 languages must be different), and\n 4) the base name of the output files.', 'Error')
        
        #...else, go ahead
        else:
            try:
                self.errors=open(self.outputpath+'\\_processing_info\\'+self.startinglanguage+ '-'+self.destinationlanguage+'_'+'errors_'+self.outputfile+'.txt','w+')
            except:
                pass
            self.statusBar.text='Please wait. This can be a long process ...'
            #Launch the segment extraction
            self.numtus=0
            self.getallsegments()
            # if any error up to now, add the name of the TMX file to the output file @errors
            if self.errortypes:
                try:
                    self.errors.write(self.presentfile.encode('utf_8','replace')+':\n'+self.errortypes)
                except:
                    pass
            try:
                self.errors.close()
            except:
                pass
            self.statusBar.text='Processing finished.'
            #Open dialog box telling that processing is finished and where can the resulting files be found
            self.inputdir=''
            self.outputfile=''
            self.outputpath=''
            print 'Extract corpus: finished at '+strftime('%H-%M-%S')
            result = dialog.alertDialog(self, 'Processing done. Results found in:\n\n1) '+ \
                self.outputpath+'\\'+self.startinglanguage+  ' ('+self.destinationlanguage+')_' +self.outputfile+ ' (starting language corpus)\n2) '+ \
                self.outputpath+'\\'+self.destinationlanguage+' ('+self.startinglanguage+')_'+self.outputfile+ \
                ' (destination language corpus)\n3) '+self.outputpath+'\\_processing_info\\'+self.startinglanguage+ '-'+self.destinationlanguage+'_'+ \
                'errors_'+self.outputfile+'.txt'+ ' (list of files that caused errors)\n4) '+self.outputpath+'\\_processing_info\\'+self.startinglanguage+ \
                '-'+self.destinationlanguage+'_'+'actions_'+self.outputfile+'.txt'+ ' (list of files where processing was successful)', 'Processing Done')
    def ExtractAllCorpora(self):
        """Extracts all the LanguagePairs that can be composed with the languages indicated in the file "LanguageCodes.txt"

        @self.presentfile: TMX file being currently processed
        @self.numtus: number of translation units extracted so far
        @numcorpora: number of language pair being processed
        @self.inputdir: directory whose files will be treated
        @self.outputfile: base name of the resulting corpora files
        @self.errors:output file indicating the types of error that occurred in each processed TMX file
        @self.startinglanguage: something like 'EN-GB'
        @self.destinationlanguage: something like 'FR-FR'
        @lang1: code of the starting language
        @lang2: code of the destination language
        @self.errortypes: variable that stocks the types of errors detected in the TMX file that is being processed
        @self.wroteactions: variable that indicates whether the actions files has already been written to
        """
        
        print 'Extract All Corpora: started at '+strftime('%H-%M-%S')
        self.presentfile=''
        self.numtus=0
        numcorpora=0
        #if the directory where TMX files (@inputdir) or the base name of the output files were not previously chosen, open a dialog box explaining
        #the conditions that have to be met so that the extraction can be made and do nothing...
        if (self.inputdir=='') or (self.outputfile==''):
            result = dialog.alertDialog(self, 'In order to extract all corpora, you need to:\n\n 1) indicate the directory where the TMX files are, and\n ' \
                                        + '2) the base name of the output files.', 'Error')
        #...else, go ahead
        else:
            try:
                for lang1 in self.languages:
                    for lang2 in self.languages:
                        if lang2 > lang1:
                            print lang1+'/'+lang2+' corpus being created...'
                            numcorpora=numcorpora+1
                            self.errortypes=''
                            self.numtus=0
                            self.wroteactions=False
                            #get the startinglanguage name (e.g.: "EN-GB") from the program window
                            self.startinglanguage=lang1
                            #get the destinationlanguage name from the program window
                            self.destinationlanguage=lang2
                            try:
                                self.errors=open(self.outputpath+'\\_processing_info\\'+self.startinglanguage+ '-'+self.destinationlanguage+'_'+'errors.txt','w+')
                            except:
                                pass
                            self.statusBar.text='Language pair '+str(numcorpora)+' being processed. Please wait.'
                            #Launch the segment extraction
                            self.getallsegments()
                            # if any error up to now, add the name of the TMX file to the output file @errors
                            if self.errortypes:
                                try:
                                    self.errors.write(self.presentfile.encode('utf_8','replace')+':\n'+self.errortypes.encode('utf_8','replace'))
                                except:
                                    pass
                            try:
                                self.errors.close()
                            except:
                                pass
                self.statusBar.text='Processing finished.'
            except:
                self.errortypes=self.errortypes+'   - Extract All Corpora error\n'
                self.errors.write(self.presentfile.encode('utf_8','replace')+':\n'+self.errortypes.encode('utf_8','replace'))
                self.errors.close()
            #Open dialog box telling that processing is finished and where can the resulting files be found
            self.inputdir=''
            self.outputfile=''
            self.outputpath=''
            print 'Extract All Corpora: finished at '+strftime('%H-%M-%S')
            result = dialog.alertDialog(self, 'Results found in: '+ self.outputpath+'.', 'Processing done')
Пример #46
0
 def showAlert(self, aMessage, aTitle):
     "Show Alert dialog with aMessage and aTitle"
     dialog.alertDialog(self, aMessage, aTitle)
    def ExtractSomeCorpora(self):
        """Extracts the segments of the LanguagePairs indicated in the file "LanguagePairs.txt" located in the program's root directory

        @self.presentfile: TMX file being currently processed
        @self.numtus: number of translation units extracted so far
        @currdir: current working directory of the program
        @pairsoflanguages: list of the pairs of language that are going to be processed
        @self.languages: list of languages whose segments can be processed
        @numcorpora: number of language pair being processed
        @self.inputdir: directory whose files will be treated
        @self.outputfile: base name of the resulting corpora files
        @self.errors:output file indicating the types of error that occurred in each processed TMX file
        @self.startinglanguage: something like 'EN-GB'
        @self.destinationlanguage: something like 'FR-FR'
        @lang1: code of the starting language
        @lang2: code of the destination language
        @self.errortypes: variable that stocks the types of errors detected in the TMX file that is being processed
        @self.wroteactions: variable that indicates whether the actions files has already been written to
        """
        
        print 'Extract Some Corpora: started at '+strftime('%H-%M-%S')
        self.presentfile=''
        self.numtus=0
        currdir=os.getcwd()
        #... load the file ("LanguageCodes.txt") with the list of languages that the program can process
        try:
            pairsoflanguages=open(currdir+r'\LanguagePairs.txt','r+').readlines()
        except:
            # If the languages file doesn't exist in the program directory, alert user that it is essential for the good working of the program and exit
            result = dialog.alertDialog(self, 'The file "LanguagePairs.txt" is missing. The program will now close.', 'Essential file missing')
            sys.exit()
        #remove end of line marker from each line in "LanguageCodes.txt"
        if pairsoflanguages:
            for item in range(len(pairsoflanguages)):
                pairsoflanguages[item]=pairsoflanguages[item].strip()
                pos=pairsoflanguages[item].find("/")
                pairsoflanguages[item]=(pairsoflanguages[item][:pos],pairsoflanguages[item][pos+1:])
        else:
            # If the languages file is empty, alert user that it is essential for the good working of the program and exit
            result = dialog.alertDialog(self, 'The file "LanguagePairs.txt" is an essential file and is empty. The program will now close.', 'Empty file')
            sys.exit()
            
        #if the directory where TMX files (@inputdir) or the base name of the output files were not previously chosen, open a dialog box explaining
        #the conditions that have to be met so that the extraction can be made and do nothing...
        if (self.inputdir=='') or (self.outputfile==''):
            result = dialog.alertDialog(self, 'In order to extract all corpora, you need to:\n\n 1) indicate the directory where the TMX files are, and\n ' \
                                        + '2) the base name of the output files.', 'Error')
        #...else, go ahead
        else:
            numcorpora=0
            for (lang1,lang2) in pairsoflanguages:
                if lang1<>lang2:
                    print lang1+'/'+lang2+' corpus being created...'
                    self.errortypes=''
                    numcorpora=numcorpora+1
                    #get the startinglanguage code (e.g.: "EN-GB") 
                    self.startinglanguage=lang1
                    #get the destinationlanguage code 
                    self.destinationlanguage=lang2
                    try:
                        self.errors=open(self.outputpath+'\\_processing_info\\'+self.startinglanguage+ '-'+self.destinationlanguage+'_'+'errors.txt','w+')
                    except:
                        pass
                    self.statusBar.text='Language pair '+str(numcorpora)+' being processed. Please wait.'
                    #Launch the segment extraction
                    self.numtus=0
                    self.wroteactions=False
                    self.getallsegments()
                    # if any error up to now, add the name of the TMX file to the output file @errors
                    if self.errortypes:
                        try:
                            self.errors.write(self.presentfile.encode('utf_8','replace')+':\n'+self.errortypes.encode('utf_8','replace'))
                        except:
                            pass
                    try:
                        self.errors.close()
                    except:
                        pass
                else:
                    result = dialog.alertDialog(self, 'A bilingual corpus involves two different languages. The pair "'+lang1+'/'+lang2 + \
                            '" will not be processed.', 'Alert')
                self.statusBar.text='Processing finished.'
            #Open dialog box telling that processing is finished and where can the resulting files be found
            self.inputdir=''
            self.outputfile=''
            self.outputpath=''
            print 'Extract Some Corpora: finished at '+strftime('%H-%M-%S')
            result = dialog.alertDialog(self, 'Results found in: '+ self.outputpath+'.', 'Processing done')
Пример #48
0
	def __add_msg( self, msg, plus_pop = False ):
		if plus_pop:
			dialog.alertDialog( self, msg, Const[ "WARNING" ] )
		self.components.TextAreaLog.appendText( msg + "\n" )
Пример #49
0
    def ExtractAllCorpora(self):
        """Extracts all the LanguagePairs that can be composed with the languages indicated in the file "LanguageCodes.txt"

        @self.presentfile: TMX file being currently processed
        @self.numtus: number of translation units extracted so far
        @numcorpora: number of language pair being processed
        @self.inputdir: directory whose files will be treated
        @self.outputfile: base name of the resulting corpora files
        @self.errors:output file indicating the types of error that occurred in each processed TMX file
        @self.startinglanguage: something like 'EN-GB'
        @self.destinationlanguage: something like 'FR-FR'
        @lang1: code of the starting language
        @lang2: code of the destination language
        @self.errortypes: variable that stocks the types of errors detected in the TMX file that is being processed
        @self.wroteactions: variable that indicates whether the actions files has already been written to
        """

        print 'Extract All Corpora: started at ' + strftime('%H-%M-%S')
        self.presentfile = ''
        self.numtus = 0
        numcorpora = 0
        #if the directory where TMX files (@inputdir) or the base name of the output files were not previously chosen, open a dialog box explaining
        #the conditions that have to be met so that the extraction can be made and do nothing...
        if (self.inputdir == '') or (self.outputfile == ''):
            result = dialog.alertDialog(self, 'In order to extract all corpora, you need to:\n\n 1) indicate the directory where the TMX files are, and\n ' \
                                        + '2) the base name of the output files.', 'Error')
        #...else, go ahead
        else:
            try:
                for lang1 in self.languages:
                    for lang2 in self.languages:
                        if lang2 > lang1:
                            print lang1 + '/' + lang2 + ' corpus being created...'
                            numcorpora = numcorpora + 1
                            self.errortypes = ''
                            self.numtus = 0
                            self.wroteactions = False
                            #get the startinglanguage name (e.g.: "EN-GB") from the program window
                            self.startinglanguage = lang1
                            #get the destinationlanguage name from the program window
                            self.destinationlanguage = lang2
                            try:
                                self.errors = open(
                                    self.outputpath + '\\_processing_info\\' +
                                    self.startinglanguage + '-' +
                                    self.destinationlanguage + '_' +
                                    'errors.txt', 'w+')
                            except:
                                pass
                            self.statusBar.text = 'Language pair ' + str(
                                numcorpora) + ' being processed. Please wait.'
                            #Launch the segment extraction
                            self.getallsegments()
                            # if any error up to now, add the name of the TMX file to the output file @errors
                            if self.errortypes:
                                try:
                                    self.errors.write(
                                        self.presentfile.encode(
                                            'utf_8', 'replace') + ':\n' +
                                        self.errortypes.encode(
                                            'utf_8', 'replace'))
                                except:
                                    pass
                            try:
                                self.errors.close()
                            except:
                                pass
                self.statusBar.text = 'Processing finished.'
            except:
                self.errortypes = self.errortypes + '   - Extract All Corpora error\n'
                self.errors.write(
                    self.presentfile.encode('utf_8', 'replace') + ':\n' +
                    self.errortypes.encode('utf_8', 'replace'))
                self.errors.close()
            #Open dialog box telling that processing is finished and where can the resulting files be found
            self.inputdir = ''
            self.outputfile = ''
            self.outputpath = ''
            print 'Extract All Corpora: finished at ' + strftime('%H-%M-%S')
            result = dialog.alertDialog(
                self, 'Results found in: ' + self.outputpath + '.',
                'Processing done')
Пример #50
0
 def on_menuHelpAbout_select(self,event):
     result = dialog.alertDialog(self, '           Behafucha - Ver 0.2 / Shavit Ilan\n\n https://developer.berlios.de/projects/hebrew', 'About: Hafuch Al Hafuch')
Пример #51
0
 def on_menuHelpAbout_select(self, event):
     result = dialog.alertDialog(
         self, 'Hafuch Al Hafuch \n \n Shavit Ilan\n    Ver 0.1',
         'About: Hafuch Al Hafuch')
Пример #52
0
 def error_type_error(self):
     log.debug('TypeError')
     self.unlock_input()
     result = dialog.alertDialog(self, 'this URL is not supported', 'Error')
Пример #53
0
    def updateComponent(self, which):
        wName, wClass = self.components.wComponentList.stringSelection.split("  :  ")
        propName = which
        
        if propName in self.checkItems:
            value = self.components["chk"+propName].checked
        elif propName in self.popItems:
            value = self.components["pop"+propName].stringSelection
        elif propName in ('items', 'userdata') or (wClass == 'TextArea' and propName == 'text'):
            value = self.components["fld"+propName].text
        else:
            value = self.components["fld"+propName].text

        if propName == "textArea": propName = 'text'
        if propName not in ['name', 'label', 'stringSelection', 'text', 'toolTip', 'userdata']:
            try:
                value = eval(value)
            except:
                pass

        # KEA 2004-05-10
        # need to figure out where to stick validation code
        # but for now just need to make sure that if we're changing the name
        # attribute that it is valid, but similar checks will be necessary for
        # integer fields, a list of items, etc.
        # also maybe each attribute should have a doc or help string displayed
        # saying what the attribute does, example values, etc.
        if propName == 'name':
            badValue = False
            # if it isn't valid then display an alert and exit
            # must start with a letter and only contain alphanumeric characters
            if value == "" or value[0] not in string.ascii_letters:
                badValue = True
            else:
                alphanumeric = string.ascii_letters + string.digits
                for c in value:
                    if c not in alphanumeric:
                        badValue = True
                        break
            if badValue:
                dialog.alertDialog(None, "Name must start with a letter and only contain letters and numbers.", 
                                         'Error: Name is invalid')
                self.components["fld"+which].text = wName
                self.components["fld"+which].setFocus()
                self.components["fld"+which].setSelection(-1, -1)
                return
            # check for duplicate names is done below

        ##widget = self.components[wName]
        widget = self._comp[wName]

        # KEA 2002-02-23
        # I can't remember why this is actually necessary
        if propName == 'size':
            width, height = value
            if wClass not in ['BitmapCanvas', 'HtmlWindow']:
                bestWidth, bestHeight = widget.GetBestSize()
                if width == -1:
                    width = bestWidth
                if height == -1:
                    height = bestHeight
            widget.size = (width, height)
        else:
            if (propName in self.cantModify) or \
               (propName == 'items' and wClass == 'RadioGroup') or \
               (propName in ['label', 'text']):
                if (propName == 'layout'):
                    xx,yy = widget.size
                    widget.size = yy, xx
                    
                order = self._comp.order.index(wName)
                desc = multiresourceOutput.widgetAttributes(self._parent, widget)
                if desc.endswith(',\n'):
                    desc = eval(desc[:-2])
                else:
                    desc = eval(desc)

                if propName == 'name':
                    if value == wName:
                        # user didn't actually change the name
                        return
                    elif value in self._comp:
                        # we already have a component with that name
                        dialog.alertDialog(self, 'Another component already exists with the name ' + value,
                                           'Error: unable to rename component')
                        self.components["fldname"].text = wName
                        self.components["fldname"].setFocus()
                        self.components["fldname"].setSelection(-1, -1)
                        return
                if propName in ['label', 'text']:
                    if not self.components.chkallowNameLabelVariation.checked: 
                        if value == "":
                            result = dialog.messageDialog(self, 
                                'To set '+propName+' to be empty, you must allow Name and '+propName+' to differ.\n'+
                                'Do you want to allow that ?', 'Empty '+propName,
                                wx.ICON_QUESTION | wx.YES_NO | wx.NO_DEFAULT)
                            if result.accepted:
                                self.components.chkallowNameLabelVariation.checked = True
                                desc[propName] = value
                            else:
                                # don't allow this change
                                #self.components["fldname"].text = wName
                                self.components["fld"+propName].text = desc[propName]      
                                self.components["fld"+propName].setFocus()
                                self.components["fld"+propName].setSelection(-1, -1)   
                                return
                        else:
                            oldval = desc[propName]
                            desc[propName] = value
                            self._parent.deriveNameFromLabel(desc)
                                
                            if desc['name'] in self._comp:
                                # we already have a component with that name
                                dialog.alertDialog(self, 'Another component already exists with the name ' + value,
                                                   'Error: unable to rename component')
                                desc['name'] = wName
                                desc[propName] = oldval
                                self.components["fldname"].text = wName
                                self.components["fld"+propName].text = desc[propName]      
                                self.components["fld"+propName].setFocus()
                                self.components["fld"+propName].setSelection(-1, -1)   
                                return
                
                if value is None:
                    desc[propName] = 'none'
                elif propName in ['min', 'max']:
                    desc[propName] = int(value)
                else:
                    desc[propName] = value
                    
                    
                # need to experiment with freeze and thaw to avoid
                # a lot of update events
                startTime = time.time()

                # this is going to trigger a changed event
                # as we delete the old component
                self._updatingComponent = True
                del self._comp[wName]
                if propName in ['name']:
                    if not self.components.chkallowNameLabelVariation.checked: self._parent.deriveLabelFromName(desc)
                    wName = desc['name']
                elif propName in ['label', 'text']:
                    if not self.components.chkallowNameLabelVariation: self._parent.deriveNameFromLabel(desc)
                    wName = desc['name']

                # this is going to trigger another changed event
                # as we create a new component with the changed attribute
                self._comp[wName] = desc
                c = self._comp[wName]
                wx.EVT_LEFT_DOWN(c, self._parent.on_mouseDown)
                wx.EVT_LEFT_UP(c, self._parent.on_mouseUp)
                wx.EVT_MOTION(c, self._parent.on_mouseDrag)

                # now restore the order of the component
                # have to update the startName in case the name was updated
                if propName == 'name':
                    self._parent.startName = wName
                self._comp.order.remove(wName)
                self._comp.order.insert(order, wName)

                self._parent.fixComponentOrder(wName)

                self._updatingComponent = False
                
                endTime = time.time()
                #print "attribute change took:", endTime - startTime
            else:
                if wClass in ['Image', 'ImageButton'] and propName == 'file':
                    cwd = os.getcwd()
                    try:
                        os.chdir(self._parent.filename)
                    except:
                        pass
                    setattr(widget, propName, value)
                    os.chdir(cwd)
                else:
                    setattr(widget, propName, value)
                    #print propName, value
        # KEA 2002-02-23
        self._parent.showSizingHandles(wName)
        
        # and check if we now have matching name/label, and if so, assume they now maintain derivation
        self.determineNameLabelState(wName)
Пример #54
0
    def error_io_erorr(self):
        log.debug('IOError')
        self.unlock_input()
#         result = dialog.alertDialog(self, 'IOError', 'Error')
        strings = self.resource.strings
        result = dialog.alertDialog(self, strings.error_IOError, 'Error')
Пример #55
0
    def ExtractSomeCorpora(self):
        """Extracts the segments of the LanguagePairs indicated in the file "LanguagePairs.txt" located in the program's root directory

        @self.presentfile: TMX file being currently processed
        @self.numtus: number of translation units extracted so far
        @currdir: current working directory of the program
        @pairsoflanguages: list of the pairs of language that are going to be processed
        @self.languages: list of languages whose segments can be processed
        @numcorpora: number of language pair being processed
        @self.inputdir: directory whose files will be treated
        @self.outputfile: base name of the resulting corpora files
        @self.errors:output file indicating the types of error that occurred in each processed TMX file
        @self.startinglanguage: something like 'EN-GB'
        @self.destinationlanguage: something like 'FR-FR'
        @lang1: code of the starting language
        @lang2: code of the destination language
        @self.errortypes: variable that stocks the types of errors detected in the TMX file that is being processed
        @self.wroteactions: variable that indicates whether the actions files has already been written to
        """

        print 'Extract Some Corpora: started at ' + strftime('%H-%M-%S')
        self.presentfile = ''
        self.numtus = 0
        currdir = os.getcwd()
        #... load the file ("LanguageCodes.txt") with the list of languages that the program can process
        try:
            pairsoflanguages = open(currdir + r'\LanguagePairs.txt',
                                    'r+').readlines()
        except:
            # If the languages file doesn't exist in the program directory, alert user that it is essential for the good working of the program and exit
            result = dialog.alertDialog(
                self,
                'The file "LanguagePairs.txt" is missing. The program will now close.',
                'Essential file missing')
            sys.exit()
        #remove end of line marker from each line in "LanguageCodes.txt"
        if pairsoflanguages:
            for item in range(len(pairsoflanguages)):
                pairsoflanguages[item] = pairsoflanguages[item].strip()
                pos = pairsoflanguages[item].find("/")
                pairsoflanguages[item] = (pairsoflanguages[item][:pos],
                                          pairsoflanguages[item][pos + 1:])
        else:
            # If the languages file is empty, alert user that it is essential for the good working of the program and exit
            result = dialog.alertDialog(
                self,
                'The file "LanguagePairs.txt" is an essential file and is empty. The program will now close.',
                'Empty file')
            sys.exit()

        #if the directory where TMX files (@inputdir) or the base name of the output files were not previously chosen, open a dialog box explaining
        #the conditions that have to be met so that the extraction can be made and do nothing...
        if (self.inputdir == '') or (self.outputfile == ''):
            result = dialog.alertDialog(self, 'In order to extract all corpora, you need to:\n\n 1) indicate the directory where the TMX files are, and\n ' \
                                        + '2) the base name of the output files.', 'Error')
        #...else, go ahead
        else:
            numcorpora = 0
            for (lang1, lang2) in pairsoflanguages:
                if lang1 <> lang2:
                    print lang1 + '/' + lang2 + ' corpus being created...'
                    self.errortypes = ''
                    numcorpora = numcorpora + 1
                    #get the startinglanguage code (e.g.: "EN-GB")
                    self.startinglanguage = lang1
                    #get the destinationlanguage code
                    self.destinationlanguage = lang2
                    try:
                        self.errors = open(
                            self.outputpath + '\\_processing_info\\' +
                            self.startinglanguage + '-' +
                            self.destinationlanguage + '_' + 'errors.txt',
                            'w+')
                    except:
                        pass
                    self.statusBar.text = 'Language pair ' + str(
                        numcorpora) + ' being processed. Please wait.'
                    #Launch the segment extraction
                    self.numtus = 0
                    self.wroteactions = False
                    self.getallsegments()
                    # if any error up to now, add the name of the TMX file to the output file @errors
                    if self.errortypes:
                        try:
                            self.errors.write(
                                self.presentfile.encode('utf_8', 'replace') +
                                ':\n' +
                                self.errortypes.encode('utf_8', 'replace'))
                        except:
                            pass
                    try:
                        self.errors.close()
                    except:
                        pass
                else:
                    result = dialog.alertDialog(self, 'A bilingual corpus involves two different languages. The pair "'+lang1+'/'+lang2 + \
                            '" will not be processed.', 'Alert')
                self.statusBar.text = 'Processing finished.'
            #Open dialog box telling that processing is finished and where can the resulting files be found
            self.inputdir = ''
            self.outputfile = ''
            self.outputpath = ''
            print 'Extract Some Corpora: finished at ' + strftime('%H-%M-%S')
            result = dialog.alertDialog(
                self, 'Results found in: ' + self.outputpath + '.',
                'Processing done')