rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
but returns a MatchFirst for best performance.
but returns a MatchFirst for best performance. Parameters: - strs - a string of space-delimited literals, or a list of string literals - caseless - (default=False) - treat all literals as caseless - useRegex - (default=True) - as an optimization, will generate a Regex object; otherwise, will generate a MatchFirst obje...
def oneOf( strs, caseless=False, useRegex=True ): """Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a MatchFirst for best performance. """ if caseless: isequal = ( lambda a,b: a.upper() == b.upper() ...
symbols = strs.split()
if isinstance(strs,list): symbols = strs[:] elif isinstance(strs,basestring): symbols = strs.split() else: warnings.warn("Invalid argument to oneOf, expected string or list", SyntaxWarning, stacklevel=2)
def oneOf( strs, caseless=False, useRegex=True ): """Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a MatchFirst for best performance. """ if caseless: isequal = ( lambda a,b: a.upper() == b.upper() ...
pass
warnings.warn("Exception creating Regex for oneOf, building MatchFirst", SyntaxWarning, stacklevel=2)
def oneOf( strs, caseless=False, useRegex=True ): """Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a MatchFirst for best performance. """ if caseless: isequal = ( lambda a,b: a.upper() == b.upper() ...
return replStr
return [replStr]
def _replFunc(*args): return replStr
columnName = Upcase( delimitedList( ident, ".", combine=True ) )
columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
def test( teststring ): print teststring,"->", try: tokens = simpleSQL.parseString( teststring ) tokenlist = tokens.asList() print tokenlist print "tokens = ", tokens print "tokens.columns =", tokens.columns print "tokens.tables =", tokens.tables print tokens.asXML("SQL",True) except ParseException, err: print ...
tableName = Upcase( delimitedList( ident, ".", combine=True ) )
tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
def test( teststring ): print teststring,"->", try: tokens = simpleSQL.parseString( teststring ) tokenlist = tokens.asList() print tokenlist print "tokens = ", tokens print "tokens.columns =", tokens.columns print "tokens.tables =", tokens.tables print tokens.asXML("SQL",True) except ParseException, err: print ...
if toklist: if isinstance(toklist,basestring):
if not toklist in (None,'',[]): if isinstance(toklist,basestring):
def __init__( self, toklist, name=None, asList=True, modal=True ): if self.__doinit: self.__doinit = False self.__name = None self.__parent = None self.__modal = modal if isinstance(toklist, list): self.__toklist = toklist[:] else: self.__toklist = [toklist] self.__tokdict = dict()
openTag = "<" + Keyword(tagStr) + Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + Optional("/",default="").setResultsName("empty") + ">"
openTag = Suppress("<") + Keyword(tagStr) + \ Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" tagAttrName = Word(alphanums) if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = "<" + Keyword(tagStr) + Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttr...
openTag = "<" + Keyword(tagStr,caseless=True) + Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + Suppress("=") + tagAttrValue ))) + Optional("/",default="").setResultsName("empty") + ">" closeTag = "</" + Keyword(tagStr,caseless=not xml) + ">"
openTag = Suppress("<") + Keyword(tagStr,caseless=True) + \ Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \ Suppress("=") + tagAttrValue ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") closeTag = Combine("</" + Keyword(tagStr,cas...
def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" tagAttrName = Word(alphanums) if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = "<" + Keyword(tagStr) + Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttr...
cStyleComment = Regex(r"\/\*[\s\S]*?\*\/")
cStyleComment = Regex(r"\/\*[\s\S]*?\*\/").setName("C style comment")
def makeXMLTags(tagStr): """Helper to construct opening and closing tag expressions for XML, given a tag name""" return _makeTags( tagStr, True )
dblSlashComment = Regex(r"\/\/.*") cppStyleComment = Regex(r"(\/\*[\s\S]*?\*\/)|(\/\/.*)")
dblSlashComment = Regex(r"\/\/.*").setName("// comment") cppStyleComment = Regex(r"(\/\*[\s\S]*?\*\/)|(\/\/.*)").setName("C++ style comment")
def makeXMLTags(tagStr): """Helper to construct opening and closing tag expressions for XML, given a tag name""" return _makeTags( tagStr, True )
out += [ nl, nextLevelIndent, "<", resTag, ">", _ustr(res), "</", resTag, ">" ]
xmlBodyText = xml.sax.saxutils.escape(_ustr(res)) out += [ nl, nextLevelIndent, "<", resTag, ">", xmlBodyText, "</", resTag, ">" ]
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ): """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.""" nl = "\n" out = [] namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items() for v in vlist ] ) nextLevelIndent = in...
out.append( dump(v,indent,depth+1) )
out.append( v.dump(indent,depth+1) )
def dump(self,indent='',depth=0): """Diagnostic method for listing out the contents of a ParseResults. Accepts an optional indent argument so that this string can be embedded in a nested display of other data.""" out = [] keys = self.items() keys.sort() for k,v in keys: if out: out.append('\n') out.append( "%s%s- %s: "...
cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
def copy( self ): """Make a copy of this ParserElement. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element.""" cpy = copy.copy( self ) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] cpy.whiteChars = ParserElement.DEFAULT_WHI...
for i in xrange(len(self.endQuoteChar)-1,0,-1)]) + ')'
for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')'
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None): """ Defined with the following parameters: - quoteChar - string of one or more characters defining the quote delimiting string - escChar - character to escape quotes, typically backslash (default=None) ...
self.whiteChars = "".join([c for c in self.whiteChars if c not in self.matchWhite])
self.setWhitespaceChars( "".join([c for c in self.whiteChars if c not in self.matchWhite]) )
def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0): super(White,self).__init__() self.matchWhite = ws self.whiteChars = "".join([c for c in self.whiteChars if c not in self.matchWhite]) #~ self.leaveWhitespace() self.name = ("".join([White.whiteStrs[c] for c in self.matchWhite])) self.mayReturnEmpty = True self.er...
self.whiteChars = " \t"
self.setWhitespaceChars( " \t" )
def __init__( self ): super(LineStart,self).__init__() self.whiteChars = " \t" self.errmsg = "Expected start of line" self.myException.msg = self.errmsg
self.whiteChars = " \t"
self.setWhitespaceChars( " \t" )
def __init__( self ): super(LineEnd,self).__init__() self.whiteChars = " \t" self.errmsg = "Expected end of line" self.myException.msg = self.errmsg
self.whiteChars = exprs[0].whiteChars
self.setWhitespaceChars( exprs[0].whiteChars )
def __init__( self, exprs, savelist = True ): super(And,self).__init__(exprs, savelist) self.mayReturnEmpty = True for e in self.exprs: if not e.mayReturnEmpty: self.mayReturnEmpty = False break self.skipWhitespace = exprs[0].skipWhitespace self.whiteChars = exprs[0].whiteChars
missing = ", ".join( [ str(e) for e in tmpReqd ] )
missing = ", ".join( [ _ustr(e) for e in tmpReqd ] )
def parseImpl( self, instring, loc, doActions=True ): tmpLoc = loc tmpReqd = self.required[:] tmpOpt = self.optionals[:] matchOrder = []
self.whiteChars = expr.whiteChars
self.setWhitespaceChars( expr.whiteChars )
def __init__( self, expr, savelist=False ): super(ParseElementEnhance,self).__init__(savelist) if isinstance( expr, basestring ): expr = Literal(expr) self.expr = expr self.strRepr = None if expr is not None: self.mayIndexError = expr.mayIndexError self.skipWhitespace = expr.skipWhitespace self.whiteChars = expr.whiteC...
Note: take care when assigning to Forward to not overlook precedence of operators.
Note: take care when assigning to Forward not to overlook precedence of operators.
def parseImpl( self, instring, loc, doActions=True ): startLoc = loc instrlen = len(instring) expr = self.expr while loc < instrlen: try: loc = expr.skipIgnorables( instring, loc ) expr._parse( instring, loc, doActions=False, callPreParse=False ) if self.includeMatch: skipText = instring[startLoc:loc] loc,mat = expr._p...
dlName = _ustr(expr)+u" ["+_ustr(delim)+u" "+_ustr(expr)+u"]..."
dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
def delimitedList( expr, delim=",", combine=False ): """Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing 'combine=True' in the constructor. If combine is set...
_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in xrange(ord(p[0]),ord(p[1])+1) ]) or p)
_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
def dictOf( key, value ): """Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the Dict, ZeroOrMore, and Group tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, t...
exprArgCache = {}
def nullDebugAction(*args): """'Do-nothing' debug action, to suppress debugging output during parsing.""" pass
super(CaselessKeyword,self).__init__( matchString, identCars, caseless=True )
super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ): super(CaselessKeyword,self).__init__( matchString, identCars, caseless=True )
return self.expr.parse( instring, loc, doActions ) else: raise ParseException(instring,loc,"",self)
lookup = (self,instring,loc,doActions) try: value = ParserElement.exprArgCache[ lookup ] if isinstance(value,ParseException): raise value return value except KeyError: try: ParserElement.exprArgCache[ lookup ] = value = self.expr.parse( instring, loc, doActions ) return value except ParseException, pe: ParserElement.ex...
def parseImpl( self, instring, loc, doActions=True ): if self.expr is not None: return self.expr.parse( instring, loc, doActions ) else: raise ParseException(instring,loc,"",self)
if isinstance(strs,list):
if isinstance(strs,(list,tuple)):
def oneOf( strs, caseless=False, useRegex=True ): """Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a MatchFirst for best performance. Parameters: - strs - a string of space-delimited literals, or a...
s.myException.msg = self.errmsg
self.myException.msg = self.errmsg
def __init__( self ): super(NoMatch,self).__init__() self.name = "NoMatch" self.mayReturnEmpty = True self.mayIndexError = False self.errmsg = "Unmatchable token" s.myException.msg = self.errmsg
maxloc = min( maxloc, len(instring) )
maxloc = min( maxloc, instrlen )
def parseImpl( self, instring, loc, doActions=True ): if not(instring[ loc ] in self.initChars): #~ raise ParseException, ( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc start = loc loc += 1 bodychars = self.bodyChars maxloc = start + self.maxLen maxloc = min( maxloc, l...
if self.maxSpecified and loc < len(instring) and instring[loc] in bodychars:
if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
def parseImpl( self, instring, loc, doActions=True ): if not(instring[ loc ] in self.initChars): #~ raise ParseException, ( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc start = loc loc += 1 bodychars = self.bodyChars maxloc = start + self.maxLen maxloc = min( maxloc, l...
printablesLessRAbrack = "".join( [ c for c in string.printable if c not in ">" ] )
printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] )
def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" tagAttrName = Word(alphanums) if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = "<" + Keyword(tagStr) + Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttr...
openTag = openTag.setResultsName("start"+tagStr.title()).setName("<"+tagStr+">") closeTag = closeTag.setResultsName("end"+tagStr.title()).setName("</"+tagStr+">")
openTag = openTag.setResultsName("start"+tagStr.title()).setName("<%s>" % tagStr) closeTag = closeTag.setResultsName("end"+tagStr.title()).setName("</%s>" % tagStr)
def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" tagAttrName = Word(alphanums) if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = "<" + Keyword(tagStr) + Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttr...
if isinstance(tokens,tuple): tokens = tokens[1] warnings.warn("Returning loc from parse actions is deprecated, return only modified tokens", DeprecationWarning,stacklevel=2)
def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ): debugging = ( self.debug ) #and doActions )
except Exception, pe:
except ParseBaseException, pe:
def _parseCache( self, instring, loc, doActions=True, callPreParse=True ): lookup = (self,instring,loc,callPreParse) if lookup in ParserElement._exprArgCache: value = ParserElement._exprArgCache[ lookup ] if isinstance(value,Exception): if isinstance(value,ParseBaseException): value.loc = loc raise value return value e...
except Exception,e:
except sre_constants.error,e:
def __init__( self, pattern, flags=0): """The parameters pattern and flags are passed to the re.compile() function as-is. See the Python re module for an explanation of the acceptable patterns and flags.""" super(Regex,self).__init__() if len(pattern) == 0: warnings.warn("null string passed to Regex; use Empty() inste...
for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')'
for i in xrange(len(self.endQuoteChar)-1,0,-1)]) + ')'
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None): """ Defined with the following parameters: - quoteChar - string of one or more characters defining the quote delimiting string - escChar - character to escape quotes, typically backslash (default=None) ...
except Exception,e:
except sre_constants.error,e:
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None): """ Defined with the following parameters: - quoteChar - string of one or more characters defining the quote delimiting string - escChar - character to escape quotes, typically backslash (default=None) ...
else: return loc, []
elif loc == len(instring): return loc+1, [] else: exc = self.myException exc.loc = loc exc.pstr = instring raise exc
def parseImpl( self, instring, loc, doActions=True ): if loc<len(instring): if instring[loc] == "\n": return loc+1, "\n" else: #~ raise ParseException( instring, loc, "Expected end of line" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc else: return loc, []
return loc, []
elif loc == len(instring): return loc+1, [] else: exc = self.myException exc.loc = loc exc.pstr = instring raise exc
def parseImpl( self, instring, loc, doActions=True ): if loc < len(instring): #~ raise ParseException( instring, loc, "Expected end of text" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, []
self.errmsg = "Found unexpected token, "+_ustr(self.expr)
self.errmsg = "Found unwanted token, "+_ustr(self.expr)
def __init__( self, expr ): super(NotAny,self).__init__(expr) #~ self.leaveWhitespace() self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs self.mayReturnEmpty = True self.errmsg = "Found unexpected token, "+_ustr(self.expr) self.myException = ParseException("",0,self.errm...
except Exception,e: print "
def parseImpl( self, instring, loc, doActions=True ): tokens = [] try: loc, tokens = self.expr._parse( instring, loc, doActions ) hasIgnoreExprs = ( len(self.ignoreExprs) > 0 ) while 1: if hasIgnoreExprs: loc = self.skipIgnorables( instring, loc ) loc, tmptokens = self.expr._parse( instring, loc, doActions ) if tmptoke...
return Combine( expr + ZeroOrMore( delim + expr ) ).setName(_ustr(expr)+_ustr(delim)+"...")
return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
def delimitedList( expr, delim=",", combine=False ): """Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing 'combine=True' in the constructor. If combine is set...
return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(_ustr(expr)+_ustr(delim)+"...")
return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
def delimitedList( expr, delim=",", combine=False ): """Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing 'combine=True' in the constructor. If combine is set...
_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in xrange(ord(p[0]),ord(p[1])+1) ]) or p)
def dictOf( key, value ): """Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the Dict, ZeroOrMore, and Group tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, t...
self[name] = (toklist.copy(),-1)
self[name] = ParseResultsWithOffset(toklist.copy(),-1)
def __init__( self, toklist, name=None, asList=True, modal=True ): if self.__doinit: self.__doinit = False self.__name = None self.__parent = None self.__accumNames = {} if isinstance(toklist, list): self.__toklist = toklist[:] else: self.__toklist = [toklist] self.__tokdict = dict()
self[name] = (ParseResults(toklist[0]),-1)
self[name] = ParseResultsWithOffset(ParseResults(toklist[0]),-1)
def __init__( self, toklist, name=None, asList=True, modal=True ): if self.__doinit: self.__doinit = False self.__name = None self.__parent = None self.__accumNames = {} if isinstance(toklist, list): self.__toklist = toklist[:] else: self.__toklist = [toklist] self.__tokdict = dict()
if isinstance(v,tuple):
if isinstance(v,ParseResultsWithOffset):
def __setitem__( self, k, v ): if isinstance(v,tuple): self.__tokdict[k] = self.__tokdict.get(k,list()) + [v] sub = v[0] elif isinstance(k,int): self.__toklist[k] = v sub = v else: self.__tokdict[k] = self.__tokdict.get(k,list()) + [(v,0)] sub = v if isinstance(sub,ParseResults): sub.__parent = self
otherdictitems = [(k,(v[0],addoffset(v[1])) ) for (k,vlist) in otheritems for v in vlist]
otherdictitems = [(k, ParseResultsWithOffset(v[0],addoffset(v[1])) ) for (k,vlist) in otheritems for v in vlist]
def __iadd__( self, other ): if other.__tokdict: offset = len(self.__toklist) addoffset = ( lambda a: (a<0 and offset) or (a+offset) ) otheritems = other.__tokdict.items() otherdictitems = [(k,(v[0],addoffset(v[1])) ) for (k,vlist) in otheritems for v in vlist] for k,v in otherdictitems: self[k] = v if isinstance(v[0],...
tokenlist[ikey] = ("",i)
tokenlist[ikey] = ParseResultsWithOffset("",i)
def postParse( self, instring, loc, tokenlist ): for i,tok in enumerate(tokenlist): ikey = _ustr(tok[0]).strip() if len(tok)==1: tokenlist[ikey] = ("",i) elif len(tok)==2 and not isinstance(tok[1],ParseResults): tokenlist[ikey] = (tok[1],i) else: dictvalue = tok.copy() #ParseResults(i) del dictvalue[0] if len(dictvalue...
tokenlist[ikey] = (tok[1],i)
tokenlist[ikey] = ParseResultsWithOffset(tok[1],i)
def postParse( self, instring, loc, tokenlist ): for i,tok in enumerate(tokenlist): ikey = _ustr(tok[0]).strip() if len(tok)==1: tokenlist[ikey] = ("",i) elif len(tok)==2 and not isinstance(tok[1],ParseResults): tokenlist[ikey] = (tok[1],i) else: dictvalue = tok.copy() #ParseResults(i) del dictvalue[0] if len(dictvalue...
tokenlist[ikey] = (dictvalue,i)
tokenlist[ikey] = ParseResultsWithOffset(dictvalue,i)
def postParse( self, instring, loc, tokenlist ): for i,tok in enumerate(tokenlist): ikey = _ustr(tok[0]).strip() if len(tok)==1: tokenlist[ikey] = ("",i) elif len(tok)==2 and not isinstance(tok[1],ParseResults): tokenlist[ikey] = (tok[1],i) else: dictvalue = tok.copy() #ParseResults(i) del dictvalue[0] if len(dictvalue...
tokenlist[ikey] = (dictvalue[0],i)
tokenlist[ikey] = ParseResultsWithOffset(dictvalue[0],i)
def postParse( self, instring, loc, tokenlist ): for i,tok in enumerate(tokenlist): ikey = _ustr(tok[0]).strip() if len(tok)==1: tokenlist[ikey] = ("",i) elif len(tok)==2 and not isinstance(tok[1],ParseResults): tokenlist[ikey] = (tok[1],i) else: dictvalue = tok.copy() #ParseResults(i) del dictvalue[0] if len(dictvalue...
(_escapeRegexChars(self.initCharsOrig),
(re.escape(self.initCharsOrig),
def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0 ): super(Word,self).__init__() self.initCharsOrig = initChars self.initChars = _str2dict(initChars) if bodyChars : self.bodyCharsOrig = bodyChars self.bodyChars = _str2dict(bodyChars) else: self.bodyCharsOrig = initChars self.bodyChars = _str2dict(ini...
( _escapeRegexChars(self.quoteChar),
( re.escape(self.quoteChar),
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True): """ Defined with the following parameters: - quoteCharacter - string of one or more characters defining the quote delimiting string - escapeCharacter - character to escape quotes, typically backslash (default=None) - esca...
'|(' + ')|('.join("%s[^%s]" % (_escapeRegexChars(self.quoteChar[:i]),
'|(' + ')|('.join("%s[^%s]" % (re.escape(self.quoteChar[:i]),
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True): """ Defined with the following parameters: - quoteCharacter - string of one or more characters defining the quote delimiting string - escapeCharacter - character to escape quotes, typically backslash (default=None) - esca...
self.pattern += (r'|(%s)' % _escapeRegexChars(escQuote))
self.pattern += (r'|(%s)' % re.escape(escQuote))
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True): """ Defined with the following parameters: - quoteCharacter - string of one or more characters defining the quote delimiting string - escapeCharacter - character to escape quotes, typically backslash (default=None) - esca...
self.pattern += (r'|(%s.)' % _escapeRegexChars(escChar)) self.escCharReplacePattern = self.escChar+"(.)" self.pattern += (r')*%s' % _escapeRegexChars(self.quoteChar))
self.pattern += (r'|(%s.)' % re.escape(escChar)) self.escCharReplacePattern = re.escape(self.escChar)+"(.)" self.pattern += (r')*%s' % re.escape(self.quoteChar))
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True): """ Defined with the following parameters: - quoteCharacter - string of one or more characters defining the quote delimiting string - escapeCharacter - character to escape quotes, typically backslash (default=None) - esca...
ret = ParseResults(result.group())
ret = result.group()
def parseImpl( self, instring, loc, doActions=True ): result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None if not result: exc = self.myException exc.loc = loc exc.pstr = instring raise exc loc = result.end() ret = ParseResults(result.group()) if self.unquoteResults: # strip off quote...
if self.escChar: ret = re.sub(self.escCharReplacePattern,"\g<1>",ret) if self.escQuote: ret.replace(self.escQuote, self.quoteChar) return loc,ret
if isinstance(ret,basestring): if self.escChar: ret = re.sub(self.escCharReplacePattern,"\g<1>",ret) if self.escQuote: ret = ret.replace(self.escQuote, self.quoteChar) return loc, ret
def parseImpl( self, instring, loc, doActions=True ): result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None if not result: exc = self.myException exc.loc = loc exc.pstr = instring raise exc loc = result.end() ret = ParseResults(result.group()) if self.unquoteResults: # strip off quote...
def _escapeRegexChars(s): for c in r"\[^$.|?*+()": s = s.replace(c,"\\"+c) s = s.replace("\n",r"\n") s = s.replace("\t",r"\t") return _ustr(s)
def _escapeRegexChars(s): #~ escape these chars: [\^$.|?*+() for c in r"\[^$.|?*+()": s = s.replace(c,"\\"+c) s = s.replace("\n",r"\n") s = s.replace("\t",r"\t") return _ustr(s)
return Regex( "|".join( [ _escapeRegexChars(sym) for sym in symbols] ) )
return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) )
def oneOf( strs, caseless=False, useRegex=True ): """Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a MatchFirst for best performance. """ if caseless: isequal = ( lambda a,b: a.upper() == b.upper() ...
expr.tryParse(instring, loc)
loc = expr.skipIgnorables( instring, loc ) expr.parse( instring, loc, doActions=False, callPreParse=False )
def parseImpl( self, instring, loc, doActions=True ): startLoc = loc instrlen = len(instring) expr = self.expr while loc < instrlen: try: expr.tryParse(instring, loc) if self.includeMatch: skipText = instring[startLoc:loc] loc,mat = expr.parse(instring,loc) if mat: return loc, [ skipText, mat ] else: return loc, [ skip...
f = os.popen('cpp -dM ../../pjlib/include/pj/config_site.h | grep PJ')
f = os.popen('cpp -dM -I../../pjlib/include ../../pjlib/include/pj/config_site.h | grep PJ')
def print_html_report(): # Get Revision info. f = os.popen('svn info | grep Revision') revision = f.readline().split()[1] # Get Machine, OS, and CC name f = os.popen('make -f Footprint.mak print_name') names = f.readline().split() m = names[0] o = names[1] cc = names[2] cc_ver = names[3] # Open HTML file filename = ...
"""Sets the ID, id can be either a list, following the
"""Set the ID, ie. the values for primary keys. id can be either a list, following the
def _setID(self, id): """Sets the ID, id can be either a list, following the _sqlPrimary, or some other type, that will be set as the singleton ID (requires 1-length sqlPrimary). """ if type(id) in (types.ListType, types.TupleType): try: for key in self._sqlPrimary: value = id[0] self.__dict__[key] = value id = id[1:]...
"""Will be called when an unknown key is to be
"""Get an attribute, normally a SQL field value. Will be called when an unknown key is to be
def __getattr__(self, key): """Will be called when an unknown key is to be retrieved, ie. most likely one of our database fields.""" if self._sqlFields.has_key(key): if not self._updated: self.load() return self._values[key] else: raise AttributeError, key
"""Will be called whenever something needs to be set, so
"""Set an attribute, normally a SQL field value. Will be called whenever something needs to be set, so
def __setattr__(self, key, value): """Will be called whenever something needs to be set, so we store the value as a SQL-thingie unless the key is not listed in sqlFields.""" if key not in self._sqlPrimary and self._sqlFields.has_key(key): if not self._updated: self.load() self._values[key] = value self._changed = time....
"""Saves the object on deletion. Be aware of this. If you want to undo some change, use reset() first.
"""Save the object on deletion. Be aware of this. If you want to undo some change, use reset() first.
def __del__(self): """Saves the object on deletion. Be aware of this. If you want to undo some change, use reset() first. Be aware of Python 2.2's garbage collector, that might run in the background. This means that unless you call save() changes might not be done immediately in the database.
(Remember: Others might reference the object already, expecting something else!) Override this method if you add properties not defined in _sqlFields"""
(Remember: Others might reference the object already, expecting something else!) Override this method if you add properties not defined in _sqlFields. """
def reset(self): """Reset all fields, almost like creating a new object. Note: Forgets changes you have made not saved to database! (Remember: Others might reference the object already, expecting something else!) Override this method if you add properties not defined in _sqlFields""" self._resetID() self._new = None se...
"""Marks this object for deletion in the database.
"""Mark this object for deletion in the database.
def delete(self): """Marks this object for deletion in the database. The object will then be reset and ready for use again with a new id.""" (sql, ) = self._prepareSQL("DELETE") curs = self.cursor() curs.execute(sql, self._getID()) curs.close() self.reset()
"""Returns a sql for the given operation.
"""Return a sql for the given operation.
def _prepareSQL(cls, operation="SELECT", where=None, selectfields=None, orderBy=None): """Returns a sql for the given operation. Possible operations: SELECT read data for this id SELECTALL read data for all ids INSERT insert data, create new id UPDATE update data for this id DELETE re...
for multi _sqlPrimary classes. Return a tupple.
for multi _sqlPrimary classes. Return a tuple.
def _prepareSQL(cls, operation="SELECT", where=None, selectfields=None, orderBy=None): """Returns a sql for the given operation. Possible operations: SELECT read data for this id SELECTALL read data for all ids INSERT insert data, create new id UPDATE update data for this id DELETE re...
"""Returns a new sequence number for insertion in self._sqlTable.
"""Return a new sequence number for insertion in self._sqlTable.
def _nextSequence(cls, name=None): """Returns a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full sequence name as an optional argument to _...
fields should be the attribute names that
``fields`` should be the attribute names that
def _loadFromRow(self, result, fields, cursor): """Load from a database row, described by fields. fields should be the attribute names that will be set. Note that userclasses will be created (but not loaded).""" position = 0 for elem in fields: value = result[position] valueType = cursor.description[position][1] if has...
"""Retrieves every object, possibly limitted by the where list of clauses that will be AND-ed). Since this an iterator is returned, only buffer rows are loaded
"""Retrieve every object as an iterator. Possibly limitted by the where list of clauses that will be AND-ed. Since an iterator is returned, only ``buffer`` rows are loaded
def getAllIterator(cls, where=None, buffer=100, useObject=None, orderBy=None): """Retrieves every object, possibly limitted by the where list of clauses that will be AND-ed). Since this an iterator is returned, only buffer rows are loaded from the database at once. This is useful if you need to process all objects. If ...
to process all objects. If useObject is given, this object is returned each time, but with new data.
to process all objects. If useObject is given, this object is returned each time, but with new data. This can be used to avoid creating many new objects when only one object is needed each time.
def getAllIterator(cls, where=None, buffer=100, useObject=None, orderBy=None): """Retrieves every object, possibly limitted by the where list of clauses that will be AND-ed). Since this an iterator is returned, only buffer rows are loaded from the database at once. This is useful if you need to process all objects. If ...
raise "Bad sqlPrimary, should be a list or tupple: %s" % cls._sqlPrimary
raise "Bad sqlPrimary, should be a list or tuple: %s" % cls._sqlPrimary
def getNext(rows=[]): forgetter = cls if not rows: rows += curs.fetchmany(buffer) if not rows: curs.close() return None row = rows[0] del rows[0] try: idPositions = [fields.index(key) for key in cls._sqlPrimary] except ValueError: raise "Bad sqlPrimary, should be a list or tupple: %s" % cls._sqlPrimary ids = [row[pos] ...
"""Retrieves a list of of all possible instances of this class. The list is composed of tupples in the format (id, description) -
"""Retrieve a list of of all possible instances of this class. The list is composed of tuples in the format (id, description) -
def getAllText(cls, where=None, SEPERATOR=' ', orderBy=None): """Retrieves a list of of all possible instances of this class. The list is composed of tupples in the format (id, description) - where description is a string composed by the fields from cls._shortView, joint with SEPERATOR.
if not self._validID():
if self._new:
def _saveDB(self): """Overloaded - we dont have nextval() in mysql""" # We're a "fresh" copy now self._updated = time.time() if not self._validID(): operation = 'INSERT' self._resetID() # Ie. get a new one else: operation = 'UPDATE' (sql, fields) = self._prepareSQL(operation) values = [] for field in fields: value = ge...
self._resetID()
def _saveDB(self): """Overloaded - we dont have nextval() in mysql""" # We're a "fresh" copy now self._updated = time.time() if not self._validID(): operation = 'INSERT' self._resetID() # Ie. get a new one else: operation = 'UPDATE' (sql, fields) = self._prepareSQL(operation) values = [] for field in fields: value = ge...
self._setID(cursor.insert_id())
if not self._validID(): if not len(self._getID()) == 1: raise "Can't retrieve auto-inserted ID for multiple-primary-key" self._setID(cursor.insert_id())
def _saveDB(self): """Overloaded - we dont have nextval() in mysql""" # We're a "fresh" copy now self._updated = time.time() if not self._validID(): operation = 'INSERT' self._resetID() # Ie. get a new one else: operation = 'UPDATE' (sql, fields) = self._prepareSQL(operation) values = [] for field in fields: value = ge...
name = cls._sqlFields['id'].replace('.','_') + '_seq'
if len(cls._sqlPrimary) <> 1: raise "Could not guess sequence name for multi-primary-key" primary = cls._sqlPrimary[0] name = primary.replace('.','_') + '_seq'
def _nextSequence(cls, name=None): """Returns a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full sequence name as an optional argument to _ne...
print 'index.html...',
print 'download.ht...',
def do_bump(newvers): print 'doing bump...', # hack the index.html file print 'index.html...', fp = open('admin/www/download.ht', 'r+') text = fp.read() parts = string.split(text, '<!-VERSION--->') parts[1] = newvers text = string.join(parts, '<!-VERSION--->') parts = string.split(text, '<!-DATE--->') timestr = time.ct...
('<p>' + _(' There currently are no publicly-advertised '), Link(mm_cfg.MAILMAN_URL, 'Mailman'), _(' mailing lists on %(hostname)s.')))
_('''<p>There currently are no publicly-advertised %(mailmanlink)s mailing lists on %(hostname)s.'''))
def listinfo_overview(msg=''): # Present the general listinfo overview hostname = Utils.get_domain() # Set up the document and assign it the correct language. The only one we # know about at the moment is the server's default. doc = Document() doc.set_language(mm_cfg.DEFAULT_SERVER_LANGUAGE) legend = _("%(hostname)s ...
subscriptions = '' if cgidata.has_key('subscribees'): subscriptions += cgidata['subscribees'].value if cgidata.has_key('subscribees_upload') and \ cgidata['subscribees_upload'].value: subscriptions += cgidata['subscribees_upload'].value if subscriptions: subscriptions.replace('\r', '') names = filter(None, [unquote(n.s...
subscribers = '' subscribers += cgidata.getvalue('subscribees', '') subscribers += cgidata.getvalue('subscribees_upload', '') if subscribers: names = filter(None, [unquote(n.strip()) for n in subscribers.replace('\r','').split(NL)]) send_welcome_msg = mlist.send_welcome_msg if cgidata.has_key('send_welcome_msg_to_this_...
def change_options(mlist, category, cgidata, doc): confirmed = 0 # Handle changes to the list moderator password. Do this before checking # the new admin password, since the latter will force a reauthentication. new = cgidata.getvalue('newmodpw', '').strip() confirm = cgidata.getvalue('confirmmodpw', '').strip() if ne...
result = mlist.ApprovedAddMembers(names, None, digest, None, send_welcome_msg)
result = mlist.ApprovedAddMembers(names, None, digest, ack=send_welcome_msg, admin_notif=send_admin_notif)
def change_options(mlist, category, cgidata, doc): confirmed = 0 # Handle changes to the list moderator password. Do this before checking # the new admin password, since the latter will force a reauthentication. new = cgidata.getvalue('newmodpw', '').strip() confirm = cgidata.getvalue('confirmmodpw', '').strip() if ne...
self._tmp_lock = lock self._lock_file = None self._internal_name = name self._ready = 0 self._log_files = {}
self.InitTempVars(name, lock)
def __init__(self, name=None, lock=1):
if name not in Utils.list_names(): raise Errors.MMUnknownListError, 'list not found: %s' % name
def __init__(self, name=None, lock=1):
self._mime_separator = '__--__--'
def InitVars(self, name=None, admin='', crypted_password=''): """Assign default values - some will be overriden by stored state."""
HTMLFormatter.InitTempVars(self)
def InitVars(self, name=None, admin='', crypted_password=''): """Assign default values - some will be overriden by stored state."""
if reduce(operator.__add__, v.values()): print >> fp, ' v = v.keys() v.sort() if not options.writelocations: pass elif options.locationstyle == options.SOLARIS: for filename, lineno in v: d = {'filename': filename, 'lineno': lineno} print >>fp, _(' elif options.locationstyle == options.GNU: locline = ' for filena...
keys = v.keys() keys.sort() reverse.setdefault(tuple(keys), []).append((k, v)) rkeys = reverse.keys() rkeys.sort() for rkey in rkeys: rentries = reverse[rkey] rentries.sort() for k, v in rentries: if reduce(operator.__add__, v.values()): print >> fp, ' v = v.keys() v.sort() if not options.writelocations: pass el...
def write(self, fp): options = self.__options timestamp = time.ctime(time.time()) # The time stamp in the header doesn't have the same format as that # generated by xgettext... print >> fp, pot_header % {'time': timestamp, 'version': __version__} for k, v in self.__messages.items(): # If the entry was gleaned out of a ...
locline = " if len(locline) > 2: print >> fp, locline print >> fp, 'msgid', normalize(k) print >> fp, 'msgstr ""\n'
print >> fp, 'msgid', normalize(k) print >> fp, 'msgstr ""\n'
def write(self, fp): options = self.__options timestamp = time.ctime(time.time()) # The time stamp in the header doesn't have the same format as that # generated by xgettext... print >> fp, pot_header % {'time': timestamp, 'version': __version__} for k, v in self.__messages.items(): # If the entry was gleaned out of a ...
self._response_buffer = '' self._cmd_dispatch = { 'subscribe' : self.ProcessSubscribeCmd, 'confirm': self.ProcessConfirmCmd,
self.__errors = 0 self.__respbuf = '' self.__dispatch = { 'subscribe' : self.ProcessSubscribeCmd, 'confirm' : self.ProcessConfirmCmd,
def __init__(self):
def AddToResponse(self, text): self._response_buffer = self._response_buffer + text + "\n" def AddError(self, text): self._response_buffer = self._response_buffer + "**** " + text + "\n"
def AddToResponse(self, text, trunc=MAXCOLUMN): if text and text[-1] == '\n': text = text[:-1] if trunc and len(text) > trunc: text = text[:trunc-3] + '...' self.__respbuf = self.__respbuf + text + "\n" def AddError(self, text, prefix='>>>>> ', trunc=MAXCOLUMN): self.__errors = self.__errors + 1 self.AddToResponse(pr...
def AddToResponse(self, text):
mail = Message.IncomingMessage() subject = mail.getheader("subject") sender = string.lower(mail.GetSender())
msg = Message.IncomingMessage() subject = msg.getheader("subject") sender = string.lower(msg.GetSender())
def ParseMailCommands(self):
mail.getheader('from'),
msg.getheader('from'),
def ParseMailCommands(self):
if (subject and self._cmd_dispatch.has_key(string.split(subject)[0])): lines = [subject] + string.split(mail.body, '\n')
if (subject and self.__dispatch.has_key(string.split(subject)[0])): lines = [subject] + string.split(msg.body, '\n')
def ParseMailCommands(self):
lines = string.split(mail.body, '\n')
lines = string.split(msg.body, '\n')
def ParseMailCommands(self):
conf_pat = (r"%s -- confirmation of subscription" r" -- request (\d\d\d\d\d\d)"
conf_pat = (r'%s -- confirmation of subscription' r' -- request (\d{6})'
def ParseMailCommands(self):
match = re.search(conf_pat, subject) if not match: match = re.search(conf_pat, mail.body) if match: lines = ["confirm %s" % (match.group(1))]
mo = re.search(conf_pat, subject) if not mo: mo = re.search(conf_pat, msg.body) if mo: lines = ["confirm %s" % (mo.group(1))]
def ParseMailCommands(self):