desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Add a notnull constraint to a field'
def add_notnull(self, tablename, fieldname):
db = self.db db_engine = self.db_engine if (db_engine == 'sqlite'): raise NotImplementedError elif (db_engine == 'mysql'): raise NotImplementedError elif (db_engine == 'postgres'): sql = ('ALTER TABLE %(tablename)s ALTER COLUMN %(fieldname)s SET NOT NU...
'Drop a field from a table e.g. for when changing type'
def drop_field(self, tablename, fieldname):
db = self.db db_engine = self.db_engine if (db_engine == 'sqlite'): sql = '' elif (db_engine == 'mysql'): sql = ('ALTER TABLE %(tablename)s DROP COLUMN %(fieldname)s;' % dict(tablename=tablename, fieldname=fieldname)) elif (db_engine == 'postgres'): sql = ('ALT...
'Modify the ondelete constraint for a foreign key'
def ondelete(self, tablename, fieldname, reftable, ondelete):
db = self.db db_engine = self.db_engine executesql = db.executesql if (tablename == 'all'): tables = db.tables else: tables = [tablename] for tablename in tables: if (fieldname not in db[tablename].fields): continue if (db_engine == 'sqlite'): ...
'Remove a Foreign Key constraint from a table'
def remove_foreign(self, tablename, fieldname):
db = self.db db_engine = self.db_engine executesql = db.executesql if (tablename == 'all'): tables = db.tables else: tables = [tablename] for tablename in tables: if (fieldname not in db[tablename].fields): continue if (db_engine == 'sqlite'): ...
'Remove a notnull constraint from a field'
def remove_notnull(self, tablename, fieldname):
db = self.db db_engine = self.db_engine if (db_engine == 'sqlite'): raise NotImplementedError elif (db_engine == 'mysql'): raise NotImplementedError elif (db_engine == 'postgres'): sql = ('ALTER TABLE %(tablename)s ALTER COLUMN %(fieldname)s DROP NOT N...
'Remove a Unique Index from a table'
def remove_unique(self, tablename, fieldname):
db = self.db db_engine = self.db_engine if (db_engine == 'sqlite'): raise NotImplementedError elif (db_engine == 'mysql'): sql = ('ALTER TABLE `%(tablename)s` DROP INDEX `%(fieldname)s`;' % dict(tablename=tablename, fieldname=fieldname)) elif (db_engine == 'postgres'):...
'Rename a field, while keeping the other properties of the field the same. If there are some indexes on that table, these will be recreated and other constraints will remain unchanged too. @param tablename : name of the table in which the field is renamed @param fieldname_old : name of the original field ...
def rename_field(self, tablename, fieldname_old, fieldname_new, attributes_to_copy=None):
db = self.db db_engine = self.db_engine if (db_engine == 'sqlite'): self._add_renamed_fields(db, tablename, fieldname_old, fieldname_new, attributes_to_copy) self._copy_field(db, tablename, fieldname_old, fieldname_new) sql = ("SELECT sql FROM sqlite_master WHERE type=...
'Rename a table. If any fields reference that table, they will be handled too. @param tablename_old : name of the original table before renaming @param tablename_new : name of the table after renaming'
def rename_table(self, tablename_old, tablename_new):
try: sql = ('ALTER TABLE %s RENAME TO %s;' % (tablename_old, tablename_new)) self.db.executesql(sql) except Exception as e: print e
'This method handles the migration in which a new table with a column for the values they\'ll get from the list field is made and maybe some empty columns to be filled in later. That new table has a foreign key reference back to the original table. Then for each value in the list field for each record in the original t...
def list_field_to_reference(self, tablename_new, new_list_field, list_field_name, table_old_id_field, tablename_old):
self._create_new_table(tablename_new, new_list_field, list_field_name, table_old_id_field, tablename_old) self._fill_the_new_table(tablename_new, new_list_field, list_field_name, table_old_id_field, tablename_old)
'Add values to a new field according to the mappings given through the mapping_function @param tablename : name of the original table in which the new unique field id added @param field_to_update : name of the field to be updated according to the mapping @param mapping_function : class instance containing the m...
def migrate_to_unique_field(self, tablename, field_to_update, mapping_function, list_of_tables=None):
db = self.db self._add_new_fields(db, field_to_update, tablename) self._add_tables_temp_db(db, list_of_tables) self.update_field_by_mapping(db, tablename, field_to_update, mapping_function)
'Update the values of an existing field according to the mappings given through the mapping_function - currently unused @param db : database instance @param tablename : name of the original table in which the new unique field id added @param field_to_update : name of the field to be updated accord...
def update_field_by_mapping(db, tablename, field_to_update, mapping_function):
fields = mapping_function.fields(db) table = db[tablename] if (table['id'] not in fields): fields.append(table['id']) rows = db(mapping_function.query(db)).select(*fields) if rows: try: rows[0][tablename]['id'] row_single_layer = False except KeyError:...
'This function maps the list type into individual field type which can contain the individual values of the list. Mappings - list:reference <table> --> refererence <table> - list:integer --> integer - list:string --> string'
@staticmethod def _map_type_list_field(old_type):
if (old_type == 'list:integer'): return 'integer' elif old_type.startswith('list:reference'): return old_type.strip('list:') elif (old_type == 'list:string'): return 'string'
'This function creates the new table which is used in the list_field_to_reference migration. That new table has a foreign key reference back to the original table. @param tablename : name of the new table to which the list field needs to migrated @param new_list_field : name of the field in the new table w...
def _create_new_table(self, tablename_new, new_list_field, list_field_name, table_old_id_field, tablename_old):
db = self.db new_field_type = self._map_type_list_field(db[tablename_old][list_field_name].type) new_field = Field(new_list_field, new_field_type) new_id_field = Field(('%s_%s' % (tablename_old, table_old_id_field)), ('reference %s' % tablename_old)) db.define_table(tablename, new_id_field, new_f...
'This function is used in the list_field_to_reference migration. For each value in the list field for each record in the original table, they create one record in the new table that points back to the original record. @param tablename_new : name of the new table to which the list field needs to migrated @param new...
@staticmethod def _fill_the_new_table(tablename_new, new_list_field, list_field_name, table_old_id_field, tablename_old):
update_dict = {} table_old = db[tablename_old] table_new = db[tablename_new] for row in db().select(table_old[table_old_id_field], table_old[list_field_name]): for element in row[list_field_name]: update_dict[new_list_field] = element update_dict[('%s_%s' % (tablename_old...
'Add a field in table mentioned while renaming a field. The renamed field is added separately to the table with the same properties as the original field. @param db : database instance'
@staticmethod def _add_renamed_fields(db, tablename, fieldname_old, fieldname_new, attributes_to_copy):
table = db[tablename] if hasattr(table, '_primarykey'): primarykey = table._primarykey else: primarykey = None field_new = Field(fieldname_new) for attribute in attributes_to_copy: exec_str = ('field_new.%(attribute)s = table[fieldname_old].%(attribute)s' % dict(attribu...
'Copy all the values from old_field into new_field @param db : database instance'
@staticmethod def _copy_field(db, tablename, fieldname_old, fieldname_new):
dict_update = {} field_old = db[tablename][fieldname_old] for row in db().select(field_old): dict_update[fieldname_new] = row[fieldname_old] query = (field_old == row[fieldname_old]) db(query).update(**dict_update)
'Map the web2py type into SQL type Used when writing SQL queries to change the properties of a field Mappings: string --> Varchar'
@staticmethod def map_type_web2py_to_sql(dal_type):
if (dal_type == 'string'): return 'varchar' else: return dal_type
'This function adds a new _unique_ field into the table, while keeping all the rest of the properties of the table unchanged @param db : database instance'
@staticmethod def _add_new_fields(db, new_unique_field, tablename):
new_field = Field(new_unique_field, 'integer') table = db[tablename] if hasattr(table, '_primarykey'): primarykey = table._primarykey else: primarykey = None db.define_table(tablename, table, new_field, primarykey=primarykey)
'This field adds tables to the temp_db from the global db these might be used for the running queries or validating values.'
def _add_tables_temp_db(self, temp_db, list_of_tables):
for tablename in list_of_tables: temp_db.define_table(tablename, self.db[tablename])
'supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text'
def __getattr__(self, aname):
if (aname == 'lineno'): return lineno(self.loc, self.pstr) elif (aname in ('col', 'column')): return col(self.loc, self.pstr) elif (aname == 'line'): return line(self.loc, self.pstr) else: raise AttributeError(aname)
'Extracts the exception line from the input string, and marks the location of the exception with a special symbol.'
def markInputline(self, markerString='>!<'):
line_str = self.line line_column = (self.column - 1) if markerString: line_str = ''.join([line_str[:line_column], markerString, line_str[line_column:]]) return line_str.strip()
'Returns all named result keys.'
def keys(self):
return self.__tokdict.keys()
'Removes and returns item at specified index (default=last). Will work with either numeric indices or dict-key indicies.'
def pop(self, index=(-1)):
ret = self[index] del self[index] return ret
'Returns named result matching the given key, or if there is no such name, then returns the given defaultValue or None if no defaultValue is specified.'
def get(self, key, defaultValue=None):
if (key in self): return self[key] else: return defaultValue
'Returns all named result keys and values as a list of tuples.'
def items(self):
return [(k, self[k]) for k in self.__tokdict]
'Returns all named result values.'
def values(self):
return [v[(-1)][0] for v in self.__tokdict.values()]
'Returns the parse results as a nested list of matching tokens, all converted to strings.'
def asList(self):
out = [] for res in self.__toklist: if isinstance(res, ParseResults): out.append(res.asList()) else: out.append(res) return out
'Returns the named parse results as dictionary.'
def asDict(self):
return dict(self.items())
'Returns a new copy of a ParseResults object.'
def copy(self):
ret = ParseResults(self.__toklist) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update(self.__accumNames) ret.__name = self.__name return ret
'Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.'
def asXML(self, doctag=None, namedItemsOnly=False, indent='', formatted=True):
nl = '\n' out = [] namedItems = dict([(v[1], k) for (k, vlist) in self.__tokdict.items() for v in vlist]) nextLevelIndent = (indent + ' ') if (not formatted): indent = '' nextLevelIndent = '' nl = '' selfTag = None if (doctag is not None): selfTag = doc...
'Returns the results name for this token expression.'
def getName(self):
if self.__name: return self.__name elif self.__parent: par = self.__parent() if par: return par.__lookup(self) else: return None elif ((len(self) == 1) and (len(self.__tokdict) == 1) and (self.__tokdict.values()[0][0][1] in (0, (-1)))): return ...
'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.'
def dump(self, indent='', depth=0):
out = [] out.append((indent + _ustr(self.asList()))) keys = self.items() keys.sort() for (k, v) in keys: if out: out.append('\n') out.append(('%s%s- %s: ' % (indent, (' ' * depth), k))) if isinstance(v, ParseResults): if v.keys(): ...
'Overrides the default whitespace chars'
def setDefaultWhitespaceChars(chars):
ParserElement.DEFAULT_WHITE_CHARS = chars
'Make a copy of this ParserElement. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element.'
def copy(self):
cpy = copy.copy(self) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS return cpy
'Define name for this expression, for use in debugging.'
def setName(self, name):
self.name = name self.errmsg = ('Expected ' + self.name) if hasattr(self, 'exception'): self.exception.msg = self.errmsg return self
'Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original ParserElement object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names.'
def setResultsName(self, name, listAllMatches=False):
newself = self.copy() newself.resultsName = name newself.modalResults = (not listAllMatches) return newself
'Method to invoke the Python pdb debugger when this element is about to be parsed. Set breakFlag to True to enable, False to disable.'
def setBreak(self, breakFlag=True):
if breakFlag: _parseMethod = self._parse def breaker(instring, loc, doActions=True, callPreParse=True): import pdb pdb.set_trace() return _parseMethod(instring, loc, doActions, callPreParse) breaker._originalParseMethod = _parseMethod self._parse =...
'Internal method used to decorate parse actions that take fewer than 3 arguments, so that all parse actions can be called as f(s,l,t).'
def _normalizeParseActionArgs(f):
STAR_ARGS = 4 if (f in singleArgBuiltins): numargs = 1 else: try: restore = None if isinstance(f, type): restore = f f = f.__init__ if (not _PY3K): codeObj = f.func_code else: code...
'Define action to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks), fn(loc,toks), fn(toks), or just fn(), where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks =...
def setParseAction(self, *fns, **kwargs):
self.parseAction = list(map(self._normalizeParseActionArgs, list(fns))) self.callDuringTry = (('callDuringTry' in kwargs) and kwargs['callDuringTry']) return self
'Add parse action to expression\'s list of parse actions. See L{I{setParseAction}<setParseAction>}.'
def addParseAction(self, *fns, **kwargs):
self.parseAction += list(map(self._normalizeParseActionArgs, list(fns))) self.callDuringTry = (self.callDuringTry or (('callDuringTry' in kwargs) and kwargs['callDuringTry'])) return self
'Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments fn(s,loc,expr,err) where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The fun...
def setFailAction(self, fn):
self.failAction = fn return self
'Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exception...
def enablePackrat():
if (not ParserElement._packratEnabled): ParserElement._packratEnabled = True ParserElement._parse = ParserElement._parseCache
'Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be successfully parsed, then set parseAll to True (equivalent to ending the grammar with StringEnd()). Note: pa...
def parseString(self, instring, parseAll=False):
ParserElement.resetCache() if (not self.streamlined): self.streamline() for e in self.ignoreExprs: e.streamline() if (not self.keepTabs): instring = instring.expandtabs() try: (loc, tokens) = self._parse(instring, 0) if parseAll: se = StringEnd() ...
'Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional maxMatches argument, to clip scanning after \'n\' matches are found. Note that the start and end locations are reported relative to the string being parsed. See L{I...
def scanString(self, instring, maxMatches=_MAX_INT):
if (not self.streamlined): self.streamline() for e in self.ignoreExprs: e.streamline() if (not self.keepTabs): instring = _ustr(instring).expandtabs() instrlen = len(instring) loc = 0 preparseFn = self.preParse parseFn = self._parse ParserElement.resetCache() ...
'Extension to scanString, to modify matching text with modified tokens that may be returned from a parse action. To use transformString, define a grammar and attach a parse action to it that modifies the returned token list. Invoking transformString() on a target string will then scan for matches, and replace the matc...
def transformString(self, instring):
out = [] lastE = 0 self.keepTabs = True try: for (t, s, e) in self.scanString(instring): out.append(instring[lastE:s]) if t: if isinstance(t, ParseResults): out += t.asList() elif isinstance(t, list): ...
'Another extension to scanString, simplifying the access to the tokens found to match the given parse expression. May be called with optional maxMatches argument, to clip searching after \'n\' matches are found.'
def searchString(self, instring, maxMatches=_MAX_INT):
try: return ParseResults([t for (t, s, e) in self.scanString(instring, maxMatches)]) except ParseBaseException: if ParserElement.verbose_stacktrace: raise else: exc = sys.exc_info()[1] raise exc
'Implementation of + operator - returns And'
def __add__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return And([self, other])
'Implementation of + operator when left operand is not a ParserElement'
def __radd__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other + self)
'Implementation of - operator, returns And with error stop'
def __sub__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return And([self, And._ErrorStop(), ...
'Implementation of - operator when left operand is not a ParserElement'
def __rsub__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other - self)
'Implementation of | operator - returns MatchFirst'
def __or__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return MatchFirst([self, other])
'Implementation of | operator when left operand is not a ParserElement'
def __ror__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other | self)
'Implementation of ^ operator - returns Or'
def __xor__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return Or([self, other])
'Implementation of ^ operator when left operand is not a ParserElement'
def __rxor__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other ^ self)
'Implementation of & operator - returns Each'
def __and__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return Each([self, other])
'Implementation of & operator when left operand is not a ParserElement'
def __rand__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other & self)
'Implementation of ~ operator - returns NotAny'
def __invert__(self):
return NotAny(self)
'Shortcut for setResultsName, with listAllMatches=default:: userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") could be written as:: userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")'
def __call__(self, name):
return self.setResultsName(name)
'Suppresses the output of this ParserElement; useful to keep punctuation from cluttering up returned output.'
def suppress(self):
return Suppress(self)
'Disables the skipping of whitespace before matching the characters in the ParserElement\'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars.'
def leaveWhitespace(self):
self.skipWhitespace = False return self
'Overrides the default whitespace chars'
def setWhitespaceChars(self, chars):
self.skipWhitespace = True self.whiteChars = chars self.copyDefaultWhiteChars = False return self
'Overrides default behavior to expand <TAB>s to spaces before parsing the input string. Must be called before parseString when the input grammar contains elements that match <TAB> characters.'
def parseWithTabs(self):
self.keepTabs = True return self
'Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns.'
def ignore(self, other):
if isinstance(other, Suppress): if (other not in self.ignoreExprs): self.ignoreExprs.append(other.copy()) else: self.ignoreExprs.append(Suppress(other.copy())) return self
'Enable display of debugging messages while doing pattern matching.'
def setDebugActions(self, startAction, successAction, exceptionAction):
self.debugActions = ((startAction or _defaultStartDebugAction), (successAction or _defaultSuccessDebugAction), (exceptionAction or _defaultExceptionDebugAction)) self.debug = True return self
'Enable display of debugging messages while doing pattern matching. Set flag to True to enable, False to disable.'
def setDebug(self, flag=True):
if flag: self.setDebugActions(_defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction) else: self.debug = False return self
'Check defined expressions for valid structure, check for infinite recursive definitions.'
def validate(self, validateTrace=[]):
self.checkRecursion([])
'Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing.'
def parseFile(self, file_or_filename, parseAll=False):
try: file_contents = file_or_filename.read() except AttributeError: f = open(file_or_filename, 'rb') file_contents = f.read() f.close() try: return self.parseString(file_contents, parseAll) except ParseBaseException: exc = sys.exc_info()[1] raise e...
'Overrides the default Keyword chars'
def setDefaultKeywordChars(chars):
Keyword.DEFAULT_KEYWORD_CHARS = chars
'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.'
def __init__(self, pattern, flags=0):
super(Regex, self).__init__() if isinstance(pattern, basestring): if (len(pattern) == 0): warnings.warn('null string passed to Regex; use Empty() instead', SyntaxWarning, stacklevel=2) self.pattern = pattern self.flags = flags try: sel...
'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) - escQuote - special quote sequence to escape an embedded quote string (such as SQL\'s "" to escape an embedded ") (defau...
def __init__(self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):
super(QuotedString, self).__init__() quoteChar = quoteChar.strip() if (len(quoteChar) == 0): warnings.warn('quoteChar cannot be the empty string', SyntaxWarning, stacklevel=2) raise SyntaxError() if (endQuoteChar is None): endQuoteChar = quoteChar else: ...
'Extends leaveWhitespace defined in base class, and also invokes leaveWhitespace on all contained expressions.'
def leaveWhitespace(self):
self.skipWhitespace = False self.exprs = [e.copy() for e in self.exprs] for e in self.exprs: e.leaveWhitespace() return self
''
def __init__(self, filepath, source):
self.filepath = filepath self.source = source self.requiredBy = []
'Extracts the dependencies specified in the source code and returns a list of them.'
def _getRequirements(self):
return re.findall(RE_REQUIRE, self.source)
'Parses the content of the named file and stores the values.'
def __init__(self, filename):
lines = [re.sub('#.*?$', '', line).strip() for line in open(filename) if (line.strip() and (not line.strip().startswith('#')))] self.forceFirst = lines[(lines.index('[first]') + 1):lines.index('[last]')] self.forceLast = lines[(lines.index('[last]') + 1):lines.index('[include]')] self.include = lines[(l...
''
def __init__(self, filepath, source):
self.filepath = filepath self.source = source self.requiredBy = []
'Extracts the dependencies specified in the source code and returns a list of them.'
def _getRequirements(self):
return re.findall(RE_REQUIRE, self.source)
'Parses the content of the named file and stores the values.'
def __init__(self, filename):
lines = [line.strip() for line in open(filename) if line.strip()] self.forceFirst = lines[(lines.index('[first]') + 1):lines.index('[last]')] self.forceLast = lines[(lines.index('[last]') + 1):lines.index('[include]')] self.include = lines[(lines.index('[include]') + 1):lines.index('[exclude]')] sel...
'return the next character from stdin. Watch out for lookahead. If the character is a control character, translate it to a space or linefeed.'
def _get(self):
c = self.theLookahead self.theLookahead = None if (c == None): c = self.instream.read(1) if ((c >= ' ') or (c == '\n')): return c if (c == ''): return '\x00' if (c == '\r'): return '\n' return ' '
'get the next character, excluding comments. peek() is used to see if a \'/\' is followed by a \'/\' or \'*\'.'
def _next(self):
c = self._get() if (c == '/'): p = self._peek() if (p == '/'): c = self._get() while (c > '\n'): c = self._get() return c if (p == '*'): c = self._get() while 1: c = self._get() if...
'do something! What you do is determined by the argument: 1 Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B. (Delete A). 3 Get the next B. (Delete B). action treats a string as a single character. Wow! action recognizes a regular expression if it is preceded by ( or , or =.'
def _action(self, action):
if (action <= 1): self._outA() if (action <= 2): self.theA = self.theB if ((self.theA == "'") or (self.theA == '"')): while 1: self._outA() self.theA = self._get() if (self.theA == self.theB): break ...
'Copy the input to the output, deleting the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed.'
def _jsmin(self):
self.theA = '\n' self._action(3) while (self.theA != '\x00'): if (self.theA == ' '): if isAlphanum(self.theB): self._action(1) else: self._action(2) elif (self.theA == '\n'): if (self.theB in ['{', '[', '(', '+', '-']): ...
'Replaces assorted punctuation with space.'
def cleanup(self, line):
return line.translate(self.trans_tbl)
'"Adds nodes and edges extracted from one table\'s schema Adds the table name, and the names of other tables found in constraints, as nodes to the supplied graph. Adds constraints as edges, pointing from primary to dependent table. @param table_id: table identifier, as needed by subclass method get_table_info(table_id)...
def add_table_to_graph(self, table_id):
(table_name, constraint_iter) = self.get_table_info(table_id) self.graph.add_node(table_name) for primary_name in constraint_iter(): if (table_name != primary_name): self.graph.add_edge(primary_name, table_name)
'Sorts tables in constraint order, least constrained tables first Constructs a constraint graph for the tables in the supplied database or databases directory, sorts it in topological order with the least constained tables first, and returns the table names in that order in a list.'
def order_tables(self):
self.add_all_tables_to_graph() ordered_tables = None try: ordered_tables = nx.topological_sort(self.graph) except: ordered_tables = None if (not ordered_tables): cycles = nx.cycle_basis(nx.Graph(self.graph)) errmsg = (('Tables and their constraints do n...
'Extracts table name and constraints from given .table file. @param file_str: the name of a .table file. @return: (table_name, constraint_iter) where constraint_iter yields the names of tables on which this table depends.'
def get_table_info(self, file_str):
try: table_file = open(os.path.join(self.dbdir_str, file_str), 'r') except: raise ValueError, ("Couldn't read file %s" % file_str) table_name = file_str.split('.', 1)[0].split('_', 1)[1] def constraint_iter(): ' Find constraint lines in the file, yie...
'Add tables and constraints from databases directory to graph.'
def add_all_tables_to_graph(self):
for file_str in os.listdir(self.dbdir_str): if file_str.endswith('.table'): self.add_table_to_graph(file_str)
'Connect to datbase, init graph. If a database connection is supplied in db, use that, else connect using the supplied or defaulted user, password, and database name.'
def __init__(self, db=None, user='sahana', password='password', dbname='sahana'):
import MySQLdb OrderTables.__init__(self) if db: self.db = db else: self.db = MySQLdb.connection(host='localhost', user=user, passwd=password, db=dbname)
'Extracts constraints for table from schema. @param table_name: name of the table to process. @return: (table_name, constraint_iter) where constraint_iter yields the names of tables on which this table depends.'
def get_table_info(self, table_name):
self.db.query(('SHOW CREATE TABLE %s;' % table_name)) result = self.db.store_result() table_schema = result.fetch_row(1)[0][1] def constraint_iter(): ' Find constraints in the schema, yield the primary table name.\n\n ...
'Add tables and constraints from MySQL database to graph.'
def add_all_tables_to_graph(self):
self.db.query('SHOW TABLES;') result = self.db.store_result() for row in result.fetch_row(1000): table_name = row[0] self.add_table_to_graph(table_name)
'Get the next line from the input buffer.'
def readline(self):
self.line_number += 1 if (self.line_number > len(self.lines)): return '' return self.lines[(self.line_number - 1)]
'Check and return the next physical line. This method can be used to feed tokenize.generate_tokens.'
def readline_check_physical(self):
line = self.readline() if line: self.check_physical(line) return line
'Run a check plugin.'
def run_check(self, check, argument_names):
arguments = [] for name in argument_names: arguments.append(getattr(self, name)) return check(*arguments)
'Run all physical checks on a raw input line.'
def check_physical(self, line):
self.physical_line = line if ((self.indent_char is None) and len(line) and (line[0] in ' DCTB ')): self.indent_char = line[0] for (name, check, argument_names) in self.physical_checks: result = self.run_check(check, argument_names) if (result is not None): (offset, te...
'Build a logical line from tokens.'
def build_tokens_line(self):
self.mapping = [] logical = [] length = 0 previous = None for token in self.tokens: (token_type, text) = token[0:2] if (token_type in (tokenize.COMMENT, tokenize.NL, tokenize.INDENT, tokenize.DEDENT, tokenize.NEWLINE)): continue if (token_type == tokenize.STRING):...
'Build a line from tokens and run all logical checks on it.'
def check_logical(self):
options.counters['logical lines'] = (options.counters.get('logical lines', 0) + 1) self.build_tokens_line() first_line = self.lines[(self.mapping[0][1][2][0] - 1)] indent = first_line[:self.mapping[0][1][2][1]] self.previous_indent_level = self.indent_level self.indent_level = expand_inden...
'Run all checks on the input file.'
def check_all(self):
self.file_errors = 0 self.line_number = 0 self.indent_char = None self.indent_level = 0 self.previous_logical = '' self.blank_lines = 0 self.tokens = [] parens = 0 for token in tokenize.generate_tokens(self.readline_check_physical): self.tokens.append(token) (token_ty...
'Report an error, according to options.'
def report_error(self, line_number, offset, text, check):
if ((options.quiet == 1) and (not self.file_errors)): message(self.filename) self.file_errors += 1 code = text[:4] options.counters[code] = (options.counters.get(code, 0) + 1) options.messages[code] = text[5:] if options.quiet: return if options.testsuite: base = os.p...
'If ``mode`` isn\'t provided, the most compact QR data type possible is chosen.'
def __init__(self, data, mode=None, check_data=True):
if check_data: data = to_bytestring(data) if (mode is None): self.mode = optimal_mode(data) else: self.mode = mode if (mode not in (MODE_NUMBER, MODE_ALPHA_NUM, MODE_8BIT_BYTE)): raise TypeError(('Invalid mode (%s)' % mode)) if (check_data and (mode ...
'Reset the internal data.'
def clear(self):
self.modules = None self.modules_count = 0 self.data_cache = None self.data_list = []
'Add data to this QR Code. :param optimize: Data will be split into multiple chunks to optimize the QR size by finding to more compressed modes of at least this length. Set to ``0`` to avoid optimizing at all.'
def add_data(self, data, optimize=20):
if isinstance(data, util.QRData): self.data_list.append(data) elif optimize: self.data_list.extend(util.optimal_data_chunks(data)) else: self.data_list.append(util.QRData(data)) self.data_cache = None