Python os.environ 模块,has_key() 实例源码

我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用os.environ.has_key()

项目:python    作者:hienha    | 项目源码 | 文件源码
def getCPPCookies(self):                # reads cookies from client
        if environ.has_key('HTTP_COOKIE'):
            for eachCookie in map(strip, \
                    split(environ['HTTP_COOKIE'], ';')):
                if len(eachCookie) > 6 and \
                        eachCookie[:3] == 'CPP':
                    tag = eachCookie[3:7]
                    try:
                        self.cookies[tag] = \
                            eval(unquote(eachCookie[8:]))
                    except (NameError, SyntaxError):
                        self.cookies[tag] = \
                            unquote(eachCookie[8:])
        else:
            self.cookies['info'] = self.cookies['user'] = ''

        if self.cookies['info'] != '':
            self.who, langStr, self.fn = \
                split(self.cookies['info'], ':')
            self.langs = split(langStr, ',')
        else:
            self.who = self.fn = ''
            self.langs = ['Python']
项目:python    作者:hienha    | 项目源码 | 文件源码
def showForm(self):                        # show fill-out form
        self.getCPPCookies()
        langStr = ''
        for eachLang in AdvCGI.langSet:
            if eachLang in self.langs:
                langStr = langStr + AdvCGI.langItem % \
                    (eachLang, ' CHECKED', eachLang)
            else:
                langStr = langStr + AdvCGI.langItem % \
                    (eachLang, '', eachLang)

        if not self.cookies.has_key('user') or \
                self.cookies['user'] == '':
            cookieStatus = '<I>(cookie has not been set yet)</I>'
            userCook = ''
        else:
            userCook = cookieStatus = self.cookies['user']

        print AdvCGI.header + AdvCGI.formhtml % (AdvCGI.url,
            cookieStatus, userCook, self.who, langStr, self.fn)
项目:python    作者:hienha    | 项目源码 | 文件源码
def getCPPCookies(self):
                if environ.has_key('HTTP_COOKIE'):
                        #s('reading cookies from server...\n')
                        for eachCookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
                                if len(eachCookie) > 6 and eachCookie[:3] == 'CPP':
                                        tag = eachCookie[3:7]
                                        try:
                                                self.cookies[tag] = eval(unquote(eachCookie[8:]))
                                        except (NameError, SyntaxError):
                                                self.cookies[tag] = unquote(eachCookie[8:])
                else:
                        #s('no cookies on server...\n')
                        self.cookies['info'] = self.cookies['user'] = ''

                #s('cookies: %s\n' % str(self.cookies))
                if self.cookies['info'] != '':
                        self.who, langStr, self.fn = split(self.cookies['info'], ':')
                        self.langs = split(langStr, ',')
                else:
                        self.who = self.fn = ''
                        self.langs = ['Python']
