当前位置: 首页>>代码示例>>Python>>正文


Python localization._translate函数代码示例

本文整理汇总了Python中psychopy.localization._translate函数的典型用法代码示例。如果您正苦于以下问题:Python _translate函数的具体用法?Python _translate怎么用?Python _translate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了_translate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: check

 def check(self, parent):
     """checks namespace, return error-msg (str), enable (bool)
     """
     control = self.GetWindow()
     newName = control.GetValue()
     msg, OK = '', True  # until we find otherwise
     if newName == '':
         msg = _translate("Missing name")
         OK = False
     else:
         namespace = parent.frame.exp.namespace
         used = namespace.exists(newName)
         sameAsOldName = bool(newName == parent.params['name'].val)
         if used and not sameAsOldName:
             msg = _translate("That name is in use (by %s). Try another name.") % used
             OK = False
         elif not namespace.isValid(newName):  # valid as a var name
             msg = _translate("Name must be alpha-numeric or _, no spaces")
             OK = False
         # warn but allow, chances are good that its actually ok
         elif namespace.isPossiblyDerivable(newName):
             msg = _translate(namespace.isPossiblyDerivable(newName))
             OK = True
     parent.warningsDict['name'] = msg
     return msg, OK
开发者ID:hoechenberger,项目名称:psychopy,代码行数:25,代码来源:validators.py

