-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.py
305 lines (277 loc) · 9.19 KB
/
utility.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#UTILITY METHODS
import logging
import os
log = logging.getLogger('geocachepython')
def DMToDD(string):
"""Converts coordinates in Decimal Minute format to Decimal Degree.
Returned as a string with latitude and longitude seperated by a space
>>> DMToDD('N 44 19.395 W 076 32.595')
'44.32325 -76.54325'
>>> DMToDD('N44 23.1 W72')
string wrong length
-1
"""
if len(string) == 24:
negLat = 0
negLon = 0
if string[:2] == "N ":
pass
elif string[:2] == "S ":
negLat = 1
else:
log.error("Error: No N or S at start of coords")
return -1
lat = int(string[2:4])
minute = float(string[5:11])
minute /= 60
lat += minute
if negLat == 1:
lat = -lat
if string[12:14] == "W ":
negLon = 1
elif string[12:14] == "E ":
pass
else:
log.error("Error: No W or E or otherwise invalid format")
return -1
lon = int(string[14:17])
minute = float(string[18:24])
minute /= 60
lon += minute
if negLon == 1:
lon = -lon
return "%s %s" % (lat, lon)
elif len(string) == 10:
negLat = 0
if string[:1] == "N":
pass
elif string[:1] == "S":
negLat = 1
else:
log.error("Error: No N or S at start of coords")
return -1
lat = int(string[1:3])
minute = float(string[4:10])
minute /= 60
lat += minute
if negLat == 1:
lat = -lat
return "%s" % (lat)
elif len(string) == 11:
negLon = 0
if string[:1] == "W":
negLon = 1
elif string[:1] == "E":
pass
else:
log.error("Error: No W or E or otherwise invalid format")
return -1
lon = int(string[1:4])
minute = float(string[5:11])
minute /= 60
lon += minute
if negLon == 1:
lon = -lon
return "%s" %lon
def DDToDM(dd, latOrLon=0):
"""Converts coordinates in Decimal Degree format to Decimal Minutes for output.
Returns string in pretty output format ex. 'N44 13.323 W76 32.322'
latOrLon 1-latitude (N or S)
2-longitude (E or W)
>>> DDToDM(10.123456789)
'10 7.407'
>>> DDToDM(44.32323, 1)
'N44 19.394'
>>> DDToDM(-76.54321, 2)
'W76 32.593'
"""
degree = int(float(dd))
decimal = float(dd) % 1
if degree < 0:
decimal = 1 - decimal
minutes = decimal * 60
DM = "%d %0.3f" % (degree, minutes)
if latOrLon == 1:
if degree > 0:
DM = "N" + DM
else:
DM = "S" + DM[1:]
elif latOrLon == 2:
if degree > 0:
DM = "E" + DM
else:
DM = "W" + DM[1:]
return DM
def toBool(value):
"""Converts string to bool"""
if value == "True":
return True
elif value == "False":
return False
else:
#TODO raise error
raise Exception('Error converting to bool')
def convertToRange(diff):
"""Converts a difficulty or terrain rating (1,1.5-5) to integer (1-9)
>>> convertToRange(1.5)
2
>>> convertToRange(5)
9
"""
return int(float(diff) * 2 - 1)
def initializeMatrix():
"""Initializes D/T Matrix
>>> initializeMatrix()
[[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]
"""
matrix = []
for i in range(9):
matrix.append([0]*9)
return matrix
def outputMatrix(matrix):
"""Prints D/T Matrix"""
numOnes = 0
print " 1 1.5 2 2.5 3 3.5 4 4.5 5"
for i in range(9):
print float(i+2) / 2, "",
for j in range(9):
print matrix[i][j], " ",
if matrix[i][j] == 1:
numOnes = numOnes + 1
print
print "You've found", numOnes, "of the possible 81 difficulty/terrain combinations.", 81-numOnes, "to go!"
def stateCode(states):
"""Returns a string of state codes for each entry in given list of states.
Prints an error to the screen if a state is not recognised
>>> stateCode(['Utah', 'Blah'])
ERROR: State not recognised: Blah
'UT'
"""
stateList = ""
for state in states:
stateDict = {
"Utah": "UT",
"Vermont": "VT",
"Washington": "WA",
"Alabama": "AL",
"Louisiana": "LA",
"Ohio": "OH",
"Alaska": "AK",
"Maine": "ME",
"Oklahoma": "OK",
"Arizona": "AZ",
"Maryland": "MD",
"Oregon": "OR",
"Arkansas": "AR",
"Massachusetts": "MA",
"Pennsylvania": "PA",
"California": "CA",
"Michigan": "MI",
"Rhode Island": "RI",
"Colorado": "CO",
"Minnesota": "MN",
"South Carolina": "SC",
"Connecticut": "CT",
"Mississippi": "MS",
"South Dakota": "SD",
"Delaware": "DE",
"Missouri": "MO",
"Tennessee": "TN",
"Florida": "FL",
"Montana": "MT",
"Texas": "TX",
"Georgia": "GA",
"Nebraska": "NE",
"Hawaii": "HI",
"Nevada": "NV",
"Idaho": "ID",
"New Hampshire": "NH",
"Virginia": "VA",
"Illinois": "IL",
"New Jersey": "NJ",
"Indiana": "IN",
"New Mexico": "NM",
"West Virginia": "WV",
"Iowa": "IA",
"New York": "NY",
"Wisconsin": "WI",
"Kansas": "KS",
"North Carolina": "NC",
"Wyoming": "WY",
"Kentucky": "KY",
"North Dakota": "ND"
}
if (stateDict.get(state, "") != ""):
stateList = stateList + (stateDict.get(state))
else:
log.error("State not recognised: %s" %state)
return stateList
def countryCode(countries):
"""Returns a string of country codes for each entry in given list of countries.
Prints error to screen if a country is not recognised
>>> countryCode(['Canada', 'Blah'])
ERROR: Country not recognised: Blah
'CA'
"""
countryList = ""
for country in countries:
countryDict = {
"Canada": "CA",
"United States": "US"
}
if (countryDict.get(country, "") != ""):
countryList = countryList + (countryDict.get(country))
else:
log.error("Country not recognised: %s" %country)
return countryList
#more country codes at http://www.iso.org/iso/english_country_names_and_code_elements
def BC_RDName_to_code(name):
BCDict = {
'Alberni-Clayoquot': 'AC', 'Bulkley-Nechako': 'BN', 'Capital': 'CP', 'Cariboo': 'CA',
'Central Coast': 'CC', 'Central Kootenay': 'CK', 'Central Okanagan': 'CO',
'Columbia-Shuswap': 'CS', 'Comox Valley': 'CV', 'Cowichan Valley': 'CW', 'East Kootenay': 'EK',
'Fraser Valley': 'FV', 'Fraser-Fort George': 'FG', 'Greater Vancouver': 'GV',
'Kitimat-Stikine': 'KS', 'Kootenay Boundary': 'KB', 'Mount Waddington': 'MW', 'Nanaimo': 'NA',
'North Okanagan': 'NO', 'Northern Rockies': 'NR', 'Okanagan-Similkameen': 'OS',
'Peace River': 'PR', 'Powell River': 'PW', 'Skeena-Queen Charlotte': 'QC',
'Squamish-Lillooet': 'SL', 'Stikine': 'ST', 'Strathcona': 'SR',
'Sunshine Coast': 'SC', 'Thompson-Nicola': 'TN'
}
if (BCDict.get(name, "") != ""):
return BCDict.get(name)
else:
raise Exception("Not a valid county name")
def viewCacheList(cacheList):
"""View Cache List"""
#If lots of caches, get users confirmation
if len(cacheList) > 20:
print "List is long -", len(cacheList), "caches."
choice = raw_input("Are you sure you wish to view the full list? (y/Y)")
if choice != "y" and choice != "Y":
return
#display caches
for cache in cacheList:
print "----------------------------------"
print cache.cacheName, "by", cache.owner, "hidden on", cache.cacheDate, "in", cache.state
print "D:", cache.difficulty, "T:", cache.terrain, cache.cacheType, cache.container
print
return
def saveFileDialog(fileType, filename=''):
#TODO: give more options, change directory
#TODO: more leeway
path = os.getcwd() # gets current working directory
#fileList = []
#dirList = os.listdir(path)
if filename == '':
print "The current path is:", path
print "You're saving a file of type", fileType
filename = raw_input("Please enter a filename (without the extension): ")
return path + os.sep + filename + '.' + fileType
# Check if running as a program
if __name__ == '__main__':
# test myself
import doctest
doctest.testmod()
else:
# No, I must have been imported as a module
pass