项目:python    作者:hienha    | 项目源码 | 文件源码
def showForm(self):
                self.getCPPCookies()                # get cookies

                # put together lang checkboxes
                langStr = ''
                for eachLang in AdvCGI.langSet:
                        if eachLang in self.langs:
                                langStr = langStr + AdvCGI.langItem % (eachLang, ' CHECKED', eachLang)
                        else:
                                langStr = langStr + AdvCGI.langItem % (eachLang, '', eachLang)

                # see if user cookie set up yet
                if not self.cookies.has_key('user') or self.cookies['user'] == '':
                        cookieStatus = '<I>(cookie has not been set yet)</I>'
                        userCook = ''
                else:
                        userCook = cookieStatus = self.cookies['user']

                # output results
                #s('filename: ' + self.fn + '\n')
                print AdvCGI.header + AdvCGI.formhtml % (AdvCGI.url, cookieStatus, userCook, self.who, langStr, self.fn)
                #print AdvCGI.header + AdvCGI.formhtml % (AdvCGI.url, cookieStatus, userCook, self.who, langStr)
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def restrictParameters(self) :

        # Initialise allowed parameters
        allowed_parameters = {}
        for group_code in self.parameter_group_codes :
            allowed_parameters[group_code] = self.parameter_via_group_codes[group_code][:]

        # Resolve any restrictions based on data type
        data_type = self.data_type_text.get()
        if self.parameter_restricted_via_data_type.has_key(data_type) :
            for group_code in self.parameter_group_codes :
                if self.parameter_restricted_via_data_type[data_type].has_key(group_code) :
                    allowed_parameters[group_code] = self.parameter_restricted_via_data_type[data_type][group_code]

        # Enable/disable parameter selections appropriately
        allowed_groups = []
        for i, group_code in enumerate(self.parameter_group_codes) : 
            if allowed_parameters[group_code] :
                allowed_groups.append(group_code)
                self.parameter_group_menu['menu'].entryconfigure(i, state=tk.NORMAL)
                for j, parameter_code in enumerate(self.parameter_via_group_codes[group_code]) :
                    if len(self.parameter_via_group_codes[group_code]) > 1  or self.parameter_via_group_codes[group_code][0] != group_code :
                        if parameter_code in allowed_parameters[group_code] :
                            self.parameter_via_group_menu[group_code]['menu'].entryconfigure(j, state=tk.NORMAL)
                        else :
                            self.parameter_via_group_menu[group_code]['menu'].entryconfigure(j, state=tk.DISABLED)
            else :
                self.parameter_group_menu['menu'].entryconfigure(i, state=tk.DISABLED)

        # Select another parameter/group if the current selection is not allowed
        selected_group = self.parameter_group_selection_map[self.parameter_group_text.get()]
        if selected_group not in allowed_groups :
            self.selectParameterGroup(allowed_groups[0])
        else :
            selected_parameter = self.parameter_via_group_selection_map[selected_group][self.parameter_via_group_text[selected_group].get()]
            if selected_parameter not in allowed_parameters[selected_group] :
                self.selectParameter(selected_group, allowed_parameters[selected_group][0])

    # Step 2 Method: Restrict Time Unit Via Data Type and/or Parameter
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def restrictTimeUnit(self) :

        # Initialise allowed time units
        allowed_time_units = self.time_unit_selection[:]

        # Resolve any restrictions based on data type
        data_type = self.data_type_text.get()
        if self.time_unit_restricted_via_data_type.has_key(data_type) :
            allowed_time_units = self.time_unit_restricted_via_data_type[data_type][:]

        # Resolve any restrictions based on parameter
        group_code = self.parameter_group_selection_map[self.parameter_group_text.get()]
        if self.time_unit_restricted_via_parameter.has_key(group_code) :
            parameter_code = self.parameter_via_group_selection_map[group_code][self.parameter_via_group_text[group_code].get()]
            if self.time_unit_restricted_via_parameter[group_code].has_key(parameter_code) :
                for time_unit in allowed_time_units[:] :
                    if time_unit not in self.time_unit_restricted_via_parameter[group_code][parameter_code] :
                        allowed_time_units.remove(time_unit)

        # Enable/disable time unit selections appropriately
        for i, selection in enumerate(self.time_unit_selection) :
            if selection in allowed_time_units :
                self.time_unit_menu['menu'].entryconfigure(i, state=tk.NORMAL)
            else :
                self.time_unit_menu['menu'].entryconfigure(i, state=tk.DISABLED)

        # Select another time unit if the current selection is not allowed
        if self.time_unit_text.get() not in allowed_time_units :
            self.selectTimeUnit(allowed_time_units[0])

    # Step 2 Method: Select Time Unit: the user selects an option
项目:python    作者:hienha    | 项目源码 | 文件源码
def doResults(self):
        MAXBYTES = 1024
        langlist = ''
        for eachLang in self.langs:
            langlist = langlist + '<LI>%s<BR>' % eachLang

        filedata = ''
        while len(filedata) < MAXBYTES:        # read file chunks
            data = self.fp.readline()
            if data == '': break
            filedata = filedata + data
        else:                                # truncate if too long
            filedata = filedata + \
                '... <B><I>(file truncated due to size)</I></B>'
        self.fp.close()
        if filedata == '':
            filedata = \
                '<B><I>(file upload error or file not given)</I></B>'
        filename = self.fn

        if not self.cookies.has_key('user') or \
                self.cookies['user'] == '':
            cookieStatus = '<I>(cookie has not been set yet)</I>'
            userCook = ''
        else:
            userCook = cookieStatus = self.cookies['user']

        self.cookies['info'] = join([self.who, \
            join(self.langs, ','), filename], ':')
        self.setCPPCookies()
        print AdvCGI.header + AdvCGI.reshtml % \
            (cookieStatus, self.who, langlist,
            filename, filedata, AdvCGI.url)
