source: TI03-DataExtractor/branches/titania_install/pygss/common.py @ 1520

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI03-DataExtractor/branches/titania_install/pygss/common.py@1610
Revision 1520, 6.2 KB checked in by astephen, 14 years ago (diff)

This is the live version on titania - changes have been made so safest to SVN it.

Line 
1#   Copyright (C) 2004 CCLRC & NERC( Natural Environment Research Council ).
2#   This software may be distributed under the terms of the
3#   Q Public License, version 1.0 or later. http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
4
5"""
6common.py
7=========
8
9Holds common functions and classes used in the package.
10
11"""
12
13# Import python modules
14import os
15
16# Import package modules
17from serverConfig import *
18
19# Set up commmon variables. These are CAPITALISED to
20# improve visibility in other modules.
21
22STAGES=["DatasetPage", "VariablesPage", "RenderingOptionsPage", "PlotConfigPage", "ResultsPage"]
23
24DOMAIN_PARAMS=("start_time", "end_time", "time_interval", "horiz_domain", 
25                      "resolution", "vertical_units", "vertical_domain", 
26                       "outputFormat")
27
28# Set up common functions
29
30def isUndefined(dict, item): 
31    """
32    Function that returns 1 if item is not a key in dict or
33    is defined as None in dict.
34    """
35    if dict.has_key(item):
36        if dict[item]!=None:
37            return 0
38    return 1
39   
40   
41def keyPatternMatch(dct, pattern):
42    """
43    Returns 1 if one or more keys in the dictionary 'dct' match the
44    pattern provided using string.find(). Returns 0 otherwise.
45    """
46    for key in dct.keys():
47        if key.find(pattern)>-1:
48            return 1
49    return 0
50   
51
52def getValuesInRange(start, end, array):
53    """
54    getValuesInRange function - takes a start and end value and returns the
55    values in the array that are between them.
56    """
57    # check all are floats
58    array=map(lambda x: float(x), list(array))
59    if array[0]>array[-1]: array.reverse()
60    if start>end:  (start, end)=(end, start)
61    (start, end)=(float(start), float(end))
62    rtarray=[]
63    for i in array:
64        if i>=start and i<=end:
65            rtarray.append(i)
66    return rtarray
67
68
69def translateURI(uri):
70    """
71    Takes a URL and returns the location of the file on the local network
72    or takes a local path and returns the URL of the file/directory.
73    """
74    if uri.find("http")>-1:
75        newpath=uri.replace(OUTPUT_DIR_URL, OUTPUT_DIR)
76    else:
77        newpath=uri.replace(OUTPUT_DIR, OUTPUT_DIR_URL)
78    return newpath
79
80
81def getBestName(v):
82        """
83        Returns the most appropriate variable or axis name for a long name listing.
84        """       
85        if not hasattr(v, "standard_name"):
86            if not hasattr(v, "long_name"):
87                   if not hasattr(v, "title"):
88                       if not hasattr(v, "name"):
89                           if hasattr(v, "id"):
90                               name=v.id
91                           else:
92                               name="unnamed_variable"
93                       else:
94                           name=v.name
95                   else:
96                       name=v.title
97            else:
98                   name=v.long_name
99        else:
100               name=v.standard_name
101        # Fix name to remove leading asterisks and lower case surface start.
102        name=name.replace("_", " ")
103        if name[:2]=="**": name=(name[2:]).strip()
104        if name[:7]=="surface": name=(name[7:]).strip()
105        return name
106
107
108def minmax(array):
109    """
110    Returns the min and max of any 1-D array.
111    """
112    mn=min(array)
113    mx=max(array)
114    return (mn,mx)
115
116
117def deUnicodeObject(obj):
118    """
119    Returns the object identical except unicode strings are all
120    converted to normal strings.
121    """
122    tupleFound=None
123    if type(obj)==type((1,2)): 
124        tupleFound=1
125        obj=list(obj)
126
127    if type(obj)==type([]):
128        rtobj=[]
129        for i in obj:
130            if type(i) in (type([]), type((1,2))):
131                rtobj.append(deUnicodeObject(i)) 
132            elif type(i)==type(u""):
133                rtobj.append(str(i))
134            else:
135                rtobj.append(i)
136        if tupleFound==1: rtobj=tuple(rtobj)
137
138    elif type(obj)==type(u""):
139        rtobj=str(obj)
140    else: 
141        rtobj=obj
142    return rtobj
143
144def overlap(list1, list2):
145    """
146    overlap function - returns a list of overlapping items in list1 and list2.
147    Otherwise returns None.
148    """ 
149    rtlist=[]
150    for i in list1:
151       if i in list2: rtlist.append(i)
152
153    if len(rtlist)>0:
154        return rtlist
155    else:
156        return None
157
158def makeDirsAndPerms(basedir, dirs, permissions, owner, verbose="no"):
159    """
160    A function for making directories recursively and setting permissions/ownership.
161    """
162    if type(dirs)==str: dirs=[dirs]
163    dirs=[basedir]+list(dirs)
164    dir=None
165
166    while len(dirs)>0:
167
168        if dir:
169            dir=os.path.join(dir, dirs[0])
170        else:
171            dir=dirs[0]
172        dirs=dirs[1:]
173
174        if not os.path.exists(dir):
175            if verbose=="yes":   print "Making directory:", dir
176            os.mkdir(dir)
177            os.chmod(dir, permissions)
178            os.system('/bin/chown %s %s' % (owner, dir))
179
180    return
181
182
183
184def checkSubDirectory(user=None):
185    """
186    checkSubDirectory method - checks if the required sub-directory exists
187    to write the output and if not it creates it.
188    """
189    if SECURITY_MODEL=="badc":
190        reqDirScript="/home/badc/software/infrastructure/make_user_request_dir"
191        os.system("%s %s" % (reqDirScript, user))
192    else:
193        makeDirsAndPerms(OUTPUT_DIR, user, OUTPUT_DIR_PERMISSION, "%s.%s" %
194                                               (OUTPUT_FILE_USER, OUTPUT_FILE_GROUP))
195
196    if user==None or user=="None":   user="anonymous"
197    outputDir=os.path.join(OUTPUT_DIR, user, "dx_output")
198    if not os.path.isdir(outputDir):
199        makeDirsAndPerms(OUTPUT_DIR, (user, "dx_output"), OUTPUT_DIR_PERMISSION, "%s.%s" %
200                                           (OUTPUT_FILE_USER, OUTPUT_FILE_GROUP))
201    return outputDir
202
203
204def fixFilePermissions(path):
205    """
206    Fixes permissions on a file.
207    """
208    os.chmod(path, OUTPUT_FILE_PERMISSION)
209    os.system("chown %s.%s %s" % (OUTPUT_FILE_USER, OUTPUT_FILE_GROUP, path))
210
211   
212# Set up common classes
213class RedirectStdout:
214    """
215    RedirectStdout class - used to direct standard output away from
216    the screen in CGI scripts.
217    """
218
219    def write(self, item):
220        """
221        write method - allows dummy standard out to work.
222        """
223        pass
224
225    def flush(self):
226        """
227        Method to do nothing, again!
228        """
229        pass
Note: See TracBrowser for help on using the repository browser.