baggabThu Aug 14 11:20:11 PDT 2003
I was hoping you would elaborate on your level of involvement: really going to tackle this thing or just messing around on the weekend. Your first post suggested just a few projects.
baggabThu Aug 14 11:20:11 PDT 2003
I was hoping you would elaborate on your level of involvement: really going to tackle this thing or just messing around on the weekend. Your first post suggested just a few projects.
Bob MillerWed Aug 13 21:13:58 PDT 2003
Maximillian Schwanekamp wrote: > What Open Source Software replaces Adobe software? > > To that I add, ...and/or Macromedia software? Here's my best answer. It'll give you guys something to shoot down. (-: Adobe Postscript -> Ghostscript. Adobe PhotoShop -> The GIMP. Adobe Acrobat Reader -> xpdf. Adobe Illustrator -> ??? There's killustrator, and there's a decent draw module in OpenOffice.org, but neither is as capable as Illustrator. Adobe Premiere -> ??? I don't know of any open source video editors. I've seen some, but don't know anything about them. Macromedia Flash -> Isn't there a GNU flash player? Macromedia Dreamweaver (HTML editor) -> Quanta Bluefish Mozilla Composer Macromedia Dreamweaver (Site Mgmt system) -> Zope OpenACS what else? Macromedia Freehand -> OpenOffice.org's draw program (yes, seriously, unless I seriously understand what you can do with Freehand) Macromedia Director -> ??? Macromedia ColdFusion -> ??? What is it? Some kind of app server? Lots of open source app servers... See above w/ Zope. -- Bob Miller K<bob> kbobsoft software consulting http://kbobsoft.com kbob at jogger-egg.com
Maximillian SchwanekampWed Aug 13 18:18:03 PDT 2003
taken from baggab's post to eug-lug at efn.org... What Open Source Software replaces Adobe software? To that I add, ...and/or Macromedia software? Mr O on [eug-lug] offered this: >Actually that's a $15,000 question. That's what Disney >contributed to the Crossover's WINE project so they could run >Photoshop 7 on linux. :) How soon Macromedia's stuff works is >another question. Well, that's one app, and one wonders at it, since the GIMP is a very mature app that could replace Photoshop. What about vector graphics editing? This seems like an area that would be of interest to the GNU world. I.e. an Open Source Illustrator/Freehand/Fireworks editor? I have found "Flame" under development on SourceForge [ http://sourceforge.net/projects/flameproject/ ] if that is of use... Max
baggabWed Aug 13 16:18:38 PDT 2003
I want to thank Bob Miller, ELUG, and all upstream parties for allowing us the space and their efforts. I got into computing to provide employment and satisfy my technical curiosity. Due to VLSI and advancements in technology I see diminishing returns in personal investment in computer technology for personal employment. Rather then admit defeat I am returning to the art end of computing. I hope to make this time investment less like work and more like entertainment. I have contacted Lane Arts Council and here is their reply: Brian -- I suspect your best bet will be (1) the UO Fine Art Dept - a number of people work in multi-media or (2) "hidden" digital artists working in graphic design, game design, architecture, etc. I don't know of any artists groups organized around 3D modeling. -Douglas Beauchamp I will check out UO in the following weeks. I would like to post some flyers at local art watering holes, but I'll wait to see if there is some dialog first. Brian
john flemingThu Feb 20 21:37:49 PST 2003
http://www.nedbatchelder.com/code/index.html http://www.nedbatchelder.com/site/index.html Ive found some very interesting python stuff off these links _______________________________________________ Think mailing list Think at zoneverte.org http://mail.zoneverte.org/cgi-bin/listinfo/think
Ralph ZellerMon Feb 17 14:26:28 PST 2003
Sorry this message is long, but I know at least Horst will read it! My wife is a writer and a new requirement given to her by her publishers is to edit her material to within certain scores on a readability index. Apparently MS-Word has some capability of computing readabiliy indexes, so these indexes are presumed to be readily available to writers. It seemed like an interesting exercise to create a flesch score program using Python. This program is slower than one I found which was written in cpp, but it serves my need. --- #!/usr/bin/env python2 # Created 2/16/03 Ralph Zeller [Python 2.2 (#1, Apr 12 2002, 15:29:57)] # given a text file, compute the Flesch readability score. # # Rudolph Flesh invented this index which is used by publishers to # judge the readability of English writing, with an objective measure. # The model purports that long sentences filled with long words are # less readable than short sentences with short words. # The index is better described at: # http://www.mang.canterbury.ac.nz/courseinfo/AcademicWriting/Flesch.htm # # The formula I used for counting syllables is based loosely on comments # that I read in a c++ program created by Roger Frank that I found at # http://www.rfrank.us/ import sys,string try: fn=sys.argv[1] f=open(fn,'r') f.close() except: print "Usage:",sys.argv[0], "filename.txt" sys.exit() print "Reading file:",fn f=open(fn,'r') t='0' dot=0 count_syllables=0.0 count_words=0.0 count_sentences=0.0 #words=[] # Container for database of words # Setup a translation table to remove punctuation tt='' for x in range(256): tt+=chr(x) dc='~!@#$%^&*()_+=-`{}|\\][\';/.,<>? :"' #delete chars # Main loop while t<>'': t=f.readline() s=t.split() for word in s: # First look for sentences. for c in ['.',';',':','?','!']: if word.find(c)>=0: count_sentences+=1 # print a dot for every sentence (to show progress). dot+=1 if dot>4: dot=0 print '.', # Strip out the funny characters word=word.translate(tt,dc) word=word.lower() #print word, if len(word)>0: count_words+=1 #words.append(word) # fill database of words (why? statistics) # Count syllables count = 0 vowels=['a','e','i','o','u','y'] # Count all vowels as a syllable, unless they are together. # This doesn't catch words like "variety", oh well. for x in range(len(word)-1): if word[x] in vowels: if word[x+1] not in vowels: count+=1 # count a syllable if last character is a vowel other than 'e' if word[len(word)-1] in ['a','i','o','u','y']: count+=1 # Every word counts as at least one syllable if count<1: count=1 count_syllables+=count #report the results if count_words<1: print "No words found." else: print " " print "Flesch Readability Score" print str(int(round(count_syllables,0))),"syllables" print str(int(round(count_words,0))), "words" print str(int(round(count_sentences,0))),"sentences" asl=count_words/count_sentences awl=count_syllables/count_words print "Average sentence length:",str(round(asl,1)),"words per sentence" print "Average word length:",str(round(awl,1)),"syllables per word" fscore=206.835-(1.015*asl+84.6*awl) print "**********Flesch score:",str(round(fscore,1)),'**********' print "Scale 90-100 = very easy = 5th grade = Comics" print " 80- 90 = easy = 6th grade = Magazine ads" print " 70- 80 = very easy = 7th grade = Movie screen" print " 60- 70 = plain English = 8th & 9th = Reader's Digest" print " 50- 60 = fairly difficult = 10th-12th = Time Magazine" print " 40 = difficult to read = college = Wall St Journal" print " 10- 20 = very difficult = grad coll = Insurance policy" f.close() _______________________________________________ Think mailing list Think at zoneverte.org http://mail.zoneverte.org/cgi-bin/listinfo/think
HorstWed Dec 4 20:19:55 PST 2002
On Tue, 5 Nov 2002, Rob Hudson wrote: > I've been following these, but not actively participating. There are some > interesting challenges, though. Anyone want to play along in Python? > > PHP Coding Contest: > http://codewalkers.com/php-contest.php > > The current one is the 'Stacking Discs' contest. Rob, Did you (or anyone else) continue working on the disk stacker problem? Well, I got hooked until I found that the time constrain (30sec run time) prohibits me from further optimizing the search algorithm. They finally posted the winning results together with the input data against which the contestant's code is ranked. So I plugged those input data into my python version and was pleasantly surprised: my algorithm beats the winning code at the total score, as well as in 9 out of 10 cases. So I couldn't resist to post my solution (incl. reference to code and output data) to their forum: http://codewalkers.com/forum/index.php?action=displaythread&forum=php-contest&id=340&realm=default or if thread above has moved: http://codewalkers.com/forum/index.php?forum=php-contest&realm=default Coming back to learning python, I would say that those run time restricted contests are not really ideal for learning the language or good coding style: a) The crux in winning that contest was finding the best algorithm, no matter how elegant or ugly the code looks like. b) Because of the time constrains you may be inclined to take shortcuts, and tailor your code to that specific problem (with little interest in reusability). As a matter of fact, I ended up coding procedural and didn't even bother to wrap a class around it at the end. Reasons: 1) Speed: I assumed that pulling data out of a global 4-dimensional list is faster than going through a series of access functions. 2) Readability. Most of the code would turn into class methods, with all the relevant data hidden as private members; e.g. instead of accessing 'maxDisk' you would have to look at 'self.__maxDisk' all the time (or alias it). If it wouldn't be for the 9/10 'victory' I wouldn't have made it public, so here you go. But then, 9/10 also means the glass is only 90% full --so, any takers ? ........................... Horst _______________________________________________ Think mailing list Think at zoneverte.org http://mail.zoneverte.org/cgi-bin/listinfo/think
Horst LueckWed Nov 6 00:40:44 PST 2002
Rob, your strip() doesn't work because you apply it after the list has
been created by readlines().
If you (only and always) want to strip the last empty line (or list
element) you could use the slice operator lines = lines[:-1].
As a quick&dirty approach, i.e. w/o argument checking or IOException
checking:
"""
from sys import argv
rawData = open(argv[1]).readlines() # file.close() at gc
strippedData = []
numericData = []
for item in rawData:
if item.strip():
strippedData.append(item) # or strip if desired
numericData.append( int(item) ) # a hint about string -> int
print strippedData # note, if not stripped, trailig \012 is octal (x0A)
print numericData
"""
See also #comment in text below.
Hey Rob -- welcome to python community ! .......... Horst
On Tue, 5 Nov 2002, Rob Hudson wrote:
> Hello,
>
> I'm trying to read in a file that looks like this:
> ====
> 1
> 2
> 3
> 4
>
> ====
>
> Note the empty line last. What I want to do is remove the new line
> characters, filter out the final empty string, and shove all that into a
> list.
>
> Here is my Python code, which doesn't filter the final empty string, though
> I'm not sure why. Any ideas or code improvements most welcome.
>
> Thanks,
> Rob
>
> #!/usr/bin/env python
> import sys
>
> def processFile (filename):
>
> f = open(filename, 'r')
> lines = [line.rstrip() for line in f.readlines()]
> f.close()
>
> filter(None,lines)
>
> return lines
>
> def printStack (stack):
> for item in stack:
> print "(%s)" % item
# if you file.readlines() you get list[string]
# --forget about the ugly %-stuff and use overloaded operator '+'
# for simple output.
# Here just 'print item' , or print 'some text', some_int,
>
>
> if len(sys.argv) == 2:
> stack = processFile(sys.argv[1])
> printStack(stack)
> else:
> print "Must specify input file",
> exit(0)
>
> _______________________________________________
> Think mailing list
> Think at zoneverte.org
> http://mail.zoneverte.org/cgi-bin/listinfo/think
>
_______________________________________________
Think mailing list
Think at zoneverte.org
http://mail.zoneverte.org/cgi-bin/listinfo/think
Bob MillerMon Nov 4 22:56:27 PST 2002
Chris Meyers wrote: > The whole thing at > > http://www.ibiblio.org/obp/py4fun Ah. Thanks. I'd looked at Python for Fun a couple of months ago, and lost track of where it was. Now it's bookmarked. > If a little recursion doesn't bother you, parsing in Python can be > very easy. You might look at a little compiler (~100 lines) that I > did for the "Python for fun" project. It's part of a 3 part > tuttorial on machine lang, assemblers, and compilers > > http://www.ibiblio.org/obp/py4fun/mm/compiler.html Interesting. That's one mighty terse compiler. Since I've been playing with the spark compiler framework[1, 2], I decided to rewrite your compiler using spark. I wanted to see whether spark really is useful for writing a real compiler, and your little language was the perfect example. Attached is a four pass compiler, with separate scanner, parser, register allocator, and code generator passes. It's a little more verbose, but I think it's easier to understand what's going on. (Of course, I always understand my code better than somebody else's code. (-: ) I attempted to compile the same language as your compiler, and for this program: term = 5 ans = 1 while term { ans = ans * term term = term - 1 } mine generates output identical to yours. [1] Spark homepage: http://pages.cpsc.ucalgary.ca/~aycock/spark/ [2] The Spark paper: http://www.foretec.com/python/workshops/1998-11/proceedings/papers/aycock-little/aycock-little.ps -- Bob Miller K<bob> kbobsoft software consulting http://kbobsoft.com kbob at jogger-egg.com -------------- next part -------------- #!/usr/bin/python2.2 # # c o m p i l e r . p y # from __future__ import generators from spark import GenericScanner, GenericParser, GenericASTTraversal def _labelgen(): 'Generate unique label numbers.' nextLabel = 1 while 1: yield nextLabel nextLabel += 1 next_label = _labelgen().next class Token: def __init__(self, type, attr=None): self.type = type self.attr = attr def __cmp__(self, o): return cmp(self.type, o) def __repr__(self): return repr(self.attr is None and self.type or self.attr) class AST: 'Abstract Syntax Tree' def __init__(self, type, *kids): self.type = type.type self.attr = type.attr self.kids = list(kids) def __getitem__(self, i): return self.kids[i] def __repr__(self): s = self.type if self.attr is not None: s += ':' + `self.attr` if 'reg' in self.__dict__: s += '[r%s]' % str(self.reg) if self.kids: s += '(%s)' % ' '.join([str(k) for k in self.kids]) return s class Scanner(GenericScanner): def __init__(self): GenericScanner.__init__(self) def scan(self, string): # return list of tokens self.rv = [] self.tokenize(string) return self.rv def t_whitespace(self, s): r' \s+ ' pass def t_int(self, s): r' \d+ ' self.rv.append(Token('int', int(s))) def t_ident(self, s): r' [A-Za-z][\w\d]* ' if s == 'while': self.rv.append(Token('while')) else: self.rv.append(Token('ident', s)) def t_op(self, s): r' [-+*/] ' self.rv.append(Token(type='op', attr=s)) def t_eq(self, s): r' = ' self.rv.append(Token(type='eq', attr=s)) def t_punct(self, s): r' [{}()=] ' self.rv.append(Token(s)) class Parser(GenericParser): def __init__(self, start='stats'): GenericParser.__init__(self, start) def p_stats1(self, args): ' stats ::= ' return AST(Token('stats')) def p_stats2(self, args): ' stats ::= stats stat ' # N.B. \n and ; are equivalent args[0].kids.append(args[1]) return args[0] def p_stat1(self, args): ' stat ::= while expr stat ' return AST(args[0], args[1], args[2]) def p_stat2(self, args): ' stat ::= { stats } ' return args[1] def p_stat3(self, args): ' stat ::= expr ' return args[0] def p_stat4(self, args): ' stat ::= ident eq expr' return AST(args[1], AST(args[0]), args[2]) def p_expr1(self, args): ' expr ::= term ' return args[0] def p_expr2(self, args): ' expr ::= expr op term ' return AST(args[1], args[0], args[2]) def p_term1(self, args): ' term ::= ( expr ) ' return args[1] def p_term2(self, args): ''' term ::= ident term ::= int ''' return AST(args[0]) def enumerate(seq): # built in in Python 2.3 'Generate (index, element) for all elements in a sequence.' i = 0 it = iter(seq) while 1: yield i, it.next() i += 1 class RegisterAllocator(GenericASTTraversal): def __init__(self): GenericASTTraversal(None) def allocate(self, ast): ast.reg = 0 self.preorder(ast) def default(self, node): if node.type in ('while', 'op'): for i, kid in enumerate(node): kid.reg = node.reg + i elif node.type == 'eq': node[0].reg = None # special marker - inhibit load node[1].reg = node.reg else: for kid in node: kid.reg = node.reg class CodeGenerator(GenericASTTraversal): def __init__(self): GenericASTTraversal(None) def generate(self, ast): self.code = [] self.vars = {} self.preorder(ast) self.emit(' hlt') for var in self.vars: self.emit('%s 0' % var) return '\n'.join(self.code) def emit(self, line): self.code.append(line) def n_int(self, node): self.emit(' ld# r%d,%d' % (node.reg, node.attr)) def n_ident(self, node): if node.reg is not None: self.emit(' ld r%d,%s' % (node.reg, node.attr)) def n_while(self, node): label1, label2 = next_label(), next_label() self.emit('z%d' % label1) self.preorder(node[0]) self.emit(' jz r%d,z%d' % (node.reg, label2)) self.preorder(node[1]) self.emit(' jmp z%d' % label1) self.emit('z%d' % label2) self.prune() def n_op_exit(self, node): opcode = { '+': 'add', '-': 'sub', '*': 'mul', '/': 'div' }[node.attr] self.emit(' %s r%d,r%d' % (opcode, node.reg, node.reg + 1)); def n_eq_exit(self, node): varname = node[0].attr self.vars[varname] = None self.emit(' sto r%d,%s' % (node.reg, varname)) def default(self, node): if node.type in ('stats', 'op', 'eq'): pass else: assert False, 'type %s not handled' % node.type def compile(source): 'Compile source into assembler.' scanner = Scanner() parser = Parser() allocator = RegisterAllocator() codegenerator = CodeGenerator() # print source tokens = scanner.scan(source) # print tokens ast = parser.parse(tokens) # print ast allocator.allocate(ast) # print ast code = codegenerator.generate(ast) return code def main () : "compile program from command line or standard input" import sys if len(sys.argv) < 2 : program = sys.stdin.read() else : program = sys.argv[1] print compile(program) if __name__ == "__main__" : main() -------------- next part -------------- # Copyright (c) 1998-2000 John Aycock # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __version__ = 'SPARK-0.6.1' import re import sys import string def _namelist(instance): namelist, namedict, classlist = [], {}, [instance.__class__] for c in classlist: for b in c.__bases__: classlist.append(b) for name in dir(c): if not namedict.has_key(name): namelist.append(name) namedict[name] = 1 return namelist class GenericScanner: def __init__(self): pattern = self.reflect() self.re = re.compile(pattern, re.VERBOSE) self.index2func = {} for name, number in self.re.groupindex.items(): self.index2func[number-1] = getattr(self, 't_' + name) def makeRE(self, name): doc = getattr(self, name).__doc__ rv = '(?P<%s>%s)' % (name[2:], doc) return rv def reflect(self): rv = [] for name in _namelist(self): if name[:2] == 't_' and name != 't_default': rv.append(self.makeRE(name)) rv.append(self.makeRE('t_default')) return string.join(rv, '|') def error(self, s, pos): print "Lexical error at position %s" % pos raise SystemExit def tokenize(self, s): pos = 0 n = len(s) while pos < n: m = self.re.match(s, pos) if m is None: self.error(s, pos) groups = m.groups() for i in range(len(groups)): if groups[i] and self.index2func.has_key(i): self.index2func[i](groups[i]) pos = m.end() def t_default(self, s): r'( . | \n )+' pass class GenericParser: def __init__(self, start): self.rules = {} self.rule2func = {} self.rule2name = {} self.collectRules() self.startRule = self.augment(start) self.ruleschanged = 1 _START = 'START' _EOF = 'EOF' # # A hook for GenericASTBuilder and GenericASTMatcher. # def preprocess(self, rule, func): return rule, func def addRule(self, doc, func): rules = string.split(doc) index = [] for i in range(len(rules)): if rules[i] == '::=': index.append(i-1) index.append(len(rules)) for i in range(len(index)-1): lhs = rules[index[i]] rhs = rules[index[i]+2:index[i+1]] rule = (lhs, tuple(rhs)) rule, fn = self.preprocess(rule, func) if self.rules.has_key(lhs): self.rules[lhs].append(rule) else: self.rules[lhs] = [ rule ] self.rule2func[rule] = fn self.rule2name[rule] = func.__name__[2:] self.ruleschanged = 1 def collectRules(self): for name in _namelist(self): if name[:2] == 'p_': func = getattr(self, name) doc = func.__doc__ self.addRule(doc, func) def augment(self, start): # # Tempting though it is, this isn't made into a call # to self.addRule() because the start rule shouldn't # be subject to preprocessing. # startRule = (self._START, ( start, self._EOF )) self.rule2func[startRule] = lambda args: args[0] self.rules[self._START] = [ startRule ] self.rule2name[startRule] = '' return startRule def makeFIRST(self): union = {} self.first = {} for rulelist in self.rules.values(): for lhs, rhs in rulelist: if not self.first.has_key(lhs): self.first[lhs] = {} if len(rhs) == 0: self.first[lhs][None] = 1 continue sym = rhs[0] if not self.rules.has_key(sym): self.first[lhs][sym] = 1 else: union[(sym, lhs)] = 1 changes = 1 while changes: changes = 0 for src, dest in union.keys(): destlen = len(self.first[dest]) self.first[dest].update(self.first[src]) if len(self.first[dest]) != destlen: changes = 1 # # An Earley parser, as per J. Earley, "An Efficient Context-Free # Parsing Algorithm", CACM 13(2), pp. 94-102. Also J. C. Earley, # "An Efficient Context-Free Parsing Algorithm", Ph.D. thesis, # Carnegie-Mellon University, August 1968, p. 27. # def typestring(self, token): return None def error(self, token): print "Syntax error at or near `%s' token" % token raise SystemExit def parse(self, tokens): tree = {} tokens.append(self._EOF) states = { 0: [ (self.startRule, 0, 0) ] } if self.ruleschanged: self.makeFIRST() for i in xrange(len(tokens)): states[i+1] = [] if states[i] == []: break self.buildState(tokens[i], states, i, tree) #_dump(tokens, states) if i < len(tokens)-1 or states[i+1] != [(self.startRule, 2, 0)]: del tokens[-1] self.error(tokens[i-1]) rv = self.buildTree(tokens, tree, ((self.startRule, 2, 0), i+1)) del tokens[-1] return rv def buildState(self, token, states, i, tree): needsCompletion = {} state = states[i] predicted = {} for item in state: rule, pos, parent = item lhs, rhs = rule # # A -> a . (completer) # if pos == len(rhs): if len(rhs) == 0: needsCompletion[lhs] = (item, i) for pitem in states[parent]: if pitem is item: break prule, ppos, pparent = pitem plhs, prhs = prule if prhs[ppos:ppos+1] == (lhs,): new = (prule, ppos+1, pparent) if new not in state: state.append(new) tree[(new, i)] = [(item, i)] else: tree[(new, i)].append((item, i)) continue nextSym = rhs[pos] # # A -> a . B (predictor) # if self.rules.has_key(nextSym): # # Work on completer step some more; for rules # with empty RHS, the "parent state" is the # current state we're adding Earley items to, # so the Earley items the completer step needs # may not all be present when it runs. # if needsCompletion.has_key(nextSym): new = (rule, pos+1, parent) olditem_i = needsCompletion[nextSym] if new not in state: state.append(new) tree[(new, i)] = [olditem_i] else: tree[(new, i)].append(olditem_i) # # Has this been predicted already? # if predicted.has_key(nextSym): continue predicted[nextSym] = 1 ttype = token is not self._EOF and \ self.typestring(token) or \ None if ttype is not None: # # Even smarter predictor, when the # token's type is known. The code is # grungy, but runs pretty fast. Three # cases are looked for: rules with # empty RHS; first symbol on RHS is a # terminal; first symbol on RHS is a # nonterminal (and isn't nullable). # for prule in self.rules[nextSym]: new = (prule, 0, i) prhs = prule[1] if len(prhs) == 0: state.append(new) continue prhs0 = prhs[0] if not self.rules.has_key(prhs0): if prhs0 != ttype: continue else: state.append(new) continue first = self.first[prhs0] if not first.has_key(None) and \ not first.has_key(ttype): continue state.append(new) continue for prule in self.rules[nextSym]: # # Smarter predictor, as per Grune & # Jacobs' _Parsing Techniques_. Not # as good as FIRST sets though. # prhs = prule[1] if len(prhs) > 0 and \ not self.rules.has_key(prhs[0]) and \ token != prhs[0]: continue state.append((prule, 0, i)) # # A -> a . c (scanner) # elif token == nextSym: #assert new not in states[i+1] states[i+1].append((rule, pos+1, parent)) def buildTree(self, tokens, tree, root): stack = [] self.buildTree_r(stack, tokens, -1, tree, root) return stack[0] def buildTree_r(self, stack, tokens, tokpos, tree, root): (rule, pos, parent), state = root while pos > 0: want = ((rule, pos, parent), state) if not tree.has_key(want): # # Since pos > 0, it didn't come from closure, # and if it isn't in tree[], then there must # be a terminal symbol to the left of the dot. # (It must be from a "scanner" step.) # pos = pos - 1 state = state - 1 stack.insert(0, tokens[tokpos]) tokpos = tokpos - 1 else: # # There's a NT to the left of the dot. # Follow the tree pointer recursively (>1 # tree pointers from it indicates ambiguity). # Since the item must have come about from a # "completer" step, the state where the item # came from must be the parent state of the # item the tree pointer points to. # children = tree[want] if len(children) > 1: child = self.ambiguity(children) else: child = children[0] tokpos = self.buildTree_r(stack, tokens, tokpos, tree, child) pos = pos - 1 (crule, cpos, cparent), cstate = child state = cparent lhs, rhs = rule result = self.rule2func[rule](stack[:len(rhs)]) stack[:len(rhs)] = [result] return tokpos def ambiguity(self, children): # # XXX - problem here and in collectRules() if the same # rule appears in >1 method. But in that case the # user probably gets what they deserve :-) Also # undefined results if rules causing the ambiguity # appear in the same method. # sortlist = [] name2index = {} for i in range(len(children)): ((rule, pos, parent), index) = children[i] lhs, rhs = rule name = self.rule2name[rule] sortlist.append((len(rhs), name)) name2index[name] = i sortlist.sort() list = map(lambda (a,b): b, sortlist) return children[name2index[self.resolve(list)]] def resolve(self, list): # # Resolve ambiguity in favor of the shortest RHS. # Since we walk the tree from the top down, this # should effectively resolve in favor of a "shift". # return list[0] # # GenericASTBuilder automagically constructs a concrete/abstract syntax tree # for a given input. The extra argument is a class (not an instance!) # which supports the "__setslice__" and "__len__" methods. # # XXX - silently overrides any user code in methods. # class GenericASTBuilder(GenericParser): def __init__(self, AST, start): GenericParser.__init__(self, start) self.AST = AST def preprocess(self, rule, func): rebind = lambda lhs, self=self: \ lambda args, lhs=lhs, self=self: \ self.buildASTNode(args, lhs) lhs, rhs = rule return rule, rebind(lhs) def buildASTNode(self, args, lhs): children = [] for arg in args: if isinstance(arg, self.AST): children.append(arg) else: children.append(self.terminal(arg)) return self.nonterminal(lhs, children) def terminal(self, token): return token def nonterminal(self, type, args): rv = self.AST(type) rv[:len(args)] = args return rv # # GenericASTTraversal is a Visitor pattern according to Design Patterns. For # each node it attempts to invoke the method n_<node type>, falling # back onto the default() method if the n_* can't be found. The preorder # traversal also looks for an exit hook named n_<node type>_exit (no default # routine is called if it's not found). To prematurely halt traversal # of a subtree, call the prune() method -- this only makes sense for a # preorder traversal. Node type is determined via the typestring() method. # class GenericASTTraversalPruningException: pass class GenericASTTraversal: def __init__(self, ast): self.ast = ast def typestring(self, node): return node.type def prune(self): raise GenericASTTraversalPruningException def preorder(self, node=None): if node is None: node = self.ast try: name = 'n_' + self.typestring(node) if hasattr(self, name): func = getattr(self, name) func(node) else: self.default(node) except GenericASTTraversalPruningException: return for kid in node: self.preorder(kid) name = name + '_exit' if hasattr(self, name): func = getattr(self, name) func(node) def postorder(self, node=None): if node is None: node = self.ast for kid in node: self.postorder(kid) name = 'n_' + self.typestring(node) if hasattr(self, name): func = getattr(self, name) func(node) else: self.default(node) def default(self, node): pass # # GenericASTMatcher. AST nodes must have "__getitem__" and "__cmp__" # implemented. # # XXX - makes assumptions about how GenericParser walks the parse tree. # class GenericASTMatcher(GenericParser): def __init__(self, start, ast): GenericParser.__init__(self, start) self.ast = ast def preprocess(self, rule, func): rebind = lambda func, self=self: \ lambda args, func=func, self=self: \ self.foundMatch(args, func) lhs, rhs = rule rhslist = list(rhs) rhslist.reverse() return (lhs, tuple(rhslist)), rebind(func) def foundMatch(self, args, func): func(args[-1]) return args[-1] def match_r(self, node): self.input.insert(0, node) children = 0 for child in node: if children == 0: self.input.insert(0, '(') children = children + 1 self.match_r(child) if children > 0: self.input.insert(0, ')') def match(self, ast=None): if ast is None: ast = self.ast self.input = [] self.match_r(ast) self.parse(self.input) def resolve(self, list): # # Resolve ambiguity in favor of the longest RHS. # return list[-1] def _dump(tokens, states): for i in range(len(states)): print 'state', i for (lhs, rhs), pos, parent in states[i]: print '\t', lhs, '::=', print string.join(rhs[:pos]), print '.', print string.join(rhs[pos:]), print ',', parent if i < len(tokens): print print 'token', str(tokens[i]) print
DICEThu Sep 12 07:55:02 PDT 2002
This job listing was sent to you by larry
This job was originally posted on Dice.com - the premier job site for IT professionals.
hmm, my knowledge of clearcase and Visual C++ is limited
otherwise I would.
****************************************************************************
Software Technology Group Randie Peterson
4240 SW 109th Avenue Tel: (503) 672-9245
Beaverton, OR 97005 Fax: (503) 350-0620
****************************************************************************
POSITION TITLE : Software Consultant
SKILLS REQUIREMENTS: Python, XML, Clearcase
LOCATION : OR 503 Portland
LENGTH : 3 months
POSITION ID: E-010
EMAIL: stg at softwaretechnology.com
WEB: http://www.softwaretechnology.com
DESCRIPTION: We have a client requiring skills in Python, XML, CVS,
and Clearcase. The task is to create a software
bridge between CVS and Clearcase. In addition, the
successful candidate will have programming skills in
Visual C/C++.
At STG we have varied projects. Visual C++ and Visual
Basic experience is also very important. We have
current projects on printer development, robotics,
laser physics, and intranet and internet development.
Please only US citizens or green card holders. Only
local candidates, or those willing to cover their own
relocation expenses.
_______________________________________________
Think mailing list
Think at zoneverte.org
http://mail.zoneverte.org/cgi-bin/listinfo/think