Attachment 'sstable-1.0.1.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.1: use unicode function - Andrew Shewmaker
277 1.0: based on sctable-1.5.2-5 by Reimar Bauer (R.Bauer AT fz-juelich.de)
278 """
279
280 Dependencies = []
281 import re
282 from math import *
283 from MoinMoin.parser import wiki
284 from MoinMoin.action import AttachFile
285 from MoinMoin.Page import Page
286
287 class SpreadSheet:
288 _cells = {}
289 tools = {}
290 _cache = None
291 def __init__(self):
292 self.tools.update({'__builtins__':None})
293 pmath = { 'ceil':ceil, 'floor':floor, \
294 'fabs':fabs, \
295 'fmod':fmod, 'modf':modf, \
296 'frexp':frexp, 'ldexp':ldexp, \
297 'exp':exp, \
298 'log':log, 'log10':log10, \
299 'pow':pow, \
300 'sqrt':sqrt, \
301 'acos':acos, 'asin':asin, 'atan':atan, 'atan2':atan2, \
302 'cos':cos, 'sin':sin, 'tan':tan, \
303 'cosh':cosh, 'sinh':sinh, 'tanh':tanh, \
304 'hypot':hypot, \
305 'degrees':degrees, 'radians':radians, \
306 'pi':pi, \
307 'e':e, \
308 'max':self.max, 'min':self.min, \
309 'sum':self.sum, \
310 }
311 self.tools.update(pmath)
312
313 def getformula(self, key):
314 return self._cells[key]
315
316 def max(self, key):
317 result = 0
318 for cellname in self.cellrange(key):
319 result = max(self.__getitem__(cellname), result)
320
321 return result
322
323 def min(self, key):
324 result = self.cellrange(key)
325 for cellname in self.cellrange(key):
326 result = min(self.__getitem__(cellname), result)
327
328 return result
329
330 def sum(self, key):
331 result = 0
332 for cellname in self.cellrange(key):
333 result += self.__getitem__(cellname)
334
335 return result
336
337 def __setitem__(self, key, formula):
338 self._cells[key.lower()] = formula
339
340 def __getitem__(self, key):
341 bCache = self._cache is None
342 if bCache: self._cache = {}
343 while True:
344 try:
345 if ( self._cells[key] == None or self._cells[key] == ''):
346 rv = ''
347 else:
348 rv = eval(self._cells[key], self.tools, self._cache)
349 break
350 except NameError, ne:
351 name = ne.args[0][6:-16] # Extract name from NameError
352 if name in self._cells:
353 self._cache[name] = self[name]
354 else:
355 self._cache[key] = None
356 self._cells[key] = None
357 except SyntaxError, se:
358 rv = self._cells[key]
359 break
360 except TypeError, te:
361 rv = 'type error: ' + self._cells[key] + ', ' + str(te)
362 break
363
364 if bCache: self._cache = None
365 return rv
366
367 def cellrange(self, keys):
368 m = re.search('([a-z]+)(\d+):([a-z])+(\d+)?', keys)
369
370 result = []
371 if m == None:
372 result = re.split(',', keys)
373 return result
374
375 (c1, r1, c2, r2) = m.groups()
376
377 mincol = min(c1, c2)
378 maxcol = max(c1, c2)
379 minrow = min(int(r1), int(r2))
380 maxrow = max(int(r1), int(r2))
381
382 col_names = 'abcdefghijklmnopqrstuvwxyz'
383 for i in range(col_names.index(mincol), col_names.index(maxcol)+1):
384 for j in range(minrow, maxrow+1):
385 result.append(col_names[i] + str(j))
386
387 return result
388
389
390 class Parser:
391
392 def __init__(self, raw, request, **kw):
393 self.ss = SpreadSheet()
394 self.raw = raw
395 self.request = request
396 self.form = request.form
397 self._ = request.getText
398 self.kw = []
399 for arg in kw.get('format_args','').split():
400 self.kw.append(arg)
401
402
403 def format(self, formatter):
404 lines = self.raw.split('\n')
405
406 kw = self.kw
407 column_header = 0
408 row_header = 0
409 show_formular = 0
410 format = ''
411 insep = '||'
412 outsep = '||'
413 right_format = '<)>'
414 left_format = '<(>'
415 colheader_format = '<:#CCCCCC>'
416 rowheader_format = '<)5%#CCCCCC>'
417 zt = 0
418 for test in kw:
419 if test == '-column_header': column_header = 1
420 if test == '-row_header': row_header = 1
421 if test == '-show_formular': show_formular = 1
422 if test == '-format': format = re.split(',', kw[zt+1])
423 if test == '-input_separator': insep = kw[zt+1]
424 if test == '-output_separator':
425 outsep = kw[zt+1]
426 right_format = ''
427 left_format = ''
428 colheader_format = ''
429 rowheader_format = ''
430 zt += 1
431
432 formats = {} # { (row,col): '<wikiformat>', ... }
433 r = 0 # row counter
434 c = 0 # column counter
435 col_names = 'abcdefghijklmnopqrstuvwxyz'
436 maxcolumns = 0
437
438 for txt in lines:
439 txt = txt.lstrip()
440 if ( txt == '' ):
441 continue
442 columns = txt.split(insep)
443 if re.search('^' + insep, txt):
444 columns = columns[1:]
445 if re.search(insep + '$', txt):
446 columns = columns[:-1]
447
448 if ( len(columns) > maxcolumns):
449 maxcolumns = len(columns)
450
451 c = 0
452 for cell in columns:
453 cellname = col_names[c]+str(r)
454 cell = cell.strip()
455
456 # check for wiki formatting string at beginning of ss data: "<format>..."
457 if cell.startswith('<'):
458 p = cell.find('>') + 1
459 if p > 1:
460 formats[(r,c)] , cell = cell[:p] , cell[p:]
461 cell = cell.strip()
462 else:
463 formats[(r,c)] = ""
464
465 # compatibility with other spreadsheet syntax
466 # case insensitivity for everything after an '='
467 m = re.search('=@?(.+)', cell)
468 nonstr_match = re.match('^[\d+-\.\{]', cell)
469 if m == None and nonstr_match == None:
470 cell = '"' + cell + '"'
471 elif m != None:
472 cell = m.group(1).lower()
473
474 # cell ranges are parsed as strings
475 m = re.search('(\w+).(\w+:\w+).', cell)
476 if m != None:
477 cell = m.group(1) + "('" + m.group(2) + "')"
478
479 # lowercase variable names
480 m = re.search('\{(.+)\}(.+)', cell)
481 if m != None:
482 cell = m.group(2).lower()
483 self.ss[m.group(1)] = cellname
484
485 # '=' and '@' are unnecessary after the parsing above
486 cell = re.sub('=@?', '', cell)
487
488 self.ss[cellname] = cell
489
490 c += 1
491
492 r += 1
493
494 maxrows = r
495 result = ""
496
497 if outsep != '||':
498 self.request.write('<pre>')
499
500 if column_header == 1:
501 header_names = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
502 result += '\n' + outsep
503 if row_header == 1:
504 start = 0
505 else:
506 start = 1
507
508 for name in header_names[start:maxcolumns+1]:
509 result += colheader_format + "'''" + name + "'''" + outsep
510
511 for r in range(maxrows):
512 result += '\n' + outsep
513
514 if row_header == 1:
515 result += rowheader_format + "'''" + str(r) + "'''" + outsep
516
517 for c in range(maxcolumns):
518 cellname = col_names[c]+str(r)
519
520 if self.ss[cellname] == '':
521 cell = ' '
522 else:
523 cell = str(self.ss[cellname])
524
525 if show_formular == 0:
526 nonstr_match = re.match('^[\d+-\.\{]', cell)
527 if nonstr_match != None:
528 fmt = right_format
529 if formats[(r,c)] != '':
530 fmt = formats[(r,c)]
531
532 if format == '':
533 cell = '%s %.*f' % (fmt, 2, float(self.ss[cellname]))
534 else:
535 cell = '%s %.*f' % (fmt, int(format[c-1]), float(self.ss[cellname]))
536
537 elif show_formular == 1:
538 cell = self.ss.getformula(cellname)
539 else:
540 if formats[(r,c)] == '':
541 cell = left_format + cell
542 else:
543 cell = formats[(r,c)] + cell
544
545 result += cell + outsep
546
547 if outsep != '||':
548 self.request.write(result + '</pre>')
549 else:
550 result = result[1:]
551 wikiizer = wiki.Parser(unicode(result,'latin-1'),self.request) # parser for wiki tabular
552 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.