项目:python    作者:hienha    | 项目源码 | 文件源码
def doResults(self):
                MAXBYTES = 1024
                langlist = ''
                for eachLang in self.langs:
                        langlist = langlist + '<LI>%s<BR>' % eachLang
                filedata = ''
                while len(filedata) < MAXBYTES:
                        data = self.fp.readline()
                        if data == '': break
                        filedata = filedata + data
                else:
                        filedata = filedata + '... <B><I>(file truncated due to size)</I></B>'
                self.fp.close()
                if filedata == '':
                        filedata = '<B><I>(file upload error or file not given)</I></B>'
                filename = self.fn

                # see if user cookie set up yet
                if not self.cookies.has_key('user') or self.cookies['user'] == '':
                        cookieStatus = '<I>(cookie has not been set yet)</I>'
                        userCook = ''
                else:
                        userCook = cookieStatus = self.cookies['user']

                # set cookies
                self.cookies['info'] = join([self.who, join(self.langs, ','), filename], ':')
                self.setCPPCookies()

                # output page
                print AdvCGI.header + AdvCGI.reshtml % (cookieStatus, self.who, langlist, filename, filedata, AdvCGI.url)
项目:python    作者:hienha    | 项目源码 | 文件源码
def getCPPCookies(self):
                if environ.has_key('HTTP_COOKIE'):
                        #s('reading cookies from server...\n')
                        #for eachCookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
                        cookies = [x.strip() for x in environ['HTTP_COOKIE'].split(';')]
                        for eachCookie in cookies:
                                if len(eachCookie) > 6 and eachCookie[:3] == 'CPP':
                                        tag = eachCookie[3:7]
                                        try:
                                                self.cookies[tag] = eval(unquote(eachCookie[8:]))
                                        except (NameError, SyntaxError):
                                                self.cookies[tag] = unquote(eachCookie[8:])
                        if not self.cookies.has_key('info'):
                            self.cookies['info'] = ''
                        if not self.cookies.has_key('user'):
                            self.cookies['user'] = ''
                else:
                        #s('no cookies on server...\n')
                        self.cookies['info'] = self.cookies['user'] = ''

                #s('cookies: %s\n' % str(self.cookies))
                if self.cookies['info'] != '':
                        self.who, langStr, self.fn = self.cookies['info'].split(':')
                        self.langs = langStr.split(',')
                else:
                        self.who = self.fn = ''
                        self.langs = ['Python']
项目:python    作者:hienha    | 项目源码 | 文件源码
def doResults(self):
                MAXBYTES = 1024
                langlist = ''
                for eachLang in self.langs:
                        langlist = langlist + '<LI>%s<BR>' % eachLang
                filedata = ''
                while len(filedata) < MAXBYTES:
                        data = self.fp.readline()
                        if data == '': break
                        filedata = filedata + data
                else:
                        filedata = filedata + '... <B><I>(file truncated due to size)</I></B>'
                self.fp.close()
                if filedata == '':
                        filedata = '<B><I>(file upload error or file not given)</I></B>'
                filename = self.fn

                # see if user cookie set up yet
                if not self.cookies.has_key('user') or self.cookies['user'] == '':
                        cookieStatus = '<I>(cookie has not been set yet)</I>'
                        userCook = ''
                else:
                        userCook = cookieStatus = self.cookies['user']

                # set cookies
                self.cookies['info'] = ':'.join([self.who, ','.join(self.langs), filename])
                self.setCPPCookies()

                # output page
                print AdvCGI.header + AdvCGI.reshtml % (cookieStatus, self.who, langlist, filename, filedata, AdvCGI.url)
