Attachment 'sstable-1.0.3.py'
Download 1
2 """
3 MoinMoin - sstable a Processor for spread sheet calculations using only Python.
4
5 @license: GNU GPL, see COPYING for details.
6
7 PURPOSE:
8 This processor is used to do some spread sheet calculation in a regular wiki
9 table using only Python. The first column/first line coordinate is A0.
10
11 This code is based on the spreadsheet code posted by Raymond Hettinger and
12 Richard Copeland at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355045
13 It is also based on the sctable parser by Reimar Bauer (R.Bauer AT fz-juelich.de).
14
15 CALLING SEQUENCE:
16 {{{
17 #!sstable [-column_header, -row_header, -show_formular, -format,
18 -input_separator, -output_separator ]
19 }}}
20
21 OPTIONAL INPUTS:
22 -column_header: additional in the result the column header is shown
23 -row_header: additional in the result the line number header is shown
24 -show_formular: if set the formular instead of the result is shown,
25 data is arranged in textmode. Blanks in formulars are removed
26 -format: is used to the set the number of digits for the column values
27 -input_separator: used to read tables delimitted by something other than the
28 default '||'
29 -output_separator: used to write tables delimitted by something other than the
30 default '||'
31
32
33 EXAMPLE:
34 {{{
35 SUM over columns}}}
36 {{{
37 #!sstable
38 ||1||2||=A0+B0||
39 ||10||20||=@sum(A1:B1)||
40 }}}
41
42 RESULT:
43 ||<)>1.00||<)>2.00||<)>3.00||
44 ||<)>10.00||<)>20.00||<)>30.00||
45 -----
46
47 {{{
48 cell B1 no data}}}
49
50 {{{
51 #!sstable
52 ||A||B||C||D||
53 ||1||||2||=A1+C1||
54 }}}
55
56 RESULT:
57 ||<(>A||<(>B||<(>C||<(>D||
58 ||<)>1.00||<)>||<)>2.00||<)>3.00||
59
60 -----
61 {{{
62 SUM over rows}}}
63 {{{
64 #!sstable
65 ||1||2||=A0+B0||
66 ||10||20||30||
67 ||=@sum(A0:A1)||=@sum(B0:B1)||=@sum(C0:C1)||
68 }}}
69
70 RESULT:
71 ||<)>1.00||<)>2.00||<)>3.00||
72 ||<)>10.00||<)>20.00||<)>30.00||
73 ||<)>11.00||<)>22.00||<)>33.00||
74
75 -----
76 {{{
77 SUM over rows and columns}}}
78 {{{
79 #!sstable
80 ||A||B||C||
81 ||1||2||=A1+B1||
82 ||10||20||=@sum(A2:B2)||
83 ||=@sum(A1:A2)||=@sum(B1:B2)||=@sum(C1:C2)||
84 }}}
85
86 RESULT:
87 ||<(>A||<(>B||<(>C||
88 ||<)>1.00||<)>2.00||<)>3.00||
89 ||<)>10.00||<)>20.00||<)>30.00||
90 ||<)>11.00||<)>22.00||<)>33.00||
91
92 -----
93 {{{
94 -column_header}}}
95 {{{
96 #!sstable -column_header
97 ||1||2||
98 ||3||4||
99 ||5||6||
100 }}}
101
102 RESULT:
103 ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||
104 ||<)>1.00||<)>2.00||
105 ||<)>3.00||<)>4.00||
106 ||<)>5.00||<)>6.00||
107
108
109 -----
110 {{{
111 -row_header}}}
112 {{{
113 #!sstable -row_header
114 ||1||2||
115 ||3||4||
116 ||5||6||
117 }}}
118
119 RESULT:
120 ||<)5%#CCCCCC>'''0'''||<)>1.00||<)>2.00||
121 ||<)5%#CCCCCC>'''1'''||<)>3.00||<)>4.00||
122 ||<)5%#CCCCCC>'''2'''||<)>5.00||<)>6.00||
123
124 -----
125 {{{
126 -column_header -row_header}}}
127 {{{
128 #!sstable -column_header -row_header
129 ||1||2||
130 ||3||4||
131 ||5||6||
132 }}}
133
134 RESULT:
135 ||<:5%#CCCCCC> ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||
136 ||<)5%#CCCCCC>'''0'''||<)>1.00||<)>2.00||
137 ||<)5%#CCCCCC>'''1'''||<)>3.00||<)>4.00||
138 ||<)5%#CCCCCC>'''2'''||<)>5.00||<)>6.00||
139
140 -----
141 {{{
142 -show_formular -column_header -row_header}}}
143 {{{
144 #!sstable -show_formular -column_header -row_header
145 ||m||p||
146 ||1||=A1 * 5||
147 ||2||=A2-3||
148 ||3||4||
149 }}}
150
151 RESULT:
152 ||<:5%#CCCCCC> ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||
153 ||<)5%#CCCCCC>'''0'''||<(>m||<(>p||
154 ||<)5%#CCCCCC>'''1'''||<(>1||<(>=A1*5||
155 ||<)5%#CCCCCC>'''2'''||<(>2||<(>=A2-3||
156 ||<)5%#CCCCCC>'''3'''||<(>3||<(>4||
157
158 -----
159 {{{
160 -column_header and blanks in cells}}}
161 {{{
162 #!sstable -column_header
163 ||Name Vorname|| || || 3 || || 5||
164 ||Name Vorname|| 1 || 2 || || 4 || 5||
165 ||Name Vorname|| 1 || 2 || || || 5||
166 }}}
167
168 RESULT:
169 ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||<:#CCCCCC>'''C'''||<:#CCCCCC>'''D'''||<:#CCCCCC>'''E'''||<:#CCCCCC>'''F'''||
170 ||<(>Name Vorname|| || ||<)>3.00|| ||<)>5.00||
171 ||<(>Name Vorname||<)>1.00||<)>2.00|| ||<)>4.00||<)>5.00||
172 ||<(>Name Vorname||<)>1.00||<)>2.00|| || ||<)>5.00||
173
174 -----
175 {{{
176 -format 1,1}}}
177 {{{
178 #!sstable -format 1,1
179 ||1||2||
180 ||3||4||
181 ||=@sum(a0:a1)||=a2*4||
182 }}}
183
184 RESULT:
185 ||<)>1.0||<)>2.0||
186 ||<)>3.0||<)>4.0||
187 ||<)>4.0||<)>16.0||
188
189 -----
190 {{{ useage of variable names -show_formular -column_header -row_header
191 }}}
192 {{{#!sstable -show_formular -column_header -row_header
193 ||A||B||C||
194 ||1||{two}2||=A1+two||
195 ||10||20||=@sum(A2:B2)||
196 ||=@sum(A1:A2)||=@sum(B1:B2)||=@sum(C1:C2)||
197 }}}
198
199
200 RESULT:
201 ||<:5%#CCCCCC> ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||<:#CCCCCC>'''C'''||
202 ||<)5%#CCCCCC>'''0'''||<(>A||<(>B||<(>C||
203 ||<)5%#CCCCCC>'''1'''||<(>1||<(>{two}2||<(>=A1+two||
204 ||<)5%#CCCCCC>'''2'''||<(>10||<(>20||<(>=@sum(A2:B2)||
205 ||<)5%#CCCCCC>'''3'''||<(>=@sum(A1:A2)||<(>=@sum(B1:B2)||<(>=@sum(C1:C2)||
206
207 and if we calculate [[BR]]
208 RESULT:
209 {{{#!sstable -column_header -row_header
210 ||A||B||C||
211 ||1||{two}2||=A1+two||
212 ||10||20||=@sum(A2:B2)||
213 ||=@sum(A1:A2)||=@sum(B1:B2)||=@sum(C1:C2)||
214 }}}
215 -----
216 {{{color in cells
217 }}}
218 {{{#!sstable
219 ||<:rowbgcolor=lightcyan>'''A'''||<:>'''B'''||<:>'''C'''||
220 ||<)#dddddd>1||<)#dddddd>{two}2||<)#cccccc>=A1+two||
221 ||<(>10||<)>20||<:#dddddd>=@sum(A2:B2)||
222 ||<rowbgcolor="#cc99ff">=@sum(A1:A2)||=@sum(B1:B2)||<bgcolor=magenta>=@sum(C1:C2)||
223 }}}
224
225 RESULT:
226 ||<:rowbgcolor=lightcyan>'''A'''||<:>'''B'''||<:>'''C'''||
227 ||<)#dddddd>1.00||<)#dddddd>2.00||<)#cccccc>3.00||
228 ||<(>10.00||<)>20.00||<:#dddddd>30.00||
229 ||<rowbgcolor="#cc99ff">11.00||22.00||<bgcolor=magenta>33.00||
230 -----
231 {{{delimit input with ','
232 }}}
233 {{{
234 #!sstable -column_header -input_separator ,
235 ,1,2,
236 ,3,4,
237 ,5,6,
238 }}}
239
240 RESULT:
241 ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||
242 ||<)>1.00||<)>2.00||
243 ||<)>3.00||<)>4.00||
244 ||<)>5.00||<)>6.00||
245 -----
246 {{{delimit input and output with ','
247 }}}
248 {{{
249 #!sstable -column_header -row_header -input_separator , -output_separator ,
250 1,2
251 3,4
252 5,6
253 }}}
254
255 RESULT:
256 {{{
257 ,''' ''','''A''','''B''',
258 ,'''0''', 1.00, 2.00,
259 ,'''1''', 3.00, 4.00,
260 ,'''2''', 5.00, 6.00,
261 }}}
262 -----
263
264
265
266 PROCEDURE:
267 All formulars have to start by a "=" sign.
268 All formulars do not need to start with a "@", but they can.
269
270 Please remove the version number from the routine name!
271
272
273 MODIFICATION:
274 @copyright: 2006-03-25 by Andrew Shewmaker (agshew AT gmail) sstable-1.0
275
276 1.0.3: improved compatibility with other spreadsheets - Andrew Shewmaker
277 1.0.2: improved cell range functions - Andrew Shewmaker
278 correct special character handling - Reimar Bauer
279 1.0.1: use unicode function - Andrew Shewmaker
280 1.0: based on sctable-1.5.2-5 by Reimar Bauer (R.Bauer AT fz-juelich.de)
281 """
282
283 Dependencies = []
284 import re
285 from math import *
286 from MoinMoin.parser import wiki
287 from MoinMoin.action import AttachFile
288 from MoinMoin.Page import Page
289 from MoinMoin import wikiutil
290
291 class SpreadSheet:
292 _cells = {}
293 tools = {}
294 _cache = None
295 def __init__(self):
296 self.tools.update({'__builtins__':None})
297 pmath = { 'ceil':ceil, 'floor':floor, \
298 'fabs':fabs, \
299 'fmod':fmod, 'modf':modf, \
300 'frexp':frexp, 'ldexp':ldexp, \
301 'exp':exp, \
302 'log':log, 'log10':log10, \
303 'pow':pow, \
304 'sqrt':sqrt, \
305 'acos':acos, 'asin':asin, 'atan':atan, 'atan2':atan2, \
306 'cos':cos, 'sin':sin, 'tan':tan, \
307 'cosh':cosh, 'sinh':sinh, 'tanh':tanh, \
308 'hypot':hypot, \
309 'degrees':degrees, 'radians':radians, \
310 'pi':pi, 'e':e, \
311 'cmp':cmp, \
312 'len':len, \
313 'round':round, \
314 'hex':hex, 'oct':oct, \
315 'max':self.max, 'min':self.min, \
316 'sum':self.sum, 'average':self.average, 'median':self.median, \
317 }
318 self.tools.update(pmath)
319
320 def getformula(self, key):
321 return self._cells[key]
322
323 def max(self, keys):
324 return max(map(self.__getitem__, self.cellrange(keys)))
325
326 def min(self, keys):
327 return min(map(self.__getitem__, self.cellrange(keys)))
328
329 def sum(self, keys):
330 return sum(map(self.__getitem__, self.cellrange(keys)))
331
332 def average(self, keys):
333 cells = map(self.__getitem__, self.cellrange(keys))
334 return sum(cells)/float(len(cells))
335
336 def median(self, keys):
337 cells = map(self.__getitem__, self.cellrange(keys))
338 n = len(cells)
339 midpt = n/2
340 if (n%2):
341 return cells[midpt]
342 else:
343 return (cells[midpt-1] + cells[midpt])/2.0
344
345 def __setitem__(self, key, formula):
346 self._cells[key.lower()] = formula
347
348 def __getitem__(self, key):
349 bCache = self._cache is None
350 if bCache: self._cache = {}
351 while True:
352 try:
353 if ( self._cells[key] == None or self._cells[key] == ''):
354 rv = ''
355 else:
356 rv = eval(self._cells[key], self.tools, self._cache)
357 break
358 except NameError, ne:
359 name = ne.args[0][6:-16] # Extract name from NameError
360 if name in self._cells:
361 self._cache[name] = self[name]
362 else:
363 self._cache[key] = None
364 self._cells[key] = None
365 except SyntaxError, se:
366 rv = self._cells[key]
367 break
368 except TypeError, te:
369 rv = 'type error: ' + self._cells[key] + ', ' + str(te)
370 break
371
372 if bCache: self._cache = None
373 return rv
374
375 def cellrange(self, keys):
376 m = re.search('([a-z]+)(\d+):([a-z])+(\d+)?', keys)
377
378 result = []
379 if m == None:
380 result = re.split(',', keys)
381 return result
382
383 (c1, r1, c2, r2) = m.groups()
384
385 mincol = min(c1, c2)
386 maxcol = max(c1, c2)
387 minrow = min(int(r1), int(r2))
388 maxrow = max(int(r1), int(r2))
389
390 col_names = 'abcdefghijklmnopqrstuvwxyz'
391 for i in range(col_names.index(mincol), col_names.index(maxcol)+1):
392 for j in range(minrow, maxrow+1):
393 result.append(col_names[i] + str(j))
394
395 return result
396
397
398 class Parser:
399
400 def __init__(self, raw, request, **kw):
401 self.eval_re = re.compile('^=')
402 self.range_re = re.compile('(\w+).(\w+:\w+).')
403 self.var_re = re.compile('\{(.+)\}(.+)')
404 self.num_re = re.compile('^(-)|(\d*)\.?[\d]*$')
405 self.ss = SpreadSheet()
406 self.raw = raw
407 self.request = request
408 self.form = request.form
409 self._ = request.getText
410 self.kw = []
411 for arg in kw.get('format_args','').split():
412 self.kw.append(arg)
413
414
415 def format(self, formatter):
416 lines = self.raw.split('\n')
417
418 kw = self.kw
419 column_header = 0
420 row_header = 0
421 show_formular = 0
422 format = ''
423 insep = '||'
424 outsep = '||'
425 right_format = '<)>'
426 left_format = '<(>'
427 colheader_format = '<:#CCCCCC>'
428 rowheader_format = '<)5%#CCCCCC>'
429 zt = 0
430 for test in kw:
431 if test == '-column_header': column_header = 1
432 if test == '-row_header': row_header = 1
433 if test == '-show_formular': show_formular = 1
434 if test == '-format': format = re.split(',', kw[zt+1])
435 if test == '-input_separator': insep = kw[zt+1]
436 if test == '-output_separator':
437 outsep = kw[zt+1]
438 right_format = ''
439 left_format = ''
440 colheader_format = ''
441 rowheader_format = ''
442 zt += 1
443
444 formats = {} # { (row,col): '<wikiformat>', ... }
445 r = 0 # row counter
446 c = 0 # column counter
447 col_names = 'abcdefghijklmnopqrstuvwxyz'
448 maxcolumns = 0
449
450 for txt in lines:
451 txt = txt.lstrip()
452 if ( txt == '' ):
453 continue
454 columns = txt.split(insep)
455 if re.search('^' + insep, txt):
456 columns = columns[1:]
457 if re.search(insep + '$', txt):
458 columns = columns[:-1]
459
460 if ( len(columns) > maxcolumns):
461 maxcolumns = len(columns)
462
463 c = 0
464 for cell in columns:
465 cellname = col_names[c]+str(r)
466 cell = cell.strip()
467
468 # check for wiki formatting string at beginning of ss data: "<format>..."
469 if cell.startswith('<'):
470 p = cell.find('>') + 1
471 if p > 1:
472 formats[(r,c)] , cell = cell[:p] , cell[p:]
473 cell = cell.strip()
474 else:
475 formats[(r,c)] = ""
476
477 # variable names
478 m = self.var_re.search(cell)
479 if m != None:
480 cell = m.group(2).lower()
481 self.ss[m.group(1)] = cellname
482
483 if self.eval_re.match(cell):
484 # case insensitivity for everything after an '='
485 cell = cell.lower()
486
487 # cell ranges are parsed as strings
488 m = self.range_re.search(cell)
489 if m != None:
490 cell = m.group(1) + "('" + m.group(2) + "')"
491
492 # '=' and '@' are unnecessary
493 cell = re.sub('^=@?', '', cell)
494
495 elif not self.num_re.match(cell):
496 cell = "'" + cell + "'"
497
498 self.ss[cellname] = cell
499
500 c += 1
501
502 r += 1
503
504 maxrows = r
505 result = ""
506
507 if outsep != '||':
508 self.request.write('<pre>')
509
510 if column_header == 1:
511 header_names = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
512 result += '\n' + outsep
513 if row_header == 1:
514 start = 0
515 else:
516 start = 1
517
518 for name in header_names[start:maxcolumns+1]:
519 result += colheader_format + "'''" + name + "'''" + outsep
520
521 for r in range(maxrows):
522 result += '\n' + outsep
523
524 if row_header == 1:
525 result += rowheader_format + "'''" + str(r) + "'''" + outsep
526
527 for c in range(maxcolumns):
528 cellname = col_names[c]+str(r)
529
530 if self.ss[cellname] == '':
531 cell = ' '
532 else:
533 cell = str(self.ss[cellname])
534 cell = re.sub("^'+", '', cell)
535 cell = re.sub("'+$", '', cell)
536
537 if show_formular == 0:
538 num_match = self.num_re.match(cell)
539 if num_match != None:
540 fmt = right_format
541 if formats[(r,c)] != '':
542 fmt = formats[(r,c)]
543
544 if format == '':
545 cell = '%s %.*f' % (fmt, 2, float(self.ss[cellname]))
546 else:
547 cell = '%s %.*f' % (fmt, int(format[c-1]), float(self.ss[cellname]))
548
549 elif show_formular == 1:
550 cell = self.ss.getformula(cellname)
551 else:
552 if formats[(r,c)] == '':
553 cell = left_format + cell
554 else:
555 cell = formats[(r,c)] + cell
556
557 result += cell + outsep
558
559 if outsep != '||':
560 self.request.write(result + '</pre>')
561 else:
562 result = result[1:]
563 result = wikiutil.unquoteWikiname(result)
564 wikiizer = wiki.Parser(result,self.request) # parser for wiki tabular
565 wikiizer.format(formatter)
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.