示例2: fetchPsychoPy

    def fetchPsychoPy(self, v='latest'):
        msg = _translate("Attempting to fetch PsychoPy %s...")
        self.statusMessage.SetLabel(msg % self.latest['version'])
        info = ""
        if v == 'latest':
            v = self.latest['version']

        # open page
        URL = "https://github.com/psychopy/psychopy/releases/download/%s/PsychoPy-%s.zip"
        page = urllib.request.urlopen(URL % v)
        # download in chunks so that we can monitor progress and abort mid-way
        chunk = 4096
        read = 0
        fileSize = int(page.info()['Content-Length'])
        buffer = io.StringIO()
        self.progressBar.SetRange(fileSize)
        while read < fileSize:
            ch = page.read(chunk)
            buffer.write(ch)
            read += chunk
            self.progressBar.SetValue(read)
            txt = _translate(
                "Fetched %(done)i of %(total)i kb of PsychoPy-%(version)s.zip")
            msg = txt % {'done': read // 1000,
                         'total': fileSize // 1000, 'version': v}
            self.statusMessage.SetLabel(msg)
            self.Update()
        info += _translate('Successfully downloaded PsychoPy-%s.zip') % v
        page.close()
        zfile = zipfile.ZipFile(buffer)
        # buffer.close()
        return zfile, info
开发者ID:flipphillips,项目名称:psychopy,代码行数:32,代码来源:connections.py

示例3: __init__

    def __init__(self, parent, ID, app):
        """Latest is optional extra. If not given it will be fetched.
        """
        self.app = app
        # get latest version info if poss
        if app.updater in [False, None]:
            # user has turned off check for updates in prefs so check now
            app.updater = updater = Updater(app=self.app)
            # don't need a warning - we'll provide one ourselves
            self.latest = updater.getLatestInfo(warnMsg=False)
        else:
            self.latest = app.updater.latest
        self.runningVersion = app.updater.runningVersion
        wx.Dialog.__init__(self, parent, ID,
                           title=_translate('PsychoPy Updates'),
                           size=(100, 200))

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        # set the actual content of status msg later in self.updateStatus()
        self.statusMessage = wx.StaticText(
            self, -1, "msg", style=wx.ALIGN_CENTER)
        mainSizer.Add(self.statusMessage, flag=wx.EXPAND | wx.ALL, border=5)
        # ctrls for auto-update from web
        msg = _translate(" Auto-update (will fetch latest version)")
        self.useLatestBtn = wx.RadioButton(self, -1, msg,
                                           style=wx.RB_GROUP)
        self.Bind(wx.EVT_RADIOBUTTON, self.onRadioSelect, self.useLatestBtn)
        self.progressBar = wx.Gauge(self, -1, 100, size=(250, 25))
        mainSizer.Add(self.useLatestBtn,
                      flag=wx.ALIGN_LEFT | wx.ALL, border=5)
        mainSizer.Add(self.progressBar, flag=wx.EXPAND | wx.ALL, border=5)
        # ctrls for updating from specific zip file
        msg = _translate(" Use zip file below (download a PsychoPy release "
                         "file ending .zip)")
        self.useZipBtn = wx.RadioButton(self, -1, msg)
        self.Bind(wx.EVT_RADIOBUTTON, self.onRadioSelect, self.useZipBtn)
        self.fileBrowseCtrl = wx.lib.filebrowsebutton.FileBrowseButton(
            self, -1, size=(450, -1), changeCallback=self.onFileBrowse,
            fileMask='*.zip')
        mainSizer.Add(self.useZipBtn, flag=wx.ALIGN_LEFT | wx.ALL, border=5)
        mainSizer.Add(self.fileBrowseCtrl,
                      flag=wx.ALIGN_LEFT | wx.ALL, border=5)
        # ctrls for buttons (install/cancel)
        self.installBtn = wx.Button(self, -1, _translate('Install'))
        self.Bind(wx.EVT_BUTTON, self.onInstall, self.installBtn)
        self.installBtn.SetDefault()
        self.cancelBtn = wx.Button(self, -1, _translate('Close'))
        self.Bind(wx.EVT_BUTTON, self.onCancel, self.cancelBtn)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add(self.installBtn, flag=wx.ALIGN_RIGHT)
        btnSizer.Add(self.cancelBtn, flag=wx.ALIGN_RIGHT | wx.LEFT, border=5)
        mainSizer.Add(btnSizer, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)

        self.SetSizerAndFit(mainSizer)
        self.SetAutoLayout(True)

        # positioning and sizing
        self.updateStatus()
        self.Center()
        self.ShowModal()
开发者ID:flipphillips,项目名称:psychopy,代码行数:60,代码来源:connections.py

示例4: onLogin

 def onLogin(self, event):
     """
     Check credentials and login
     """
     if not havePyosf:
         dialogs.MessageDialog(parent=self.parent, type='Warning',
                               title=_translate("pyosf not found"),
                               message=_translate("You need pyosf to "
                                       "log in to Open Science Framework"),
                               )
         return None
     username = self.username.GetValue()
     pword = self.password.GetValue()
     rememberMe = bool(self.rememberMe.GetValue())
     try:
         session = pyosf.Session(username=username,
                                 password=pword, remember_me=rememberMe)
         self.app.osf_session = session
         self.updateStatus(_translate("Successful authentication"),
                           color=(0, 170, 0))
         time.sleep(0.5)
         self.Destroy()
     except pyosf.AuthError:
         self.updateStatus(_translate("Failed to Authenticate. "
                           "Check username/password"), color=(255, 0, 0))
开发者ID:ChenTzuYin,项目名称:psychopy,代码行数:25,代码来源:projects.py

示例5: setPrefsFromCtrls

 def setPrefsFromCtrls(self):
     # extract values, adjust as needed:
     # a) strip() to remove whitespace
     # b) case-insensitive match for Cmd+ at start of string
     # c) reverse-map locale display names to canonical names (ja_JP)
     re_cmd2ctrl = re.compile('^Cmd\+', re.I)
     for sectionName in self.prefsCfg:
         for prefName in self.prefsSpec[sectionName]:
             if prefName in ['version']:  # any other prefs not to show?
                 continue
             ctrlName = sectionName + '.' + prefName
             ctrl = self.ctrls[ctrlName]
             thisPref = ctrl.getValue()
             # remove invisible trailing whitespace:
             if hasattr(thisPref, 'strip'):
                 thisPref = thisPref.strip()
             # regularize the display format for keybindings
             if sectionName == 'keyBindings':
                 thisPref = thisPref.replace(' ', '')
                 thisPref = '+'.join([part.capitalize()
                                      for part in thisPref.split('+')])
                 if platform.system() == 'Darwin':
                     # key-bindings were displayed as 'Cmd+O', revert to
                     # 'Ctrl+O' internally
                     thisPref = re_cmd2ctrl.sub('Ctrl+', thisPref)
             self.prefsCfg[sectionName][prefName] = thisPref
             # make sure list values are converted back to lists (from str)
             if self.prefsSpec[sectionName][prefName].startswith('list'):
                 try:
                     # if thisPref is not a null string, do eval() to get a
                     # list.
                     if thisPref == '' or type(thisPref) == list:
                         newVal = thisPref
                     else:
                         newVal = eval(thisPref)
                 except Exception:
                     # if eval() failed, show warning dialog and return
                     try:
                         pLabel = _localized[prefName]
                         sLabel = _localized[sectionName]
                     except Exception:
                         pLabel = prefName
                         sLabel = sectionName
                     txt = _translate(
                         'Invalid value in "%(pref)s" ("%(section)s" Tab)')
                     msg = txt % {'pref': pLabel, 'section': sLabel}
                     title = _translate('Error')
                     warnDlg = dialogs.MessageDialog(parent=self,
                                                     message=msg,
                                                     type='Info',
                                                     title=title)
                     resp = warnDlg.ShowModal()
                     return
                 if type(newVal) != list:
                     self.prefsCfg[sectionName][prefName] = [newVal]
                 else:
                     self.prefsCfg[sectionName][prefName] = newVal
     self.app.prefs.saveUserPrefs()  # includes a validation
开发者ID:flipphillips,项目名称:psychopy,代码行数:58,代码来源:preferencesDlg.py

示例6: save

 def save(self, event=None):
     """save header + row x col data to a pickle file
     """
     self.getData(True)  # update self.data
     adjustedNames = False
     for i, paramName in enumerate(self.data[0]):
         newName = paramName
         # ensure its legal as a var name, including namespace check:
         if self.parent:
             msg, enable = self.parent._checkName(name=paramName)
             if msg:  # msg not empty means a namespace issue
                 newName = self.parent.exp.namespace.makeValid(
                     paramName, prefix='param')
                 adjustedNames = True
         elif not valid_var_re.match(paramName):
             msg, enable = _translate(
                 "Name must be alpha-numeric or _, no spaces"), False
             newName = _nonalphanumeric_re.sub('_', newName)
             adjustedNames = True
         else:
             msg, enable = "", True
         # try to ensure its unique:
         while newName in self.data[0][:i]:
             adjustedNames = True
             newName += 'x'  # might create a namespace conflict?
         self.data[0][i] = newName
         self.header[i].SetValue(newName)  # displayed value
     if adjustedNames:
         self.tmpMsg.SetLabel(_translate(
             'Param name(s) adjusted to be legal. Look ok?'))
         return False
     if hasattr(self, 'fileName') and self.fileName:
         fname = self.fileName
     else:
         self.newFile = True
         fname = self.defaultFileName
     if self.newFile or not os.path.isfile(fname):
         fullPath = gui.fileSaveDlg(initFilePath=os.path.split(fname)[0],
                                    initFileName=os.path.basename(fname),
                                    allowed="Pickle files (*.pkl)|*.pkl")
     else:
         fullPath = fname
     if fullPath:  # None if user canceled
         if not fullPath.endswith('.pkl'):
             fullPath += '.pkl'
         f = open(fullPath, 'w')
         pickle.dump(self.data, f)
         f.close()
         self.fileName = fullPath
         self.newFile = False
         # ack, sometimes might want relative path
         if self.parent:
             self.parent.conditionsFile = fullPath
     return True
开发者ID:flipphillips,项目名称:psychopy,代码行数:54,代码来源:dlgsConditions.py

示例7: onOpenFile

 def onOpenFile(self, event):
     """Open project file from dialog
     """
     dlg = wx.FileDialog(parent=None,
                         message=_translate("Open local project file"),
                         style=wx.FD_OPEN,
                         wildcard=_translate(
                         "Project files (*.psyproj)|*.psyproj"))
     if dlg.ShowModal() == wx.ID_OK:
         projFile = dlg.GetPath()
         self.openProj(projFile)
开发者ID:ChenTzuYin,项目名称:psychopy,代码行数:11,代码来源:projects.py

示例8: getProject

def getProject(filename):
    """Will try to find (locally synced) pavlovia Project for the filename
    """
    try:
        git
        haveGit = True
    except ImportError:
        haveGit = False
    if not haveGit:
        logging.error(
            "You need to install git to connect with Pavlovia projects")
        return None
    gitRoot = getGitRoot(filename)
    if gitRoot in knownProjects:
        return knownProjects[gitRoot]
    elif gitRoot:
        # Existing repo but not in our knownProjects. Investigate
        logging.info("Investigating repo at {}".format(gitRoot))
        localRepo = git.Repo(gitRoot)
        proj = None
        for remote in localRepo.remotes:
            for url in remote.urls:
                if "gitlab.pavlovia.org/" in url:
                    namespaceName = url.split('gitlab.pavlovia.org/')[1]
                    namespaceName = namespaceName.replace('.git', '')
                    pavSession = getCurrentSession()
                    if pavSession.user:
                        proj = pavSession.getProject(namespaceName,
                                                     repo=localRepo)
                        if proj.pavlovia == 0:
                            logging.warning(
                                    _translate(
                                        "We found a repository pointing to {} "
                                        "but ") +
                                    _translate("no project was found there ("
                                               "deleted?)")
                                    .format(url))

                    else:
                        logging.warning(
                                _translate(
                                    "We found a repository pointing to {} "
                                    "but ") +
                                _translate(
                                    "no user is logged in for us to check "
                                    "it")
                                .format(url))
                    return proj
        if proj == None:
            logging.warning("We found a repository at {} but it "
                            "doesn't point to gitlab.pavlovia.org. "
                            "You could create that as a remote to "
                            "sync from PsychoPy.".format(gitRoot))
开发者ID:mmagnuski,项目名称:psychopy,代码行数:53,代码来源:pavlovia.py

示例9: getLatestInfo

 def getLatestInfo(self, warnMsg=False):
     # open page
     latest = getLatestVersionInfo()
     if latest == -1:
         m1 = _translate("Couldn't connect to psychopy.org to check for "
                         "updates. \n")
         m2 = _translate("Check internet settings (and proxy setting in "
                         "PsychoPy Preferences).")
         confirmDlg = dialogs.MessageDialog(
             parent=None, message=m1 + m2, type='Info',
             title=_translate('PsychoPy updates'))
         confirmDlg.ShowModal()
     return latest
开发者ID:flipphillips,项目名称:psychopy,代码行数:13,代码来源:connections.py

示例10: onInsertRoutineSelect

 def onInsertRoutineSelect(self, event):
     """User has selected a routine to be entered so bring up the
     entrypoint marker and await mouse button press.
     see self.insertRoutine() for further info
     """
     self.mode = 'routine'
     self.btnInsertRoutine.SetLabel(_translate('CANCEL Insert'))
     self.btnInsertRoutine.SetLabelColor(**self.labelTextRed)
     self.frame.SetStatusText(_translate(
         'Click where you want to insert the Routine, or CANCEL insert.'))
     self.insertingRoutine = self.routinesFromID[event.GetId()]
     x = self.getNearestGapPoint(0)
     self.drawEntryPoints([x])
开发者ID:dgfitch,项目名称:psychopy,代码行数:13,代码来源:flow.py

示例11: updateUserProjs

 def updateUserProjs(self):
     if self.app.osf_session.user_id is None:
         self.myProjectsPanel.setContents(
             _translate("No user logged in. \n\n"
             "Go to menu item Projects>Users>"))
     else:
         self.myProjectsPanel.setContents(
             _translate("Searching projects for user {} ...")
             .format(self.app.osf_session.username))
         self.Update()
         wx.Yield()
         myProjs = self.app.osf_session.find_user_projects()
         self.myProjectsPanel.setContents(myProjs)
开发者ID:ChenTzuYin,项目名称:psychopy,代码行数:13,代码来源:projects.py

示例12: check

    def check(self, parent):
        """Checks python syntax of code snippets, and for self-reference.

        Note: code snippets simply use existing names in the namespace,
        like from condition-file headers. They do not add to the
        namespace (unlike Name fields).

        Code snippets in param fields will often be user-defined
        vars, especially condition names. Can also be expressions like
        random(1,100). Hard to know what will be problematic.
        But its always the case that self-reference is wrong.
        """
        # first check if there's anything to validate (and return if not)
        control = self.GetWindow()
        if not hasattr(control, 'GetValue'):
            return '', True
        val = control.GetValue()  # same as parent.params[self.fieldName].val
        if not isinstance(val, basestring):
            return '', True

        field = self.fieldName
        msg, OK = '', True  # until we find otherwise
        codeWanted = psychopy.experiment.utils.unescapedDollarSign_re.search(val)
        isCodeField = bool(parent.params[self.fieldName].valType == 'code')
        if codeWanted or isCodeField:
            # get var names from val, check against namespace:
            code = experiment.getCodeFromParamStr(val)
            try:
                names = compile(code, '', 'eval').co_names
            except SyntaxError:
                # empty '' compiles to a syntax error, ignore
                if not code.strip() == '':
                    msg = _translate('Python syntax error in field `{}`:  {}')
                    msg = msg.format(self.displayName, code)
                    OK = False
            else:
                # namespace = parent.frame.exp.namespace
                # parent.params['name'].val is not in namespace for new params
                # and is not fixed as .val until dialog closes. Use getvalue()
                # to handle dynamic changes to Name field:
                if 'name' in parent.paramCtrls:  # some components don't have names
                    parentName = parent.paramCtrls['name'].getValue()
                    for name in names:
                        # `name` means a var name within a compiled code snippet
                        if name == parentName:
                            msg = _translate(
                                'Python var `{}` in `{}` is same as Name')
                            msg = msg.format(name, self.displayName)
                            OK = False
        parent.warningsDict[field] = msg
        return msg, OK
开发者ID:flipphillips,项目名称:psychopy,代码行数:51,代码来源:validators.py

示例13: __init__

    def __init__(self, project, parent, *args, **kwargs):
        wx.Dialog.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.project = project
        existingName = project.name
        msgText = _translate("points to a remote that doesn't exist (deleted?).")
        msgText += (" "+_translate("What shall we do?"))
        msg = wx.StaticText(self, label="{} {}".format(existingName, msgText))
        choices = [_translate("(Re)create a project"),
                   "{} ({})".format(_translate("Point to an different location"),
                                    _translate("not yet supported")),
                   _translate("Forget the local git repository (deletes history keeps files)")]
        self.radioCtrl = wx.RadioBox(self, label='RadioBox', choices=choices,
                                     majorDimension=1)
        self.radioCtrl.EnableItem(1, False)
        self.radioCtrl.EnableItem(2, False)

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
        buttonSizer.Add(wx.Button(self, id=wx.ID_OK, label=_translate("OK")),
                      1, wx.ALL | wx.ALIGN_RIGHT, 5)
        buttonSizer.Add(wx.Button(self, id=wx.ID_CANCEL, label=_translate("Cancel")),
                      1, wx.ALL | wx.ALIGN_RIGHT, 5)
        mainSizer.Add(msg, 1, wx.ALL, 5)
        mainSizer.Add(self.radioCtrl, 1, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)
        mainSizer.Add(buttonSizer, 1, wx.ALL | wx.ALIGN_RIGHT, 1)

        self.SetSizer(mainSizer)
        self.Layout()
开发者ID:dgfitch,项目名称:psychopy,代码行数:29,代码来源:project.py

示例14: addPavloviaTools

    def addPavloviaTools(self, buttons=[]):
        rc = self.frame.app.prefs.paths['resources']

        info = {}
        info['pavloviaRun'] = {
            'emblem': 'run16.png',
            'func': self.frame.onPavloviaRun,
            'label': _translate('Run online'),
            'tip': _translate('Run the study online (with pavlovia.org)')}
        info['pavloviaSync'] = {
            'emblem': 'sync_green16.png',
            'func': self.frame.onPavloviaSync,
            'label': _translate('Sync online'),
            'tip': _translate('Sync with web project (at pavlovia.org)')}
        info['pavloviaSearch'] = {
            'emblem': 'magnifier16.png',
            'func': self.onPavloviaSearch,
            'label': _translate('Search Pavlovia.org'),
            'tip': _translate('Find existing studies online (at pavlovia.org)')}
        info['pavloviaUser'] = {
            'emblem': 'user22.png',
            'func': self.onPavloviaUser,
            'label': _translate('Log in to Pavlovia'),
            'tip': _translate('Log in to (or create user at) Pavlovia.org')}
        info['pavloviaProject'] = {
            'emblem': 'info16.png',
            'func': self.onPavloviaProject,
            'label': _translate('View project'),
            'tip': _translate('View details of this project')}

        if not buttons:  # allows panels to select subsets
            buttons = info.keys()

        for buttonName in buttons:
            emblem = info[buttonName]['emblem']
            btnFunc = info[buttonName]['func']
            label = info[buttonName]['label']
            tip = info[buttonName]['tip']
            btnImage = icons.combineImageEmblem(
                    main=join(rc, 'globe%i.png' % self.tbSize),
                    emblem=join(rc, emblem), pos='bottom_right')

            if 'phoenix' in wx.PlatformInfo:
                self.btnHandles[buttonName] = self.toolbar.AddTool(
                        wx.ID_ANY, label, btnImage, tip)
            else:
                self.btnHandles[buttonName] = self.toolbar.AddSimpleTool(
                        wx.ID_ANY, btnImage, label, tip)

            self.toolbar.Bind(wx.EVT_TOOL, btnFunc, self.btnHandles[buttonName])
开发者ID:dgfitch,项目名称:psychopy,代码行数:50,代码来源:toolbar.py

示例15: __init__

    def __init__(self, parent, id, project, *args, **kwargs):
        wx.Panel.__init__(self, parent, id, *args, **kwargs)
        self.project = project

        self.sizer = wx.FlexGridSizer(rows=2, cols=2, vgap=5, hgap=5)
        self.sizer.AddGrowableCol(1)

        upLabel = wx.StaticText(self, -1, _translate("Uploading:"))
        self.upProg = wx.Gauge(self, -1, range=1, size=(200, -1))
        downLabel = wx.StaticText(self, -1, _translate("Downloading:"))
        self.downProg = wx.Gauge(self, -1, range=1, size=(200, -1))
        self.sizer.AddMany([upLabel, self.upProg,
                            downLabel, self.downProg])
        self.SetSizerAndFit(self.sizer)
开发者ID:ChenTzuYin,项目名称:psychopy,代码行数:14,代码来源:projects.py


注:本文中的psychopy.localization._translate函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。