项目:rhsecapi    作者:ryran    | 项目源码 | 文件源码
def fpaste_it(inputdata, lang='text', author=None, password=None, private='no', expire=28, project=None, url='http://paste.fedoraproject.org'):
    """Submit a new paste to fedora project pastebin."""
    # Establish critical params
    params = {
        'paste_data': inputdata,
        'paste_lang': lang,
        'api_submit': 'true',
        'mode': 'json',
        'paste_private': private,
        'paste_expire': str(expire*24*60*60),
        }
    # Add optional params
    if password:
        params['paste_password'] = password
    if project:
        params['paste_project'] = project
    if author:
        # If author is too long, truncate
        if len(author) > 50:
            author = author[0:47] + "..."
        params['paste_user'] = author
    # Check size of what we're about to post and raise exception if too big
    # FIXME: Figure out how to do this in requests without wasteful call to urllib.urlencode()
    from urllib import urlencode
    p = urlencode(params)
    pasteSizeKiB = len(p)/1024.0
    if pasteSizeKiB >= 512:
        raise ValueError("Fedora Pastebin client WARN: paste size ({0:.1f} KiB) too large (max size: 512 KiB)".format(pasteSizeKiB))
    # Print status, then connect
    logger.log(25, "Fedora Pastebin client uploading {0:.1f} KiB...".format(pasteSizeKiB))
    r = requests.post(url, params)
    r.raise_for_status()
    try:
        j = r.json()
    except:
        # If no json returned, we've hit some weird error
        from tempfile import NamedTemporaryFile
        tmp = NamedTemporaryFile(delete=False)
        print(r.content, file=tmp)
        tmp.flush()
        raise ValueError("Fedora Pastebin client ERROR: Didn't receive expected JSON response (saved to '{0}' for debugging)".format(tmp.name))
    # Error keys adapted from Jason Farrell's fpaste
    if j.has_key('error'):
        err = j['error']
        if err == 'err_spamguard_php':
            raise ValueError("Fedora Pastebin server ERROR: Poster's IP rejected as malicious")
        elif err == 'err_spamguard_noflood':
            raise ValueError("Fedora Pastebin server ERROR: Poster's IP rejected as trying to flood")
        elif err == 'err_spamguard_stealth':
            raise ValueError("Fedora Pastebin server ERROR: Paste input triggered spam filter")
        elif err == 'err_spamguard_ipban':
            raise ValueError("Fedora Pastebin server ERROR: Poster's IP rejected as permanently banned")
        elif err == 'err_author_numeric':
            raise ValueError("Fedora Pastebin server ERROR: Poster's author should be alphanumeric")
        else:
            raise ValueError("Fedora Pastebin server ERROR: '{0}'".format(err))
    # Put together URL with optional hash if requested
    pasteUrl = '{0}/{1}'.format(url, j['result']['id'])
    if 'yes' in private and j['result'].has_key('hash'):
        pasteUrl += '/{0}'.format(j['result']['hash'])
    return pasteUrl
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def selectClimateDataDirectory(self) :

        # Use existing Climate Data Directory if it exists
        current_dir = self.climate_data_directory_text.get()
        if path.exists(current_dir) :
            initial_directory = current_dir
        elif MAC_VERSION and environ.has_key('HOME') and path.exists(environ['HOME']) :
            initial_directory = environ['HOME']
        elif environ.has_key('USERPROFILE') and path.exists(environ['USERPROFILE']) : # PC version
            initial_directory = environ['USERPROFILE']
        else :
            initial_directory = getcwd()

        # Open file selection dialog
        climate_data_directory_path = askdirectory(title='Select the directory containing the climate data', initialdir=initial_directory)

        if climate_data_directory_path : # Directory selected

            # Create directory if it doesn't already exist
            if not path.exists(climate_data_directory_path) :
                try :
                    climate_data_directory_path = self.data_file_helper.createDirectoryPath(climate_data_directory_path)
                except Exception, e :
                    directory_name = self.data_file_helper.splitPath(climate_data_directory_path)['name']
                    showerror('Directory Error', 'Error loading or creating directory \"'+directory_name+'\". Check file permissions.')
                    print >> sys.stderr, 'Error loading or creating directory:', e

            # Set the climate data directory appropriately
            climate_data_directory_path = path.normpath(str(climate_data_directory_path))
            previous_path = self.data_file_helper.getClimateDataDirectoryPath()
            self.data_file_helper.setClimateDataDirectory(climate_data_directory_path)
            if hasattr(self, 'config_climate_data_location_window') and self.config_climate_data_location_window.children :
                # Does it contain the climate data?
                if self.data_file_helper.climateDataIsPresent() :
                    self.climate_data_directory_text.set(climate_data_directory_path)
                    self.setToolOptions({ 'climate_data_directory' : climate_data_directory_path })
                    # Reset focus to config window
                    self.config_climate_data_location_window.focus_set()
                else :
                    showwarning('Climate data not found', 'None of the expected climate data was not found in ' + climate_data_directory_path)
                    self.data_file_helper.setClimateDataDirectory(previous_path)
            elif hasattr(self, 'download_climate_data_window') and self.download_climate_data_window.children :
                self.climate_data_directory_text.set(climate_data_directory_path)
                self.setToolOptions({ 'climate_data_directory' : climate_data_directory_path })
                # Reset focus to download window
                self.download_climate_data_window.focus_set()

    # Menu Method: Configure Default File Generation Directory
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def selectDefaultFileGenerationDirectory(self) :

        # Get current config tool options
        tool_option_values = self.getToolOptions()

        # Use existing Default File Generation Directory if it exists
        if path.exists(tool_option_values['default_file_generation_directory']) :
            initial_directory = tool_option_values['default_file_generation_directory']
        elif MAC_VERSION and environ.has_key('HOME') and path.exists(environ['HOME']) :
            initial_directory = environ['HOME']
        elif environ.has_key('USERPROFILE') and path.exists(environ['USERPROFILE']) : # PC version
            initial_directory = environ['USERPROFILE']
        else :
            initial_directory = getcwd()

        # Open file selection dialog
        default_file_generation_directory_path = askdirectory(title='Select the default directory for output files', initialdir=initial_directory)

        if default_file_generation_directory_path : # Directory selected

            # Create directory if it doesn't already exist
            if not path.exists(default_file_generation_directory_path) :
                try :
                    default_file_generation_directory_path = self.data_file_helper.createDirectoryPath(default_file_generation_directory_path)
                except Exception, e :
                    directory_name = self.data_file_helper.splitPath(default_file_generation_directory_path)['name']
                    showerror('Directory Error', 'Error loading or creating directory \"'+directory_name+'\". Check file permissions.')
                    print >> sys.stderr, 'Error loading or creating directory:', e

            # Set the directory
            default_file_generation_directory_path = path.normpath(str(default_file_generation_directory_path))
            self.data_file_helper.setFileGenerationDirectory(default_file_generation_directory_path)
            location_descr = 'File generation in \"' + self.data_file_helper.getFileGenerationDirectoryName() + '\"'
            self.generation_directory_label_text.set(location_descr)
            self.default_file_generation_directory_location.set(default_file_generation_directory_path)
            self.setToolOptions({ 'default_file_generation_directory' : default_file_generation_directory_path, 'default_file_generation_directory_set' : True })

            # Enable the generate button
            self.generate_button.configure(state=tk.NORMAL)

            # Reset focus to config window
            self.config_default_file_generation_directory_window.focus_set()

    # Menu Method: Download Climate Data
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def downloadSelectedClimateData(self) :

        # Override URL and proxy
        self.setClimateDataLocation(download=True)

        # Get download data parameters and intervals required
        data_parameters_selected = []
        for data_parameter in self.data_file_helper.getDataParameters() :
            if self.climate_data_parameter_int.has_key(data_parameter) and self.climate_data_parameter_int[data_parameter].get() :
                data_parameters_selected.append(data_parameter)
        download_intervals_selected = []
        for download_interval in self.data_file_helper.getClimateDataDownloadIntervals() :
            if self.climate_download_interval_int.has_key(download_interval) and self.climate_download_interval_int[download_interval].get() :
                download_intervals_selected.append(download_interval)

        # Download and unpack NetCDF files
        if self.data_file_helper.getClimateDataUrl() and self.data_file_helper.getClimateDataDirectoryPath() and data_parameters_selected and download_intervals_selected :
            for data_parameter in data_parameters_selected :
                for download_interval in download_intervals_selected :
                    overwrite_ok = True
                    if self.data_file_helper.climateDataDownloadIntervalPresent(data_parameter, download_interval) :
                        overwrite_ok = askyesno('Data already present: overwrite?',
                                                'The data for '+data_parameter.replace('_',' ').title()+' interval '+download_interval+' is already present in the directory selected.\n\n'+
                                                'Do you wish to download again and overwrite the existing file?', parent=self.download_climate_data_window)
                    if overwrite_ok :
                        self.climate_data_download_button.configure(state=tk.DISABLED)
                        self.climate_data_download_status_text.set('Downloading ' + data_parameter.replace('_',' ').title() + ' ' + download_interval + ' ...')
                        self.climate_data_download_status_bar['maximum'] = 1
                        self.climate_data_download_status_bar['value'] = 0
                        self.climate_data_download_status_bar.grid()
                        self.update() # .update_idletasks()
                        try :
                            self.data_file_helper.downloadClimateDataInterval(data_parameter, download_interval, delimiter='')
                        except Exception, e :
                            if hasattr(self, 'download_climate_data_window') and self.download_climate_data_window.children :
                                showerror('Data download error', str(e), parent=self.download_climate_data_window)
                                print >> sys.stderr, 'Data download error:', e
                        if self.download_climate_data_window.children :
                            self.climate_data_download_status_text.set('')
                            self.climate_data_download_status_bar.grid_remove()
                            self.climate_data_download_button.configure(state=tk.NORMAL)
                            self.update() # .update_idletasks()
        else :
            if not self.data_file_helper.getClimateDataUrl() :
                showinfo('Download from URL not defined', 'Please enter the URL location of the climate data download(s).', parent=self.download_climate_data_window)
            elif not self.data_file_helper.getClimateDataDirectoryPath() :
                showinfo('Download to Directory not defined', 'Please select the directory destination for the climate data download(s).', parent=self.download_climate_data_window)
            elif not (data_parameters_selected and download_intervals_selected) :
                showinfo('Download Selection not fully defined', 'Please select the climate data parameters and intervals to download.', parent=self.download_climate_data_window)

    ## Step 1: Data Type Methods ################################################################################################################################################

    # Step 1 Method: Select data type: the user selects an option
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def selectGenerationDirectory(self) :

        # Place focus on select directory button
        self.generation_directory_button.focus_set()

        # Reset generation
        self.resetGeneration()

        # Get current config tool options
        tool_option_values = self.getToolOptions()

        # Use existing/last used generation directory if it exists otherwise use default directory
        if self.data_file_helper.getFileGenerationDirectoryPath() and path.exists(self.data_file_helper.getFileGenerationDirectoryPath()) :
            initial_directory = self.data_file_helper.getFileGenerationDirectoryPath()
        elif tool_option_values['default_file_generation_directory'] and path.exists(tool_option_values['default_file_generation_directory']) :
            initial_directory = tool_option_values['default_file_generation_directory']
        elif MAC_VERSION and environ.has_key('HOME') and path.exists(environ['HOME']) :
            initial_directory = environ['HOME']
        elif environ.has_key('USERPROFILE') and path.exists(environ['USERPROFILE']) : # PC version
            initial_directory = environ['USERPROFILE']
        else :
            initial_directory = getcwd()

        # Open file selection dialog
        generation_directory_path = askdirectory(title='Select the directory to generate files', initialdir=initial_directory)

        if generation_directory_path : # Directory selected

            # Create directory if it doesn't already exist
            if not path.exists(generation_directory_path) :
                try :
                    generation_directory_path = self.data_file_helper.createDirectoryPath(generation_directory_path)
                except Exception, e :
                    directory_name = self.data_file_helper.splitPath(generation_directory_path)['name']
                    showerror('Directory Error', 'Error loading or creating directory \"'+directory_name+'\". Check file permissions.')
                    print >> sys.stderr, 'Error loading or creating directory:', e

            # Set path
            generation_directory_path = path.normpath(str(generation_directory_path))
            self.data_file_helper.setFileGenerationDirectory(generation_directory_path)
            location_descr = 'File generation in \"' + self.data_file_helper.getFileGenerationDirectoryName() + '\"'
            self.generation_directory_label_text.set(location_descr)

            # Set default when not already set via config options
            if not tool_option_values['default_file_generation_directory'] or not path.exists(tool_option_values['default_file_generation_directory']) or not tool_option_values['default_file_generation_directory_set'] :
                self.setToolOptions({ 'default_file_generation_directory' : generation_directory_path })

            # Enable the generate button
            self.generate_button.configure(state=tk.NORMAL)

    # Step 7 Method: Generate Data Files
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def calculateColourSchemeBoundaries(self) :

        # Find minimum and maximum data values and colour scheme interval
        if self.map_colour_scheme == '90%_range' :
            data_5th_percentile = min(self.grid_plot_statistics['region']['percentile_5th'])
            data_95th_percentile = max(self.grid_plot_statistics['region']['percentile_95th'])
            scheme_interval = (data_95th_percentile - data_5th_percentile)/9
            data_min = data_5th_percentile - scheme_interval
            data_max = data_95th_percentile + scheme_interval

        else : # fixed_range

            # Resolve selected parameter/group codes
            parameter_group_code = self.parameter_group_selection_map[self.parameter_group_text.get()]
            parameter_code = self.parameter_via_group_selection_map[parameter_group_code][self.parameter_via_group_text[parameter_group_code].get()]

            # Select fixed colour scheme via parameter codes and delta settings
            if self.utilise_delta.get() :
                if self.delta_as_percent.get() and self.parameter_fixed_range_colour_scheme[parameter_group_code][parameter_code].has_key('%delta') :
                    fixed_range_colour_scheme = self.parameter_fixed_range_colour_scheme[parameter_group_code][parameter_code]['%delta']
                else :
                    fixed_range_colour_scheme = self.parameter_fixed_range_colour_scheme[parameter_group_code][parameter_code]['delta']
            else :
                fixed_range_colour_scheme = self.parameter_fixed_range_colour_scheme[parameter_group_code][parameter_code]['value']

            # Prioritise min/max then first/last boundaries, use statistical min/max when neither provided
            if fixed_range_colour_scheme['min'] != None :
                data_min = fixed_range_colour_scheme['min']
            elif fixed_range_colour_scheme['first_boundary'] != None :
                data_min = None
            else :
                data_min = min(self.grid_plot_statistics['region']['minimum'])
            if fixed_range_colour_scheme['max'] != None :
                data_max = fixed_range_colour_scheme['max']
            elif fixed_range_colour_scheme['last_boundary'] != None :
                data_max = None
            else :
                data_max = max(self.grid_plot_statistics['region']['maximum'])

            # Resolve scheme interval and unresolved min/max
            if data_min == None and data_max == None :
                scheme_interval = (fixed_range_colour_scheme['last_boundary'] - fixed_range_colour_scheme['first_boundary'])/9.0
                data_min = fixed_range_colour_scheme['first_boundary'] - scheme_interval
                data_max = fixed_range_colour_scheme['last_boundary'] + scheme_interval
            elif data_min == None :
                scheme_interval = (data_max - fixed_range_colour_scheme['first_boundary'])/10.0
                data_min = fixed_range_colour_scheme['first_boundary'] - scheme_interval
            elif data_max == None :
                scheme_interval = (fixed_range_colour_scheme['last_boundary'] - data_min)/10.0
                data_max = fixed_range_colour_scheme['last_boundary'] + scheme_interval
            else :
                scheme_interval = (data_max - data_min)/11.0

        # Return colour scheme boundary values
        if scheme_interval :
            return np.arange(data_min, data_max+0.1*scheme_interval, scheme_interval)
        else :
            return np.arange(data_min-1.0, data_max+1.2, 0.2)

    # Shared Method: Adjust Colour Scheme Zero Boundaries (used in menu colour edit and grid plot methods)
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def adjustColourSchemeZeroBoundaries(self, colour_scheme_boundaries) :

        if self.map_colour_scheme == '90%_range' : # shift left method
            colour_scheme_boundaries_zero_index = (colour_scheme_boundaries >= 0).nonzero()[0][0]
            colour_scheme_boundaries -= colour_scheme_boundaries[colour_scheme_boundaries_zero_index]

        else : # fixed_range: minimal stretch method

            # Resolve selected parameter/group codes
            parameter_group_code = self.parameter_group_selection_map[self.parameter_group_text.get()]
            parameter_code = self.parameter_via_group_selection_map[parameter_group_code][self.parameter_via_group_text[parameter_group_code].get()]

            # Select fixed colour scheme via parameter codes and delta settings
            if self.utilise_delta.get() :
                if self.delta_as_percent.get() and self.parameter_fixed_range_colour_scheme[parameter_group_code][parameter_code].has_key('%delta') :
                    fixed_range_colour_scheme = self.parameter_fixed_range_colour_scheme[parameter_group_code][parameter_code]['%delta']
                else :
                    fixed_range_colour_scheme = self.parameter_fixed_range_colour_scheme[parameter_group_code][parameter_code]['delta']
            else :
                fixed_range_colour_scheme = self.parameter_fixed_range_colour_scheme[parameter_group_code][parameter_code]['value']

            # Resolve colour scheme zero boundaries
            first_index = int(fixed_range_colour_scheme['first_boundary'] != None and fixed_range_colour_scheme['min'] == None)
            last_index = 11 - int(fixed_range_colour_scheme['last_boundary'] != None and fixed_range_colour_scheme['max'] == None)
            if colour_scheme_boundaries.round(12).min() >= 0 :
                data_min = 0.0
                scheme_interval = (colour_scheme_boundaries[last_index] - data_min)/last_index
                data_max = colour_scheme_boundaries[last_index] + scheme_interval*(11 - last_index)
                colour_scheme_boundaries_zero_index = 0
            elif colour_scheme_boundaries.round(12).max() <= 0 :
                data_max = 0.0
                scheme_interval = (data_max - colour_scheme_boundaries[first_index])/(11 - first_index)
                data_min = colour_scheme_boundaries[first_index] - scheme_interval*first_index
                colour_scheme_boundaries_zero_index = 11
            else :
                first_positive_index = (colour_scheme_boundaries >= 0).nonzero()[0][0]
                lower_stretch = None
                upper_stretch = None
                if first_positive_index < last_index :
                    lower_stretch = (last_index - first_index)*colour_scheme_boundaries[first_positive_index]/(last_index - first_positive_index)
                if first_positive_index > first_index + 1 :
                    upper_stretch = (last_index - first_index)*colour_scheme_boundaries[first_positive_index - 1]/(first_index - first_positive_index + 1)
                if upper_stretch == None or (lower_stretch != None and round(lower_stretch, 12) <= round(upper_stretch, 12)) :
                    colour_scheme_boundaries[first_index] -= lower_stretch
                    colour_scheme_boundaries_zero_index = first_positive_index
                else :
                    colour_scheme_boundaries[last_index] += upper_stretch
                    colour_scheme_boundaries_zero_index = first_positive_index - 1
                scheme_interval = (colour_scheme_boundaries[last_index] - colour_scheme_boundaries[first_index])/(last_index - first_index)
                data_min = colour_scheme_boundaries[first_index] - scheme_interval*first_index
                data_max = colour_scheme_boundaries[last_index] + scheme_interval*(11 - last_index)
            colour_scheme_boundaries = np.arange(data_min, data_max+0.1*scheme_interval, scheme_interval).round(12)

        return (colour_scheme_boundaries_zero_index, colour_scheme_boundaries)

    ## Generic Methods ####################################################################################################################################################

    # Generic Method: Ensures menu selection triggers entry field validation focusout events
项目:python    作者:hienha    | 项目源码 | 文件源码
def go(self):                # determine which page to return
        self.cookies = {}
        self.error = ''
        form = FieldStorage()
        if form.keys() == []:
            self.showForm()
            return

        if form.has_key('person'):
            self.who = capwords(strip(form['person'].value))
            if self.who == '':
                self.error = 'Your name is required. (blank)'
        else:
            self.error = 'Your name is required. (missing)'

        if form.has_key('cookie'):
            self.cookies['user'] = unquote(strip( \
                form['cookie'].value))
        else:
            self.cookies['user'] = ''

        self.langs = []
        if form.has_key('lang'):
            langdata = form['lang']
            if type(langdata) == type([]):
                for eachLang in langdata:
                    self.langs.append(eachLang.value)
            else:
                self.langs.append(langdata.value)
        else:
            self.error = 'At least one language required.'

        if form.has_key('upfile'):
            upfile = form["upfile"]
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''

        if not self.error:
            self.doResults()
        else:
            self.showError()
项目:python    作者:hienha    | 项目源码 | 文件源码
def go(self):
                self.error = ''

                form = FieldStorage()

                if form.keys() == []:
                    #s('calling showForm()\n')
                    self.showForm()
                    return

                if form.has_key('person'):
                        self.who = capwords(strip(form['person'].value))
                        if self.who == '':
                                self.error = 'Your name is required. (blank)'
                else:
                        self.error = 'Your name is required. (missing)'

                if form.has_key('cookie'):
                        self.cookies['user'] = unquote(strip(form['cookie'].value))
                else:
                        self.cookies['user'] = ''

                self.langs = []
                if form.has_key('lang'):
                        langdata = form['lang']
                        if type(langdata) == type([]):
                                for eachLang in langdata:
                                        self.langs.append(eachLang.value)
                        else:
                                self.langs.append(langdata.value)
                else:
                        self.error = 'At least one language required.'

                if form.has_key('upfile'):
                        upfile = form["upfile"]
                        self.fn = upfile.filename or ''
                        #s('filename is %s??\n' % self.fn)
                        if upfile.file:
                                self.fp = upfile.file
                        else:
                                self.fp = StringIO('(no data)')
                else:
                        self.fp = StringIO('(no file)')
                        self.fn = ''

                if not self.error:
                        #s('calling doResults()\n')
                        self.doResults()
                else:
                        #s('calling showError()\n')
                        self.showError()