From 556eecc11809907bf14f68e4414bb43172939a08 Mon Sep 17 00:00:00 2001 From: Salvo 'LtWorf' Tomaselli Date: Fri, 27 Dec 2013 00:31:43 +0100 Subject: [PATCH] Changed about and README to not point to galileo anymore --- README | 9 +- driver.py | 280 +++++----- relational/__init__.py | 12 +- relational/maintenance.py | 43 +- relational/optimizations.py | 877 ++++++++++++++++---------------- relational/optimizer.py | 155 +++--- relational/parallel.py | 122 ++--- relational/parser.py | 477 +++++++++-------- relational/query.py | 25 +- relational/relation.py | 629 ++++++++++++----------- relational/rtypes.py | 118 +++-- relational_curses/maingui.py | 176 +++---- relational_gui.py | 96 ++-- relational_gui/about.py | 393 +++++++------- relational_gui/compatibility.py | 37 +- relational_gui/creator.py | 129 ++--- relational_gui/guihandler.py | 271 +++++----- relational_gui/maingui.py | 2 +- relational_gui/rel_edit.py | 2 +- relational_gui/survey.py | 2 +- relational_gui/surveyForm.py | 75 +-- relational_pyside/maingui.py | 2 +- relational_pyside/rel_edit.py | 2 +- relational_pyside/survey.py | 2 +- relational_readline/linegui.py | 299 +++++------ 25 files changed, 2212 insertions(+), 2023 deletions(-) diff --git a/README b/README index bb175e8..b919019 100644 --- a/README +++ b/README @@ -1,7 +1,10 @@ -To launch the application, run +To launch the application, run ./relational_gui.py -If it needs some dependencies, check this page: -http://galileo.dmi.unict.it/wiki/relational/doku.php?id=download#install +Language definition is here: +https://github.com/ltworf/relational/wiki/Grammar-and-language + +If it needs some dependencies: +Qt4, Python 2.7, either PyQT4 or Pyside. diff --git a/driver.py b/driver.py index 90d22bc..d6852a0 100755 --- a/driver.py +++ b/driver.py @@ -3,20 +3,20 @@ # coding=UTF-8 # Relational # Copyright (C) 2010 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli import os @@ -33,14 +33,15 @@ COLOR_CYAN = 0x00ffff print relation -rels={} -examples_path='samples/' -tests_path='test/' +rels = {} +examples_path = 'samples/' +tests_path = 'test/' + def readfile(fname): '''Reads a file as string and returns its content''' - fd=open(fname) - expr=fd.read() + fd = open(fname) + expr = fd.read() fd.close() return expr @@ -50,193 +51,196 @@ def load_relations(): examples_path variable and stores them in the rels dictionary''' print "Loading relations" for i in os.listdir(examples_path): - if i.endswith('.csv'): #It's a relation, loading it - - #Naming the relation - relname=i[:-4] - - print ("Loading relation %s with name %s..." % (i,relname)), - - rels[relname]=relation.relation('%s%s' % (examples_path,i)) + if i.endswith('.csv'): # It's a relation, loading it + + # Naming the relation + relname = i[:-4] + + print ("Loading relation %s with name %s..." % (i, relname)), + + rels[relname] = relation.relation('%s%s' % (examples_path, i)) print 'done' - + + def execute_tests(): - - py_bad=0 - py_good=0 - py_tot=0 - q_bad=0 - q_good=0 - q_tot=0 - ex_bad=0 - ex_good=0 - ex_tot=0 - - + + py_bad = 0 + py_good = 0 + py_tot = 0 + q_bad = 0 + q_good = 0 + q_tot = 0 + ex_bad = 0 + ex_good = 0 + ex_tot = 0 + for i in os.listdir(tests_path): if i.endswith('.query'): - q_tot+=1 + q_tot += 1 if run_test(i[:-6]): - q_good+=1 + q_good += 1 else: - q_bad+=1 + q_bad += 1 elif i.endswith('.python'): - py_tot+=1 + py_tot += 1 if run_py_test(i[:-7]): - py_good+=1 + py_good += 1 else: - py_bad+=1 + py_bad += 1 elif i.endswith('.exec'): - ex_tot+=1 + ex_tot += 1 if run_exec_test(i[:-5]): - ex_good+=1 + ex_good += 1 else: - ex_bad+=1 - print colorize("Resume of the results",COLOR_CYAN) - - print colorize("Query tests",COLOR_MAGENTA) + ex_bad += 1 + print colorize("Resume of the results", COLOR_CYAN) + + print colorize("Query tests", COLOR_MAGENTA) print "Total test count: %d" % q_tot print "Passed tests: %d" % q_good - if q_bad>0: - print colorize("Failed tests count: %d" % q_bad,COLOR_RED) - - print colorize("Python tests",COLOR_MAGENTA) + if q_bad > 0: + print colorize("Failed tests count: %d" % q_bad, COLOR_RED) + + print colorize("Python tests", COLOR_MAGENTA) print "Total test count: %d" % py_tot print "Passed tests: %d" % py_good - if py_bad>0: - print colorize("Failed tests count: %d" % py_bad,COLOR_RED) - - print colorize("Execute Python tests",COLOR_MAGENTA) + if py_bad > 0: + print colorize("Failed tests count: %d" % py_bad, COLOR_RED) + + print colorize("Execute Python tests", COLOR_MAGENTA) print "Total test count: %d" % ex_tot print "Passed tests: %d" % ex_good - if ex_bad>0: - print colorize("Failed tests count: %d" % ex_bad,COLOR_RED) - - - print colorize("Total results",COLOR_CYAN) - if q_bad+py_bad+ex_bad==0: - print colorize("No failed tests",COLOR_GREEN) + if ex_bad > 0: + print colorize("Failed tests count: %d" % ex_bad, COLOR_RED) + + print colorize("Total results", COLOR_CYAN) + if q_bad + py_bad + ex_bad == 0: + print colorize("No failed tests", COLOR_GREEN) return 0 else: - print colorize("There are %d failed tests" % (py_bad+q_bad+ex_bad), COLOR_RED) + print colorize("There are %d failed tests" % (py_bad + q_bad + ex_bad), COLOR_RED) return 1 - - + + def run_exec_test(testname): '''Runs a python test, which executes code directly rather than queries''' - print "Running python test: " + colorize(testname,COLOR_MAGENTA) - - glob=rels.copy() - exp_result={} - + print "Running python test: " + colorize(testname, COLOR_MAGENTA) + + glob = rels.copy() + exp_result = {} + try: - - expr=readfile('%s%s.exec' % (tests_path,testname)) - exec(expr,glob) #Evaluating the expression - - expr=readfile('%s%s.exec' % (tests_path,testname)) - exec(expr,glob) #Evaluating the expression - - - expr=readfile('%s%s.result' % (tests_path,testname)) - exp_result=eval(expr,rels) #Evaluating the expression - - - if isinstance(exp_result,dict): - fields_ok=True - + + expr = readfile('%s%s.exec' % (tests_path, testname)) + exec(expr, glob) # Evaluating the expression + + expr = readfile('%s%s.exec' % (tests_path, testname)) + exec(expr, glob) # Evaluating the expression + + expr = readfile('%s%s.result' % (tests_path, testname)) + exp_result = eval(expr, rels) # Evaluating the expression + + if isinstance(exp_result, dict): + fields_ok = True + for i in exp_result: - fields_ok = fields_ok and glob[i]==exp_result[i] - + fields_ok = fields_ok and glob[i] == exp_result[i] + if fields_ok: - print colorize('Test passed',COLOR_GREEN) + print colorize('Test passed', COLOR_GREEN) return True except: pass - print colorize('ERROR',COLOR_RED) - print colorize('=====================================',COLOR_RED) + print colorize('ERROR', COLOR_RED) + print colorize('=====================================', COLOR_RED) print "Expected %s" % exp_result - #print "Got %s" % result - print colorize('=====================================',COLOR_RED) + # print "Got %s" % result + print colorize('=====================================', COLOR_RED) return False + def run_py_test(testname): '''Runs a python test, which evaluates expressions directly rather than queries''' - print "Running expression python test: " + colorize (testname,COLOR_MAGENTA) - + print "Running expression python test: " + colorize(testname, COLOR_MAGENTA) + try: - - expr=readfile('%s%s.python' % (tests_path,testname)) - result=eval(expr,rels) #Evaluating the expression - - expr=readfile('%s%s.result' % (tests_path,testname)) - exp_result=eval(expr,rels) #Evaluating the expression - - if result==exp_result: - print colorize('Test passed',COLOR_GREEN) + + expr = readfile('%s%s.python' % (tests_path, testname)) + result = eval(expr, rels) # Evaluating the expression + + expr = readfile('%s%s.result' % (tests_path, testname)) + exp_result = eval(expr, rels) # Evaluating the expression + + if result == exp_result: + print colorize('Test passed', COLOR_GREEN) return True except: pass - - print colorize('ERROR',COLOR_RED) - print colorize('=====================================',COLOR_RED) + + print colorize('ERROR', COLOR_RED) + print colorize('=====================================', COLOR_RED) print "Expected %s" % exp_result print "Got %s" % result - print colorize('=====================================',COLOR_RED) + print colorize('=====================================', COLOR_RED) return False + def run_test(testname): '''Runs a specific test executing the file testname.query - and comparing the result with + and comparing the result with testname.result The query will be executed both unoptimized and optimized''' - print "Running test: "+ colorize(testname,COLOR_MAGENTA) - - query=None;expr=None;o_query=None;o_expr=None - result_rel=None - result=None - o_result=None - - + print "Running test: " + colorize(testname, COLOR_MAGENTA) + + query = None + expr = None + o_query = None + o_expr = None + result_rel = None + result = None + o_result = None + try: - result_rel=relation.relation('%s%s.result' % (tests_path,testname)) - - query=unicode(readfile('%s%s.query' % (tests_path,testname)).strip(),'utf8') - o_query=optimizer.optimize_all(query,rels) - - expr=parser.parse(query)#Converting expression to python string - result=eval(expr,rels) #Evaluating the expression - - o_expr=parser.parse(o_query)#Converting expression to python string - o_result=eval(o_expr,rels) #Evaluating the expression - - c_expr=parser.tree(query).toCode() #Converting to python code - c_result=eval(c_expr,rels) - - if (o_result==result_rel) and (result==result_rel) and (c_result==result_rel): - print colorize('Test passed',COLOR_GREEN) + result_rel = relation.relation('%s%s.result' % (tests_path, testname)) + + query = unicode( + readfile('%s%s.query' % (tests_path, testname)).strip(), 'utf8') + o_query = optimizer.optimize_all(query, rels) + + expr = parser.parse(query) # Converting expression to python string + result = eval(expr, rels) # Evaluating the expression + + o_expr = parser.parse( + o_query) # Converting expression to python string + o_result = eval(o_expr, rels) # Evaluating the expression + + c_expr = parser.tree(query).toCode() # Converting to python code + c_result = eval(c_expr, rels) + + if (o_result == result_rel) and (result == result_rel) and (c_result == result_rel): + print colorize('Test passed', COLOR_GREEN) return True except Exception as inst: print inst pass - print colorize('ERROR',COLOR_RED) - print "Query: %s -> %s" % (query,expr) - print "Optimized query: %s -> %s" % (o_query,o_expr) - print colorize('=====================================',COLOR_RED) - print colorize("Expected result",COLOR_GREEN) + print colorize('ERROR', COLOR_RED) + print "Query: %s -> %s" % (query, expr) + print "Optimized query: %s -> %s" % (o_query, o_expr) + print colorize('=====================================', COLOR_RED) + print colorize("Expected result", COLOR_GREEN) print result_rel - print colorize("Result",COLOR_RED) + print colorize("Result", COLOR_RED) print result - print colorize("Optimized result",COLOR_RED) + print colorize("Optimized result", COLOR_RED) print o_result - print colorize("optimized result match %s" % str(result_rel==o_result),COLOR_MAGENTA) - print colorize("result match %s" % str(result==result_rel), COLOR_MAGENTA) - print colorize('=====================================',COLOR_RED) + print colorize("optimized result match %s" % str(result_rel == o_result), COLOR_MAGENTA) + print colorize("result match %s" % str(result == result_rel), COLOR_MAGENTA) + print colorize('=====================================', COLOR_RED) return False - + if __name__ == '__main__': print "-> Starting testsuite for relational" load_relations() diff --git a/relational/__init__.py b/relational/__init__.py index 9a4c4e7..4a086d1 100644 --- a/relational/__init__.py +++ b/relational/__init__.py @@ -1,11 +1,11 @@ __all__ = ( -"relation", -"parser", -"optimizer", -"optimizations", -"rtypes", -"parallel", + "relation", + "parser", + "optimizer", + "optimizations", + "rtypes", + "parallel", ) diff --git a/relational/maintenance.py b/relational/maintenance.py index 2231f8a..591a05e 100644 --- a/relational/maintenance.py +++ b/relational/maintenance.py @@ -23,23 +23,21 @@ import httplib import urllib import relation + def send_survey(data): '''Sends the survey. Data must be a dictionary. returns the http response''' - post='' + post = '' for i in data.keys(): - post+='%s: %s\n' %(i,data[i]) - - #sends the string - params = urllib.urlencode({'survey':post}) - headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} - #connection = httplib.HTTPConnection('galileo.dmi.unict.it') - #connection.request("POST","/~ltworf/survey.php",params,headers) + post += '%s: %s\n' % (i, data[i]) + # sends the string + params = urllib.urlencode({'survey': post}) + headers = {"Content-type": + "application/x-www-form-urlencoded", "Accept": "text/plain"} connection = httplib.HTTPConnection('feedback-ltworf.appspot.com') - connection.request("POST","/feedback/relational",params,headers) - + connection.request("POST", "/feedback/relational", params, headers) return connection.getresponse() @@ -49,46 +47,47 @@ def check_latest_version(): Heavely dependent on server and server configurations not granted to work forever.''' connection = httplib.HTTPConnection('feedback-ltworf.appspot.com') - connection.request("GET","/version/relational") - r=connection.getresponse() + connection.request("GET", "/version/relational") + r = connection.getresponse() - #html - s=r.read() - if len(s)==0: + # html + s = r.read() + if len(s) == 0: return None return s.strip() class interface (object): + '''It is used to provide services to the user interfaces, in order to reduce the amount of duplicated code present in different user interfaces. ''' def __init__(self): - self.rels= {} + self.rels = {} - def load(self,filename,name): + def load(self, filename, name): '''Loads a relation from file, and gives it a name to be used in subsequent queries.''' pass - def unload(self,name): + def unload(self, name): '''Unloads an existing relation.''' pass - def store(self,filename,name): + def store(self, filename, name): '''Stores a relation to file.''' pass - def get_relation(self,name): + def get_relation(self, name): '''Returns the relation corresponding to name.''' pass - def set_relation(self,name,rel): + def set_relation(self, name, rel): '''Sets the relation corresponding to name.''' pass - def execute(self,query,relname='last_'): + def execute(self, query, relname='last_'): '''Executes a query, returns the result and if relname is not None, adds the result to the dictionary, with the name given in relname.''' diff --git a/relational/optimizations.py b/relational/optimizations.py index 18885cb..ed01da7 100644 --- a/relational/optimizations.py +++ b/relational/optimizations.py @@ -1,20 +1,20 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2009 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli # # This module contains functions to perform various optimizations on the expression trees. @@ -34,64 +34,67 @@ import parser from cStringIO import StringIO from tokenize import generate_tokens -sel_op=('//=','**=','and','not','in','//','**','<<','>>','==','!=','>=','<=','+=','-=','*=','/=','%=','or','+','-','*','/','&','|','^','~','<','>','%','=','(',')',',','[',']') +sel_op = ( + '//=', '**=', 'and', 'not', 'in', '//', '**', '<<', '>>', '==', '!=', '>=', '<=', '+=', '-=', + '*=', '/=', '%=', 'or', '+', '-', '*', '/', '&', '|', '^', '~', '<', '>', '%', '=', '(', ')', ',', '[', ']') -PRODUCT=parser.PRODUCT -DIFFERENCE=parser.DIFFERENCE -UNION=parser.UNION -INTERSECTION=parser.INTERSECTION -DIVISION=parser.DIVISION -JOIN=parser.JOIN -JOIN_LEFT=parser.JOIN_LEFT -JOIN_RIGHT=parser.JOIN_RIGHT -JOIN_FULL=parser.JOIN_FULL -PROJECTION=parser.PROJECTION -SELECTION=parser.SELECTION -RENAME=parser.RENAME -ARROW=parser.ARROW +PRODUCT = parser.PRODUCT +DIFFERENCE = parser.DIFFERENCE +UNION = parser.UNION +INTERSECTION = parser.INTERSECTION +DIVISION = parser.DIVISION +JOIN = parser.JOIN +JOIN_LEFT = parser.JOIN_LEFT +JOIN_RIGHT = parser.JOIN_RIGHT +JOIN_FULL = parser.JOIN_FULL +PROJECTION = parser.PROJECTION +SELECTION = parser.SELECTION +RENAME = parser.RENAME +ARROW = parser.ARROW -def replace_node(replace,replacement): +def replace_node(replace, replacement): '''This function replaces "replace" node with the node "with", the father of the node will now point to the with node''' - replace.name=replacement.name - replace.kind=replacement.kind + replace.name = replacement.name + replace.kind = replacement.kind - if replace.kind==parser.UNARY: - replace.child=replacement.child - replace.prop=replacement.prop - elif replace.kind==parser.BINARY: - replace.right=replacement.right - replace.left=replacement.left + if replace.kind == parser.UNARY: + replace.child = replacement.child + replace.prop = replacement.prop + elif replace.kind == parser.BINARY: + replace.right = replacement.right + replace.left = replacement.left -def recoursive_scan(function,node,rels=None): + +def recoursive_scan(function, node, rels=None): '''Does a recoursive optimization on the tree. - + This function will recoursively execute the function given as "function" parameter starting from node to all the tree. if rels is provided it will be passed as argument to the function. Otherwise the function will be called just on the node. - + Result value: function is supposed to return the amount of changes it has performed on the tree. The various result will be added up and this final value will be the returned value.''' - changes=0 - #recoursive scan - if node.kind==parser.UNARY: - if rels!=None: - changes+=function(node.child,rels) + changes = 0 + # recoursive scan + if node.kind == parser.UNARY: + if rels != None: + changes += function(node.child, rels) else: - changes+=function(node.child) - elif node.kind==parser.BINARY: - if rels!=None: - changes+=function(node.right,rels) - changes+=function(node.left,rels) + changes += function(node.child) + elif node.kind == parser.BINARY: + if rels != None: + changes += function(node.right, rels) + changes += function(node.left, rels) else: - changes+=function(node.right) - changes+=function(node.left) + changes += function(node.right) + changes += function(node.left) return changes - + def duplicated_select(n): '''This function locates and deletes things like @@ -100,287 +103,298 @@ def duplicated_select(n): the 2nd one with a single select with both conditions in and ''' - changes=0 - if n.name==SELECTION and n.child.name==SELECTION: - if n.prop != n.child.prop: #Nested but different, joining them + changes = 0 + if n.name == SELECTION and n.child.name == SELECTION: + if n.prop != n.child.prop: # Nested but different, joining them n.prop = n.prop + " and " + n.child.prop - - #This adds parenthesis if they are needed + + # This adds parenthesis if they are needed if n.child.prop.startswith('(') or n.prop.startswith('('): - n.prop= '(%s)' % n.prop - - n.child=n.child.child - changes=1 - changes+=duplicated_select(n) - - return changes+recoursive_scan(duplicated_select,n) + n.prop = '(%s)' % n.prop + + n.child = n.child.child + changes = 1 + changes += duplicated_select(n) + + return changes + recoursive_scan(duplicated_select, n) + def futile_union_intersection_subtraction(n): '''This function locates things like r ᑌ r, and replaces them with r. - R ᑌ R --> R - R ᑎ R --> R + R ᑌ R --> R + R ᑎ R --> R R - R --> σ False (R) - σ k (R) - R --> σ False (R) - R - σ k (R) --> σ not k (R) - σ k (R) ᑌ R --> R + σ k (R) - R --> σ False (R) + R - σ k (R) --> σ not k (R) + σ k (R) ᑌ R --> R σ k (R) ᑎ R --> σ k (R) ''' - - changes=0 - - #Union and intersection of the same thing - if n.name in (UNION,INTERSECTION) and n.left==n.right: - changes=1 - replace_node(n,n.left) - - #selection and union of the same thing - elif (n.name == UNION): - if n.left.name==SELECTION and n.left.child==n.right: - changes=1 - replace_node(n,n.right) - elif n.right.name==SELECTION and n.right.child==n.left: - changes=1 - replace_node(n,n.left) - - #selection and intersection of the same thing - elif n.name == INTERSECTION: - if n.left.name==SELECTION and n.left.child==n.right: - changes=1 - replace_node(n,n.left) - elif n.right.name==SELECTION and n.right.child==n.left: - changes=1 - replace_node(n,n.right) - - #Subtraction and selection of the same thing - elif (n.name == DIFFERENCE and (n.right.name==SELECTION and n.right.child==n.left)): #Subtraction of two equal things, but one has a selection - n.name=n.right.name - n.kind=n.right.kind - n.child=n.right.child - n.prop='(not (%s))' % n.right.prop - n.left=n.right=None - - #Subtraction of the same thing or with selection on the left child - elif (n.name==DIFFERENCE and ((n.left==n.right) or (n.left.name==SELECTION and n.left.child==n.right)) ):#Empty relation - changes=1 - n.kind=parser.UNARY - n.name=SELECTION - n.prop='False' - n.child=n.left.get_left_leaf() - #n.left=n.right=None - return changes+recoursive_scan(futile_union_intersection_subtraction,n) + changes = 0 + + # Union and intersection of the same thing + if n.name in (UNION, INTERSECTION) and n.left == n.right: + changes = 1 + replace_node(n, n.left) + + # selection and union of the same thing + elif (n.name == UNION): + if n.left.name == SELECTION and n.left.child == n.right: + changes = 1 + replace_node(n, n.right) + elif n.right.name == SELECTION and n.right.child == n.left: + changes = 1 + replace_node(n, n.left) + + # selection and intersection of the same thing + elif n.name == INTERSECTION: + if n.left.name == SELECTION and n.left.child == n.right: + changes = 1 + replace_node(n, n.left) + elif n.right.name == SELECTION and n.right.child == n.left: + changes = 1 + replace_node(n, n.right) + + # Subtraction and selection of the same thing + elif (n.name == DIFFERENCE and (n.right.name == SELECTION and n.right.child == n.left)): # Subtraction of two equal things, but one has a selection + n.name = n.right.name + n.kind = n.right.kind + n.child = n.right.child + n.prop = '(not (%s))' % n.right.prop + n.left = n.right = None + + # Subtraction of the same thing or with selection on the left child + elif (n.name == DIFFERENCE and ((n.left == n.right) or (n.left.name == SELECTION and n.left.child == n.right))): # Empty relation + changes = 1 + n.kind = parser.UNARY + n.name = SELECTION + n.prop = 'False' + n.child = n.left.get_left_leaf() + # n.left=n.right=None + + return changes + recoursive_scan(futile_union_intersection_subtraction, n) + def down_to_unions_subtractions_intersections(n): '''This funcion locates things like σ i==2 (c ᑌ d), where the union can be a subtraction and an intersection and replaces them with - σ i==2 (c) ᑌ σ i==2(d). + σ i==2 (c) ᑌ σ i==2(d). ''' - changes=0 - _o=(UNION,DIFFERENCE,INTERSECTION) - if n.name==SELECTION and n.child.name in _o: - - left=parser.node() - left.prop=n.prop - left.name=n.name - left.child=n.child.left - left.kind=parser.UNARY - right=parser.node() - right.prop=n.prop - right.name=n.name - right.child=n.child.right - right.kind=parser.UNARY - - n.name=n.child.name - n.left=left - n.right=right - n.child=None - n.prop=None - n.kind=parser.BINARY - changes+=1 - - return changes+recoursive_scan(down_to_unions_subtractions_intersections,n) + changes = 0 + _o = (UNION, DIFFERENCE, INTERSECTION) + if n.name == SELECTION and n.child.name in _o: + + left = parser.node() + left.prop = n.prop + left.name = n.name + left.child = n.child.left + left.kind = parser.UNARY + right = parser.node() + right.prop = n.prop + right.name = n.name + right.child = n.child.right + right.kind = parser.UNARY + + n.name = n.child.name + n.left = left + n.right = right + n.child = None + n.prop = None + n.kind = parser.BINARY + changes += 1 + + return changes + recoursive_scan(down_to_unions_subtractions_intersections, n) + def duplicated_projection(n): '''This function locates thing like π i ( π j (R)) and replaces them with π i (R)''' - changes=0 - - if n.name==PROJECTION and n.child.name==PROJECTION: - n.child=n.child.child - changes+=1 - - return changes+recoursive_scan(duplicated_projection,n) + changes = 0 + + if n.name == PROJECTION and n.child.name == PROJECTION: + n.child = n.child.child + changes += 1 + + return changes + recoursive_scan(duplicated_projection, n) + def selection_inside_projection(n): '''This function locates things like σ j (π k(R)) and - converts them into π k(σ j (R))''' - changes=0 - - if n.name==SELECTION and n.child.name==PROJECTION: - changes=1 - temp=n.prop - n.prop=n.child.prop - n.child.prop=temp - n.name=PROJECTION - n.child.name=SELECTION - - return changes+recoursive_scan(selection_inside_projection,n) + converts them into π k(σ j (R))''' + changes = 0 + + if n.name == SELECTION and n.child.name == PROJECTION: + changes = 1 + temp = n.prop + n.prop = n.child.prop + n.child.prop = temp + n.name = PROJECTION + n.child.name = SELECTION + + return changes + recoursive_scan(selection_inside_projection, n) + def swap_union_renames(n): - '''This function locates things like + '''This function locates things like ρ a➡b(R) ᑌ ρ a➡b(Q) and replaces them with ρ a➡b(R ᑌ Q). Does the same with subtraction and intersection''' - changes=0 - - if n.name in (DIFFERENCE,UNION,INTERSECTION) and n.left.name==n.right.name and n.left.name==RENAME: - l_vars={} + changes = 0 + + if n.name in (DIFFERENCE, UNION, INTERSECTION) and n.left.name == n.right.name and n.left.name == RENAME: + l_vars = {} for i in n.left.prop.split(','): - q=i.split(ARROW) - l_vars[q[0].strip()]=q[1].strip() - - r_vars={} + q = i.split(ARROW) + l_vars[q[0].strip()] = q[1].strip() + + r_vars = {} for i in n.right.prop.split(','): - q=i.split(ARROW) - r_vars[q[0].strip()]=q[1].strip() - - if r_vars==l_vars: - changes=1 - - #Copying self, but child will be child of renames - q=parser.node() - q.name=n.name - q.kind=parser.BINARY - q.left=n.left.child - q.right=n.right.child - - n.name=RENAME - n.kind=parser.UNARY - n.child=q - n.prop=n.left.prop - n.left=n.right=None - - return changes+recoursive_scan(swap_union_renames,n) + q = i.split(ARROW) + r_vars[q[0].strip()] = q[1].strip() + + if r_vars == l_vars: + changes = 1 + + # Copying self, but child will be child of renames + q = parser.node() + q.name = n.name + q.kind = parser.BINARY + q.left = n.left.child + q.right = n.right.child + + n.name = RENAME + n.kind = parser.UNARY + n.child = q + n.prop = n.left.prop + n.left = n.right = None + + return changes + recoursive_scan(swap_union_renames, n) + def futile_renames(n): '''This function purges renames like id->id''' - changes=0 - - if n.name==RENAME: - #Located two nested renames. - changes=1 + changes = 0 - #Creating a dictionary with the attributes - _vars={} + if n.name == RENAME: + # Located two nested renames. + changes = 1 + + # Creating a dictionary with the attributes + _vars = {} for i in n.prop.split(','): - q=i.split(ARROW) - _vars[q[0].strip()]=q[1].strip() - #Scans dictionary to locate things like "a->b,b->c" and replace them with "a->c" + q = i.split(ARROW) + _vars[q[0].strip()] = q[1].strip() + # Scans dictionary to locate things like "a->b,b->c" and replace them + # with "a->c" for key in list(_vars.keys()): try: - value=_vars[key] + value = _vars[key] except: - value=None - if key==value: - _vars.pop(value) #Removes the unused one - #Reset prop var - n.prop="" - - #Generates new prop var + value = None + if key == value: + _vars.pop(value) # Removes the unused one + # Reset prop var + n.prop = "" + + # Generates new prop var for i in _vars.items(): - n.prop+=u"%s%s%s," % (i[0],ARROW,i[1]) - n.prop=n.prop[:-1] #Removing ending comma - - if len(n.prop)==0: #Nothing to rename, removing the rename op - replace_node(n,n.child) - - return changes+recoursive_scan(futile_renames,n) - + n.prop += u"%s%s%s," % (i[0], ARROW, i[1]) + n.prop = n.prop[:-1] # Removing ending comma + + if len(n.prop) == 0: # Nothing to rename, removing the rename op + replace_node(n, n.child) + + return changes + recoursive_scan(futile_renames, n) + + def subsequent_renames(n): '''This function removes redoundant subsequent renames joining them into one''' - + '''Purges renames like id->id Since it's needed to be performed BEFORE this one so it is not in the list with the other optimizations''' - futile_renames(n) - changes=0 - - if n.name==RENAME and n.child.name==n.name: - #Located two nested renames. - changes=1 - #Joining the attribute into one - n.prop+=','+n.child.prop - n.child=n.child.child + futile_renames(n) + changes = 0 - #Creating a dictionary with the attributes - _vars={} + if n.name == RENAME and n.child.name == n.name: + # Located two nested renames. + changes = 1 + # Joining the attribute into one + n.prop += ',' + n.child.prop + n.child = n.child.child + + # Creating a dictionary with the attributes + _vars = {} for i in n.prop.split(','): - q=i.split(ARROW) - _vars[q[0].strip()]=q[1].strip() - #Scans dictionary to locate things like "a->b,b->c" and replace them with "a->c" + q = i.split(ARROW) + _vars[q[0].strip()] = q[1].strip() + # Scans dictionary to locate things like "a->b,b->c" and replace them + # with "a->c" for key in list(_vars.keys()): try: - value=_vars[key] + value = _vars[key] except: - value=None + value = None if value in _vars.keys(): - if _vars[value]!=key: - #Double rename on attribute - _vars[key] = _vars[_vars[key]] #Sets value - _vars.pop(value) #Removes the unused one - else: #Cycle rename a->b,b->a - _vars.pop(value) #Removes the unused one - _vars.pop(key) #Removes the unused one - - #Reset prop var - n.prop="" - - #Generates new prop var - for i in _vars.items(): - n.prop+=u"%s%s%s," % (i[0],ARROW,i[1]) - n.prop=n.prop[:-1] #Removing ending comma - - if len(n.prop)==0: #Nothing to rename, removing the rename op - replace_node(n,n.child) + if _vars[value] != key: + # Double rename on attribute + _vars[key] = _vars[_vars[key]] # Sets value + _vars.pop(value) # Removes the unused one + else: # Cycle rename a->b,b->a + _vars.pop(value) # Removes the unused one + _vars.pop(key) # Removes the unused one + + # Reset prop var + n.prop = "" + + # Generates new prop var + for i in _vars.items(): + n.prop += u"%s%s%s," % (i[0], ARROW, i[1]) + n.prop = n.prop[:-1] # Removing ending comma + + if len(n.prop) == 0: # Nothing to rename, removing the rename op + replace_node(n, n.child) + + return changes + recoursive_scan(subsequent_renames, n) - return changes+recoursive_scan(subsequent_renames,n) class level_string(str): - level=0 + level = 0 + def tokenize_select(expression): '''This function returns the list of tokens present in a selection. The expression can contain parenthesis. It will use a subclass of str with the attribute level, which will specify the nesting level of the token into parenthesis.''' - g=generate_tokens(StringIO(str(expression)).readline) - l=list(token[1] for token in g) - + g = generate_tokens(StringIO(str(expression)).readline) + l = list(token[1] for token in g) + l.remove('') - - #Changes the 'a','.','method' token group into a single 'a.method' token + + # Changes the 'a','.','method' token group into a single 'a.method' token try: while True: - dot=l.index('.') - l[dot]='%s.%s' % (l[dot-1],l[dot+1]) - l.pop(dot+1) - l.pop(dot-1) + dot = l.index('.') + l[dot] = '%s.%s' % (l[dot - 1], l[dot + 1]) + l.pop(dot + 1) + l.pop(dot - 1) except: pass - - - level=0 + + level = 0 for i in range(len(l)): - l[i]=level_string(l[i]) - l[i].level=level - - if l[i]=='(': - level+=1 - elif l[i]==')': - level-=1 - + l[i] = level_string(l[i]) + l[i].level = level + + if l[i] == '(': + level += 1 + elif l[i] == ')': + level -= 1 + return l + def swap_rename_projection(n): '''This function locates things like π k(ρ j(R)) and replaces them with ρ j(π k(R)). @@ -388,217 +402,222 @@ def swap_rename_projection(n): and more important, will hopefully allow further optimizations. Will also eliminate fields in the rename that are cutted in the projection. ''' - changes=0 - - if n.name==PROJECTION and n.child.name==RENAME: - changes=1 - - #π index,name(ρ id➡index(R)) - _vars={} + changes = 0 + + if n.name == PROJECTION and n.child.name == RENAME: + changes = 1 + + # π index,name(ρ id➡index(R)) + _vars = {} for i in n.child.prop.split(','): - q=i.split(ARROW) - _vars[q[1].strip()]=q[0].strip() - - _pr=n.prop.split(',') + q = i.split(ARROW) + _vars[q[1].strip()] = q[0].strip() + + _pr = n.prop.split(',') for i in range(len(_pr)): try: - _pr[i]=_vars[_pr[i].strip()] + _pr[i] = _vars[_pr[i].strip()] except: pass - - _pr_reborn=n.prop.split(',') + + _pr_reborn = n.prop.split(',') for i in list(_vars.keys()): if i not in _pr_reborn: _vars.pop(i) - n.name=n.child.name - n.prop='' + n.name = n.child.name + n.prop = '' for i in _vars.keys(): - n.prop+=u'%s%s%s,' % (_vars[i],ARROW,i) - n.prop=n.prop[:-1] - - n.child.name=PROJECTION - n.child.prop='' + n.prop += u'%s%s%s,' % (_vars[i], ARROW, i) + n.prop = n.prop[:-1] + + n.child.name = PROJECTION + n.child.prop = '' for i in _pr: - n.child.prop+=i+',' - n.child.prop=n.child.prop[:-1] - - - return changes+recoursive_scan(swap_rename_projection,n) + n.child.prop += i + ',' + n.child.prop = n.child.prop[:-1] + + return changes + recoursive_scan(swap_rename_projection, n) + def swap_rename_select(n): '''This function locates things like σ k(ρ j(R)) and replaces them with ρ j(σ k(R)). Renaming the attributes used in the selection, so the operation is still valid.''' - changes=0 - - if n.name==SELECTION and n.child.name==RENAME: - changes=1 - #Dictionary containing attributes of rename - _vars={} + changes = 0 + + if n.name == SELECTION and n.child.name == RENAME: + changes = 1 + # Dictionary containing attributes of rename + _vars = {} for i in n.child.prop.split(','): - q=i.split(ARROW) - _vars[q[1].strip()]=q[0].strip() - - #tokenizes expression in select - _tokens=tokenize_select(n.prop) - - #Renaming stuff + q = i.split(ARROW) + _vars[q[1].strip()] = q[0].strip() + + # tokenizes expression in select + _tokens = tokenize_select(n.prop) + + # Renaming stuff for i in range(len(_tokens)): - splitted=_tokens[i].split('.',1) + splitted = _tokens[i].split('.', 1) if splitted[0] in _vars: - if len(splitted)==1: - _tokens[i]=_vars[_tokens[i].split('.')[0]] + if len(splitted) == 1: + _tokens[i] = _vars[_tokens[i].split('.')[0]] else: - _tokens[i]=_vars[_tokens[i].split('.')[0]]+'.'+splitted[1] - - #Swapping operators - n.name=RENAME - n.child.name=SELECTION - - n.prop=n.child.prop - n.child.prop='' + _tokens[i] = _vars[ + _tokens[i].split('.')[0]] + '.' + splitted[1] + + # Swapping operators + n.name = RENAME + n.child.name = SELECTION + + n.prop = n.child.prop + n.child.prop = '' for i in _tokens: - n.child.prop+=i+ ' ' - - return changes+recoursive_scan(swap_rename_select,n) + n.child.prop += i + ' ' + + return changes + recoursive_scan(swap_rename_select, n) + def select_union_intersect_subtract(n): '''This function locates things like σ i(a) ᑌ σ q(a) and replaces them with σ (i OR q) (a) Removing a O(n²) operation like the union''' - changes=0 - if n.name in (UNION, INTERSECTION, DIFFERENCE) and n.left.name==SELECTION and n.right.name==SELECTION and n.left.child==n.right.child: - cahnges=1 - - d={UNION:'or', INTERSECTION:'and', DIFFERENCE:'and not'} - op=d[n.name] - - newnode=parser.node() - - if n.left.prop.startswith('(') or n.right.prop.startswith('('): - t_str='(' - if n.left.prop.startswith('('): - t_str+='(%s)' - else: - t_str+='%s' - t_str+=' %s ' - if n.right.prop.startswith('('): - t_str+='(%s)' - else: - t_str+='%s' - t_str+=')' - - newnode.prop= t_str % (n.left.prop,op,n.right.prop) - else: - newnode.prop='%s %s %s' % (n.left.prop,op,n.right.prop) - newnode.name=SELECTION - newnode.child=n.left.child - newnode.kind=parser.UNARY - replace_node(n,newnode) - - return changes+recoursive_scan(select_union_intersect_subtract,n) + changes = 0 + if n.name in (UNION, INTERSECTION, DIFFERENCE) and n.left.name == SELECTION and n.right.name == SELECTION and n.left.child == n.right.child: + cahnges = 1 -def selection_and_product(n,rels): + d = {UNION: 'or', INTERSECTION: 'and', DIFFERENCE: 'and not'} + op = d[n.name] + + newnode = parser.node() + + if n.left.prop.startswith('(') or n.right.prop.startswith('('): + t_str = '(' + if n.left.prop.startswith('('): + t_str += '(%s)' + else: + t_str += '%s' + t_str += ' %s ' + if n.right.prop.startswith('('): + t_str += '(%s)' + else: + t_str += '%s' + t_str += ')' + + newnode.prop = t_str % (n.left.prop, op, n.right.prop) + else: + newnode.prop = '%s %s %s' % (n.left.prop, op, n.right.prop) + newnode.name = SELECTION + newnode.child = n.left.child + newnode.kind = parser.UNARY + replace_node(n, newnode) + + return changes + recoursive_scan(select_union_intersect_subtract, n) + + +def selection_and_product(n, rels): '''This function locates things like σ k (R*Q) and converts them into σ l (σ j (R) * σ i (Q)). Where j contains only attributes belonging to R, i contains attributes belonging to Q and l contains attributes belonging to both''' - changes=0 - - if n.name==SELECTION and n.child.name in (PRODUCT,JOIN,JOIN_LEFT,JOIN_RIGHT,JOIN_FULL): - l_attr=n.child.left.result_format(rels) - r_attr=n.child.right.result_format(rels) - - tokens=tokenize_select(n.prop) - groups=[] - temp=[] - + changes = 0 + + if n.name == SELECTION and n.child.name in (PRODUCT, JOIN, JOIN_LEFT, JOIN_RIGHT, JOIN_FULL): + l_attr = n.child.left.result_format(rels) + r_attr = n.child.right.result_format(rels) + + tokens = tokenize_select(n.prop) + groups = [] + temp = [] + for i in tokens: - if i=='and' and i.level==0: + if i == 'and' and i.level == 0: groups.append(temp) - temp=[] + temp = [] else: temp.append(i) - if len(temp)!=0: + if len(temp) != 0: groups.append(temp) - temp=[] - - left=[] - right=[] - both=[] - + temp = [] + + left = [] + right = [] + both = [] + for i in groups: - l_fields=False #has fields in left? - r_fields=False #has fields in left? - + l_fields = False # has fields in left? + r_fields = False # has fields in left? + for j in set(i).difference(sel_op): - j=j.split('.')[0] - if j in l_attr:#Field in left - l_fields=True - if j in r_attr:#Field in right - r_fields=True - - if l_fields and r_fields:#Fields in both + j = j.split('.')[0] + if j in l_attr: # Field in left + l_fields = True + if j in r_attr: # Field in right + r_fields = True + + if l_fields and r_fields: # Fields in both both.append(i) elif l_fields: left.append(i) elif r_fields: right.append(i) - else:#Unknown.. adding in both + else: # Unknown.. adding in both both.append(i) - - #Preparing left selection - if len(left)>0: - changes=1 - l_node=parser.node() - l_node.name=SELECTION - l_node.kind=parser.UNARY - l_node.child=n.child.left - l_node.prop='' - n.child.left=l_node - while len(left)>0: - c=left.pop(0) - for i in c: - l_node.prop+=i+ ' ' - if len(left)>0: - l_node.prop+=' and ' - if '(' in l_node.prop: - l_node.prop='(%s)' % l_node.prop - - #Preparing right selection - if len(right)>0: - changes=1 - r_node=parser.node() - r_node.name=SELECTION - r_node.prop='' - r_node.kind=parser.UNARY - r_node.child=n.child.right - n.child.right=r_node - while len(right)>0: - c=right.pop(0) - for i in c: - r_node.prop+=i+ ' ' - if len(right)>0: - r_node.prop+=' and ' - if '(' in r_node.prop: - r_node.prop='(%s)' % r_node.prop - #Changing main selection - n.prop='' - if len(both)!=0: - while len(both)>0: - c=both.pop(0) - for i in c: - n.prop+=i+ ' ' - if len(both)>0: - n.prop+=' and ' - if '(' in n.prop: - n.prop='(%s)' % n.prop - else:#No need for general select - replace_node(n,n.child) - - return changes+recoursive_scan(selection_and_product,n,rels) - -general_optimizations=[duplicated_select,down_to_unions_subtractions_intersections,duplicated_projection,selection_inside_projection,subsequent_renames,swap_rename_select,futile_union_intersection_subtraction,swap_union_renames,swap_rename_projection,select_union_intersect_subtract] -specific_optimizations=[selection_and_product] -if __name__=="__main__": + # Preparing left selection + if len(left) > 0: + changes = 1 + l_node = parser.node() + l_node.name = SELECTION + l_node.kind = parser.UNARY + l_node.child = n.child.left + l_node.prop = '' + n.child.left = l_node + while len(left) > 0: + c = left.pop(0) + for i in c: + l_node.prop += i + ' ' + if len(left) > 0: + l_node.prop += ' and ' + if '(' in l_node.prop: + l_node.prop = '(%s)' % l_node.prop + + # Preparing right selection + if len(right) > 0: + changes = 1 + r_node = parser.node() + r_node.name = SELECTION + r_node.prop = '' + r_node.kind = parser.UNARY + r_node.child = n.child.right + n.child.right = r_node + while len(right) > 0: + c = right.pop(0) + for i in c: + r_node.prop += i + ' ' + if len(right) > 0: + r_node.prop += ' and ' + if '(' in r_node.prop: + r_node.prop = '(%s)' % r_node.prop + # Changing main selection + n.prop = '' + if len(both) != 0: + while len(both) > 0: + c = both.pop(0) + for i in c: + n.prop += i + ' ' + if len(both) > 0: + n.prop += ' and ' + if '(' in n.prop: + n.prop = '(%s)' % n.prop + else: # No need for general select + replace_node(n, n.child) + + return changes + recoursive_scan(selection_and_product, n, rels) + +general_optimizations = [ + duplicated_select, down_to_unions_subtractions_intersections, duplicated_projection, selection_inside_projection, + subsequent_renames, swap_rename_select, futile_union_intersection_subtraction, swap_union_renames, swap_rename_projection, select_union_intersect_subtract] +specific_optimizations = [selection_and_product] + +if __name__ == "__main__": print tokenize_select("skill == 'C' and id % 2 == 0") diff --git a/relational/optimizer.py b/relational/optimizer.py index a7dde2d..97c3e57 100644 --- a/relational/optimizer.py +++ b/relational/optimizer.py @@ -2,20 +2,20 @@ # coding=UTF-8 # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli # # This module optimizes relational expressions into ones that require less time to be executed. @@ -29,23 +29,24 @@ import optimizations import parser -#Stuff that was here before, keeping it for compatibility -RELATION=parser.RELATION -UNARY=parser.UNARY -BINARY=parser.BINARY +# Stuff that was here before, keeping it for compatibility +RELATION = parser.RELATION +UNARY = parser.UNARY +BINARY = parser.BINARY -b_operators=parser.b_operators -u_operators=parser.u_operators -op_functions=parser.op_functions -node=parser.node -tokenize=parser.tokenize -tree=parser.tree -#End of the stuff +b_operators = parser.b_operators +u_operators = parser.u_operators +op_functions = parser.op_functions +node = parser.node +tokenize = parser.tokenize +tree = parser.tree +# End of the stuff -def optimize_all(expression,rels,specific=True,general=True,debug=None): + +def optimize_all(expression, rels, specific=True, general=True, debug=None): '''This function performs all the available optimizations. - + expression : see documentation of this module rels: dic with relation name as key, and relation istance as value specific: True if it has to perform specific optimizations @@ -53,65 +54,70 @@ def optimize_all(expression,rels,specific=True,general=True,debug=None): debug: if a list is provided here, after the end of the function, it will contain the query repeated many times to show the performed steps. - + Return value: this will return an optimized version of the expression''' - if isinstance(expression,unicode): - n=tree(expression) #Gets the tree - elif isinstance(expression,node): - n=expression + if isinstance(expression, unicode): + n = tree(expression) # Gets the tree + elif isinstance(expression, node): + n = expression else: raise (TypeError("expression must be a unicode string or a node")) - - if isinstance(debug,list): - dbg=True + + if isinstance(debug, list): + dbg = True else: - dbg=False - - total=1 - while total!=0: - total=0 + dbg = False + + total = 1 + while total != 0: + total = 0 if specific: for i in optimizations.specific_optimizations: - res=i(n,rels) #Performs the optimization - if res!=0 and dbg: debug.append(n.__str__()) - total+=res + res = i(n, rels) # Performs the optimization + if res != 0 and dbg: + debug.append(n.__str__()) + total += res if general: for i in optimizations.general_optimizations: - res=i(n) #Performs the optimization - if res!=0 and dbg: debug.append(n.__str__()) - total+=res + res = i(n) # Performs the optimization + if res != 0 and dbg: + debug.append(n.__str__()) + total += res return n.__str__() -def specific_optimize(expression,rels): + +def specific_optimize(expression, rels): '''This function performs specific optimizations. Means that it will need to know the fields used by the relations. - + expression : see documentation of this module rels: dic with relation name as key, and relation istance as value - + Return value: this will return an optimized version of the expression''' - return optimize_all(expression,rels,specific=True,general=False) - + return optimize_all(expression, rels, specific=True, general=False) + + def general_optimize(expression): '''This function performs general optimizations. Means that it will not need to know the fields used by the relations - - expression : see documentation of this module - - Return value: this will return an optimized version of the expression''' - return optimize_all(expression,None,specific=False,general=True) -if __name__=="__main__": - #n=node(u"((a ᑌ b) - c ᑌ d) - b") - #n=node(u"π a,b (d-a*b)") - - #print n.__str__() - #a= tokenize("(a - (a ᑌ b) * π a,b (a-b)) - ρ 123 (a)") - #a= tokenize(u"π a,b (a*b)") - #a=tokenize("(a-b*c)*(b-c)") - - import relation,optimizations - + expression : see documentation of this module + + Return value: this will return an optimized version of the expression''' + return optimize_all(expression, None, specific=False, general=True) + +if __name__ == "__main__": + # n=node(u"((a ᑌ b) - c ᑌ d) - b") + # n=node(u"π a,b (d-a*b)") + + # print n.__str__() + # a= tokenize("(a - (a ᑌ b) * π a,b (a-b)) - ρ 123 (a)") + # a= tokenize(u"π a,b (a*b)") + # a=tokenize("(a-b*c)*(b-c)") + + import relation + import optimizations + '''rels={} rels["P1"]= relation.relation("/home/salvo/dev/relational/trunk/samples/people.csv") rels["P2"]= relation.relation("/home/salvo/dev/relational/trunk/samples/people.csv") @@ -120,27 +126,28 @@ if __name__=="__main__": rels["D1"]= relation.relation("/home/salvo/dev/relational/trunk/samples/dates.csv") rels["S1"]= relation.relation("/home/salvo/dev/relational/trunk/samples/skillo.csv") print rels''' - n=tree(u"π indice,qq,name (ρ age➡qq,id➡indice (P1-P2))") - #n=tree("σ id==3 and indice==2 and name==5 or name<2(P1 * S1)") + n = tree(u"π indice,qq,name (ρ age➡qq,id➡indice (P1-P2))") + # n=tree("σ id==3 and indice==2 and name==5 or name<2(P1 * S1)") print n print n.toPython() - - #print optimizations.selection_and_product(n,rels) - + + # print optimizations.selection_and_product(n,rels) + ''' σ skill=='C' (π id,name,chief,age (σ chief==i and age>a (ρ id➡i,age➡a(π id,age(people))*people)) ᐅᐊ skills) - (π id,name,chief,age (σ chief == i and age > a ((ρ age➡a,id➡i (π id,age (people)))*people)))ᐅᐊ(σ skill == 'C' (skills)) + (π id,name,chief,age (σ chief == i and age > a ((ρ age➡a,id➡i (π id,age (people)))*people)))ᐅᐊ(σ skill == 'C' (skills)) ''' - - #print specific_optimize("σ name==skill and age>21 and id==indice and skill=='C'(P1ᐅᐊS1)",rels) - - #print n - #print n.result_format(rels) + + # print specific_optimize("σ name==skill and age>21 and id==indice and + # skill=='C'(P1ᐅᐊS1)",rels) + + # print n + # print n.result_format(rels) '''σ k (r) ᑌ r with r σ k (r) ᑎ r with σ k (r)''' - - #a=general_optimize('π indice,qq,name (ρ age➡qq,id➡indice (P1-P2))') - #a=general_optimize("σ i==2 (σ b>5 (d))") - #print a - #print node(a) - #print tokenize("(a)") \ No newline at end of file + + # a=general_optimize('π indice,qq,name (ρ age➡qq,id➡indice (P1-P2))') + # a=general_optimize("σ i==2 (σ b>5 (d))") + # print a + # print node(a) + # print tokenize("(a)") diff --git a/relational/parallel.py b/relational/parallel.py index 7ca43b5..e9e83b1 100644 --- a/relational/parallel.py +++ b/relational/parallel.py @@ -1,111 +1,117 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2009 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli -# +# # This module offers capability of executing relational queries in parallel. import optimizer import multiprocessing import parser -def execute(tree,rels): + +def execute(tree, rels): '''This funcion executes a query in parallel. Tree is the tree describing the query (usually obtained with parser.tree(querystring) rels is a dictionary containing the relations associated with the names''' q = multiprocessing.Queue() - p = multiprocessing.Process(target=__p_exec__, args=(tree,rels,q,)) + p = multiprocessing.Process(target=__p_exec__, args=(tree, rels, q,)) p.start() - result= q.get() + result = q.get() p.join() return result -def __p_exec__(tree,rels,q): + +def __p_exec__(tree, rels, q): '''q is the queue used for communication''' - if tree.kind==parser.RELATION: + if tree.kind == parser.RELATION: q.put(rels[tree.name]) - elif tree.kind==parser.UNARY: - - #Obtain the relation + elif tree.kind == parser.UNARY: + + # Obtain the relation temp_q = multiprocessing.Queue() - __p_exec__(tree.child,rels,temp_q) - rel=temp_q.get() - - #Execute the query - result=__p_exec_unary__(tree,rel) + __p_exec__(tree.child, rels, temp_q) + rel = temp_q.get() + + # Execute the query + result = __p_exec_unary__(tree, rel) q.put(result) - elif tree.kind==parser.BINARY: + elif tree.kind == parser.BINARY: left_q = multiprocessing.Queue() - left_p = multiprocessing.Process(target=__p_exec__, args=(tree.left,rels,left_q,)) + left_p = multiprocessing.Process( + target=__p_exec__, args=(tree.left, rels, left_q,)) right_q = multiprocessing.Queue() - right_p = multiprocessing.Process(target=__p_exec__, args=(tree.right,rels,right_q,)) - - - #Spawn the children + right_p = multiprocessing.Process( + target=__p_exec__, args=(tree.right, rels, right_q,)) + + # Spawn the children left_p.start() right_p.start() - - #Get the left and right relations - left= left_q.get() - right= right_q.get() - - #Wait for the children to terminate + + # Get the left and right relations + left = left_q.get() + right = right_q.get() + + # Wait for the children to terminate left_p.join() right_p.join() - - result = __p_exec_binary__(tree,left,right) + + result = __p_exec_binary__(tree, left, right) q.put(result) return -def __p_exec_binary__(tree,left,right): - if tree.name=='*': + + +def __p_exec_binary__(tree, left, right): + if tree.name == '*': return left.product(right) - elif tree.name=='-': + elif tree.name == '-': return left.difference(right) - elif tree.name=='ᑌ': + elif tree.name == 'ᑌ': return left.union(right) - elif tree.name=='ᑎ': + elif tree.name == 'ᑎ': return left.intersection(right) - elif tree.name=='÷': + elif tree.name == '÷': return left.division(right) - elif tree.name=='ᐅᐊ': + elif tree.name == 'ᐅᐊ': return left.join(right) - elif tree.name=='ᐅLEFTᐊ': + elif tree.name == 'ᐅLEFTᐊ': return left.outer_left(right) - elif tree.name=='ᐅRIGHTᐊ': + elif tree.name == 'ᐅRIGHTᐊ': return left.outer_right(right) - else: # tree.name=='ᐅFULLᐊ': + else: # tree.name=='ᐅFULLᐊ': return left.outer(right) - -def __p_exec_unary__(tree,rel): - if tree.name=='π':#Projection - tree.prop=tree.prop.replace(' ','').split(',') - result= rel.projection(tree.prop) - elif tree.name=="ρ": #Rename - #tree.prop='{\"%s\"}' % tree.prop.replace(',','\",\"').replace('➡','\":\"').replace(' ','') - d={} - tree.prop=tree.prop.replace(' ','') + + +def __p_exec_unary__(tree, rel): + if tree.name == 'π': # Projection + tree.prop = tree.prop.replace(' ', '').split(',') + result = rel.projection(tree.prop) + elif tree.name == "ρ": # Rename + # tree.prop='{\"%s\"}' % + # tree.prop.replace(',','\",\"').replace('➡','\":\"').replace(' ','') + d = {} + tree.prop = tree.prop.replace(' ', '') for i in tree.prop.split(','): - rename_=i.split('➡') - d[rename_[0]]=rename_[1] - - result= rel.rename(d) - else: #Selection - result= rel.selection(tree.prop) + rename_ = i.split('➡') + d[rename_[0]] = rename_[1] + + result = rel.rename(d) + else: # Selection + result = rel.selection(tree.prop) return result - \ No newline at end of file diff --git a/relational/parser.py b/relational/parser.py index 306650c..a0b932d 100644 --- a/relational/parser.py +++ b/relational/parser.py @@ -2,20 +2,20 @@ # coding=UTF-8 # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli # # @@ -25,15 +25,15 @@ # of the expression. # # The input must be provided in UTF-8 -# +# # # Language definition: # Query := Ident # Query := Query BinaryOp Query -# Query := (Query) -# Query := σ PYExprWithoutParenthesis (Query) | σ (PYExpr) (Query) -# Query := π FieldList (Query) -# Query := ρ RenameList (Query) +# Query := (Query) +# Query := σ PYExprWithoutParenthesis (Query) | σ (PYExpr) (Query) +# Query := π FieldList (Query) +# Query := ρ RenameList (Query) # FieldList := Ident | Ident , FieldList # RenameList := Ident ➡ Ident | Ident ➡ Ident , RenameList # BinaryOp := * | - | ᑌ | ᑎ | ÷ | ᐅᐊ | ᐅLEFTᐊ | ᐅRIGHTᐊ | ᐅFULLᐊ @@ -43,246 +43,264 @@ import re import rtypes -RELATION=0 -UNARY=1 -BINARY=2 +RELATION = 0 +UNARY = 1 +BINARY = 2 -PRODUCT=u'*' -DIFFERENCE=u'-' -UNION=u'ᑌ' -INTERSECTION=u'ᑎ' -DIVISION=u'÷' -JOIN=u'ᐅᐊ' -JOIN_LEFT=u'ᐅLEFTᐊ' -JOIN_RIGHT=u'ᐅRIGHTᐊ' -JOIN_FULL=u'ᐅFULLᐊ' -PROJECTION=u'π' -SELECTION=u'σ' -RENAME=u'ρ' -ARROW=u'➡' +PRODUCT = u'*' +DIFFERENCE = u'-' +UNION = u'ᑌ' +INTERSECTION = u'ᑎ' +DIVISION = u'÷' +JOIN = u'ᐅᐊ' +JOIN_LEFT = u'ᐅLEFTᐊ' +JOIN_RIGHT = u'ᐅRIGHTᐊ' +JOIN_FULL = u'ᐅFULLᐊ' +PROJECTION = u'π' +SELECTION = u'σ' +RENAME = u'ρ' +ARROW = u'➡' -b_operators=(PRODUCT,DIFFERENCE,UNION,INTERSECTION,DIVISION,JOIN,JOIN_LEFT,JOIN_RIGHT,JOIN_FULL) # List of binary operators -u_operators=(PROJECTION,SELECTION,RENAME) # List of unary operators +b_operators = (PRODUCT, DIFFERENCE, UNION, INTERSECTION, DIVISION, + JOIN, JOIN_LEFT, JOIN_RIGHT, JOIN_FULL) # List of binary operators +u_operators = (PROJECTION, SELECTION, RENAME) # List of unary operators # Associates operator with python method -op_functions={PRODUCT:'product',DIFFERENCE:'difference',UNION:'union',INTERSECTION:'intersection',DIVISION:'division',JOIN:'join',JOIN_LEFT:'outer_left',JOIN_RIGHT:'outer_right',JOIN_FULL:'outer',PROJECTION:'projection',SELECTION:'selection',RENAME:'rename'} +op_functions = { + PRODUCT: 'product', DIFFERENCE: 'difference', UNION: 'union', INTERSECTION: 'intersection', DIVISION: 'division', JOIN: 'join', + JOIN_LEFT: 'outer_left', JOIN_RIGHT: 'outer_right', JOIN_FULL: 'outer', PROJECTION: 'projection', SELECTION: 'selection', RENAME: 'rename'} + class TokenizerException (Exception): pass + + class ParserException (Exception): pass + class node (object): + '''This class is a node of a relational expression. Leaves are relations and internal nodes are operations. - + The kind property says if the node is a binary operator, unary operator or relation. Since relations are leaves, a relation node will have no attribute for children. - + If the node is a binary operator, it will have left and right properties. - + If the node is a unary operator, it will have a child, pointing to the child node and a prop containing the string with the props of the operation. - + This class is used to convert an expression into python code.''' - kind=None - __hash__=None - - def __init__(self,expression=None): + kind = None + __hash__ = None + + def __init__(self, expression=None): '''Generates the tree from the tokenized expression If no expression is specified then it will create an empty node''' - if expression==None or len(expression)==0: + if expression == None or len(expression) == 0: return - - #If the list contains only a list, it will consider the lower level list. - #This will allow things like ((((((a))))) to work - while len(expression)==1 and isinstance(expression[0],list): - expression=expression[0] - - #The list contains only 1 string. Means it is the name of a relation - if len(expression)==1 and isinstance(expression[0],unicode): - self.kind=RELATION - self.name=expression[0] + + # If the list contains only a list, it will consider the lower level list. + # This will allow things like ((((((a))))) to work + while len(expression) == 1 and isinstance(expression[0], list): + expression = expression[0] + + # The list contains only 1 string. Means it is the name of a relation + if len(expression) == 1 and isinstance(expression[0], unicode): + self.kind = RELATION + self.name = expression[0] if not rtypes.is_valid_relation_name(self.name): - raise ParserException(u"'%s' is not a valid relation name" % self.name) + raise ParserException( + u"'%s' is not a valid relation name" % self.name) return - + '''Expression from right to left, searching for binary operators this means that binary operators have lesser priority than unary operators. It finds the operator with lesser priority, uses it as root of this (sub)tree using everything on its left as left parameter (so building - a left subtree with the part of the list located on left) and doing + a left subtree with the part of the list located on left) and doing the same on right. Since it searches for strings, and expressions into parenthesis are within sub-lists, they won't be found here, ensuring that they will have highest priority.''' - for i in xrange(len(expression)-1,-1,-1): - if expression[i] in b_operators: #Binary operator - self.kind=BINARY - self.name=expression[i] - - if len(expression[:i])==0: - raise ParserException(u"Expected left operand for '%s'" % self.name) - - if len(expression[i+1:])==0: - raise ParserException(u"Expected right operand for '%s'" % self.name) - - self.left=node(expression[:i]) - self.right=node(expression[i+1:]) + for i in xrange(len(expression) - 1, -1, -1): + if expression[i] in b_operators: # Binary operator + self.kind = BINARY + self.name = expression[i] + + if len(expression[:i]) == 0: + raise ParserException( + u"Expected left operand for '%s'" % self.name) + + if len(expression[i + 1:]) == 0: + raise ParserException( + u"Expected right operand for '%s'" % self.name) + + self.left = node(expression[:i]) + self.right = node(expression[i + 1:]) return '''Searches for unary operators, parsing from right to left''' - for i in xrange(len(expression)-1,-1,-1): - if expression[i] in u_operators: #Unary operator - self.kind=UNARY - self.name=expression[i] - - if len(expression)<=i+2: - raise ParserException(u"Expected more tokens in '%s'"%self.name) - - self.prop=expression[1+i].strip() - self.child=node(expression[2+i]) - + for i in xrange(len(expression) - 1, -1, -1): + if expression[i] in u_operators: # Unary operator + self.kind = UNARY + self.name = expression[i] + + if len(expression) <= i + 2: + raise ParserException( + u"Expected more tokens in '%s'" % self.name) + + self.prop = expression[1 + i].strip() + self.child = node(expression[2 + i]) + return raise ParserException(u"Unable to parse tokens") pass + def toCode(self): '''This method converts the tree into a python code object''' code = self.toPython() - return compile(code,'','eval') - + return compile(code, '', 'eval') + def toPython(self): - '''This method converts the expression into a python code string, which + '''This method converts the expression into a python code string, which will require the relation module to be executed.''' if self.name in b_operators: - return '%s.%s(%s)' % (self.left.toPython(),op_functions[self.name],self.right.toPython()) + return '%s.%s(%s)' % (self.left.toPython(), op_functions[self.name], self.right.toPython()) elif self.name in u_operators: - prop =self.prop - - #Converting parameters - if self.name==PROJECTION: - prop='\"%s\"' % prop.replace(' ','').replace(',','\",\"') - elif self.name==RENAME: - prop='{\"%s\"}' % prop.replace(',','\",\"').replace(ARROW,'\":\"').replace(' ','') - else: #Selection - prop='\"%s\"' % prop - - return '%s.%s(%s)' % (self.child.toPython(),op_functions[self.name],prop) + prop = self.prop + + # Converting parameters + if self.name == PROJECTION: + prop = '\"%s\"' % prop.replace(' ', '').replace(',', '\",\"') + elif self.name == RENAME: + prop = '{\"%s\"}' % prop.replace( + ',', '\",\"').replace(ARROW, '\":\"').replace(' ', '') + else: # Selection + prop = '\"%s\"' % prop + + return '%s.%s(%s)' % (self.child.toPython(), op_functions[self.name], prop) else: return self.name pass - def printtree(self,level=0): + + def printtree(self, level=0): '''returns a representation of the tree using indentation''' - r='' + r = '' for i in range(level): - r+=' ' - r+=self.name + r += ' ' + r += self.name if self.name in b_operators: - r+=self.left.printtree(level+1) - r+=self.right.printtree(level+1) + r += self.left.printtree(level + 1) + r += self.right.printtree(level + 1) elif self.name in u_operators: - r+='\t%s\n' % self.prop - r+=self.child.printtree(level+1) - - return '\n'+r + r += '\t%s\n' % self.prop + r += self.child.printtree(level + 1) + + return '\n' + r + def get_left_leaf(self): '''This function returns the leftmost leaf in the tree. It is needed by some optimizations.''' - if self.kind==RELATION: + if self.kind == RELATION: return self - elif self.kind==UNARY: + elif self.kind == UNARY: return self.child.get_left_leaf() - elif self.kind==BINARY: + elif self.kind == BINARY: return self.left.get_left_leaf() - - - def result_format(self,rels): + + def result_format(self, rels): '''This function returns a list containing the fields that the resulting relation will have. It requires a dictionary where keys are the names of the relations and the values are the relation objects.''' - if rels==None: + if rels == None: return - - if self.kind==RELATION: + + if self.kind == RELATION: return list(rels[self.name].header.attributes) - elif self.kind==BINARY and self.name in (DIFFERENCE,UNION,INTERSECTION): + elif self.kind == BINARY and self.name in (DIFFERENCE, UNION, INTERSECTION): return self.left.result_format(rels) - elif self.kind==BINARY and self.name==DIVISION: + elif self.kind == BINARY and self.name == DIVISION: return list(set(self.left.result_format(rels)) - set(self.right.result_format(rels))) - elif self.name==PROJECTION: - l=[] + elif self.name == PROJECTION: + l = [] for i in self.prop.split(','): l.append(i.strip()) return l - elif self.name==PRODUCT: - return self.left.result_format(rels)+self.right.result_format(rels) - elif self.name==SELECTION: + elif self.name == PRODUCT: + return self.left.result_format(rels) + self.right.result_format(rels) + elif self.name == SELECTION: return self.child.result_format(rels) - elif self.name==RENAME: - _vars={} + elif self.name == RENAME: + _vars = {} for i in self.prop.split(','): - q=i.split(ARROW) - _vars[q[0].strip()]=q[1].strip() - - _fields=self.child.result_format(rels) + q = i.split(ARROW) + _vars[q[0].strip()] = q[1].strip() + + _fields = self.child.result_format(rels) for i in range(len(_fields)): if _fields[i] in _vars: - _fields[i]=_vars[_fields[i]] + _fields[i] = _vars[_fields[i]] return _fields - elif self.name in (JOIN,JOIN_LEFT,JOIN_RIGHT,JOIN_FULL): + elif self.name in (JOIN, JOIN_LEFT, JOIN_RIGHT, JOIN_FULL): return list(set(self.left.result_format(rels)).union(set(self.right.result_format(rels)))) - def __eq__(self,other): - if not (isinstance(other,node) and self.name==other.name and self.kind==other.kind): - return False - - if self.kind==UNARY: - if other.prop!=self.prop: - return False - return self.child==other.child - if self.kind==BINARY: - return self.left==other.left and self.right==other.right - return True - - def __str__(self): - if (self.kind==RELATION): - return self.name - elif (self.kind==UNARY): - return self.name + " "+ self.prop+ " (" + self.child.__str__() +")" - elif (self.kind==BINARY): - if self.left.kind==RELATION: - le=self.left.__str__() - else: - le="("+self.left.__str__()+")" - if self.right.kind==RELATION: - re=self.right.__str__() - else: - re="("+self.right.__str__()+")" - - return (le+ self.name +re) -def _find_matching_parenthesis(expression,start=0,openpar=u'(',closepar=u')'): + def __eq__(self, other): + if not (isinstance(other, node) and self.name == other.name and self.kind == other.kind): + return False + + if self.kind == UNARY: + if other.prop != self.prop: + return False + return self.child == other.child + if self.kind == BINARY: + return self.left == other.left and self.right == other.right + return True + + def __str__(self): + if (self.kind == RELATION): + return self.name + elif (self.kind == UNARY): + return self.name + " " + self.prop + " (" + self.child.__str__() + ")" + elif (self.kind == BINARY): + if self.left.kind == RELATION: + le = self.left.__str__() + else: + le = "(" + self.left.__str__() + ")" + if self.right.kind == RELATION: + re = self.right.__str__() + else: + re = "(" + self.right.__str__() + ")" + + return (le + self.name + re) + + +def _find_matching_parenthesis(expression, start=0, openpar=u'(', closepar=u')'): '''This function returns the position of the matching close parenthesis to the 1st open parenthesis found starting from start (0 by default)''' - par_count=0 #Count of parenthesis - for i in range(start,len(expression)): - if expression[i]==openpar: - par_count+=1 - elif expression[i]==closepar: - par_count-=1 - if par_count==0: - return i #Closing parenthesis of the parameter + par_count = 0 # Count of parenthesis + for i in range(start, len(expression)): + if expression[i] == openpar: + par_count += 1 + elif expression[i] == closepar: + par_count -= 1 + if par_count == 0: + return i # Closing parenthesis of the parameter + def tokenize(expression): '''This function converts an expression into a list where every token of the expression is an item of a list. Expressions into parenthesis will be converted into sublists.''' - if not isinstance(expression,unicode): + if not isinstance(expression, unicode): raise TokenizerException('expected unicode') - - items=[] #List for the tokens - + + items = [] # List for the tokens + '''This is a state machine. Initial status is determined by the starting of the expression. There are the following statuses: - + relation: this is the status if the expressions begins with something else than an operator or a parenthesis. binary operator: this is the status when parsing a binary operator, nothing much to say @@ -290,9 +308,9 @@ def tokenize(expression): sub-expression. sub-expression: this status is entered when finding a '(' and will be exited when finding a ')'. means that the others open must be counted to determine which close is the right one.''' - - expression=expression.strip() #Removes initial and endind spaces - state=0 + + expression = expression.strip() # Removes initial and endind spaces + state = 0 ''' 0 initial and useless 1 previous stuff was a relation @@ -301,83 +319,92 @@ def tokenize(expression): 4 previous stuff was a binary operator ''' - while len(expression)>0: - - if expression.startswith('('): #Parenthesis state - state=2 - end=_find_matching_parenthesis(expression) - if end==None: - raise TokenizerException("Missing matching ')' in '%s'" %expression) - #Appends the tokenization of the content of the parenthesis + while len(expression) > 0: + + if expression.startswith('('): # Parenthesis state + state = 2 + end = _find_matching_parenthesis(expression) + if end == None: + raise TokenizerException( + "Missing matching ')' in '%s'" % expression) + # Appends the tokenization of the content of the parenthesis items.append(tokenize(expression[1:end])) - #Removes the entire parentesis and content from the expression - expression=expression[end+1:].strip() - - elif expression.startswith((u"σ",u"π",u"ρ")): #Unary 2 bytes - items.append(expression[0:1]) #Adding operator in the top of the list - expression=expression[1:].strip() #Removing operator from the expression - - if expression.startswith('('): #Expression with parenthesis, so adding what's between open and close without tokenization - par=expression.find('(',_find_matching_parenthesis(expression)) - else: #Expression without parenthesis, so adding what's between start and parenthesis as whole - par=expression.find('(') - - items.append(expression[:par].strip()) #Inserting parameter of the operator - expression=expression[par:].strip() #Removing parameter from the expression - elif expression.startswith((u"÷",u"ᑎ",u"ᑌ",u"*",u"-")): + # Removes the entire parentesis and content from the expression + expression = expression[end + 1:].strip() + + elif expression.startswith((u"σ", u"π", u"ρ")): # Unary 2 bytes + items.append(expression[0:1]) + #Adding operator in the top of the list + expression = expression[ + 1:].strip() # Removing operator from the expression + + if expression.startswith('('): # Expression with parenthesis, so adding what's between open and close without tokenization + par = expression.find( + '(', _find_matching_parenthesis(expression)) + else: # Expression without parenthesis, so adding what's between start and parenthesis as whole + par = expression.find('(') + + items.append(expression[:par].strip()) + #Inserting parameter of the operator + expression = expression[ + par:].strip() # Removing parameter from the expression + elif expression.startswith((u"÷", u"ᑎ", u"ᑌ", u"*", u"-")): items.append(expression[0]) - expression=expression[1:].strip() #1 char from the expression - state=4 - elif expression.startswith(u"ᐅ"): #Binary long - i=expression.find(u"ᐊ") - if i==-1: + expression = expression[1:].strip() # 1 char from the expression + state = 4 + elif expression.startswith(u"ᐅ"): # Binary long + i = expression.find(u"ᐊ") + if i == -1: raise TokenizerException(u"Expected ᐊ in %s" % (expression,)) - items.append(expression[:i+1]) - expression=expression[i+1:].strip() - state=4 - elif re.match(r'[_0-9A-Za-z]',expression[0])==None: #At this point we only have relation names, so we raise errors for anything else - raise TokenizerException("Unexpected '%c' in '%s'" % (expression[0],expression)) - else: #Relation (hopefully) - if state==1: #Previous was a relation, appending to the last token - i=items.pop() - items.append(i+expression[0]) - expression=expression[1:].strip() #1 char from the expression + items.append(expression[:i + 1]) + expression = expression[i + 1:].strip() + state = 4 + elif re.match(r'[_0-9A-Za-z]', expression[0]) == None: # At this point we only have relation names, so we raise errors for anything else + raise TokenizerException( + "Unexpected '%c' in '%s'" % (expression[0], expression)) + else: # Relation (hopefully) + if state == 1: # Previous was a relation, appending to the last token + i = items.pop() + items.append(i + expression[0]) + expression = expression[ + 1:].strip() # 1 char from the expression else: - state=1 + state = 1 items.append(expression[0]) - expression=expression[1:].strip() #1 char from the expression - + expression = expression[ + 1:].strip() # 1 char from the expression + return items + def tree(expression): '''This function parses a relational algebra expression into a tree and returns the root node using the Node class defined in this module.''' return node(tokenize(expression)) - def parse(expr): - '''This function parses a relational algebra expression, converting it into python, + '''This function parses a relational algebra expression, converting it into python, executable by eval function to get the result of the expression. It has 2 class of operators: without parameters *, -, ᑌ, ᑎ, ᐅᐊ, ᐅLEFTᐊ, ᐅRIGHTᐊ, ᐅFULLᐊ with parameters: σ, π, ρ - + Syntax for operators without parameters is: relation operator relation - + Syntax for operators with parameters is: operator parameters (relation) - + Since a*b is a relation itself, you can parse π a,b (a*b). And since π a,b (A) is a relation, you can parse π a,b (A) ᑌ B. - + You can use parenthesis to change priority: a ᐅᐊ (q ᑌ d). - + IMPORTANT: all strings must be unicode - + EXAMPLES σage > 25 and rank == weight(A) Q ᐅᐊ π a,b(A) ᐅᐊ B @@ -387,13 +414,13 @@ def parse(expr): A ᐅᐊ B ''' return tree(expr).toPython() - -if __name__=="__main__": + +if __name__ == "__main__": while True: - e=unicode(raw_input("Expression: "),'utf-8') + e = unicode(raw_input("Expression: "), 'utf-8') print parse(e) - - #b=u"σ age>1 and skill=='C' (peopleᐅᐊskills)" - #print b[0] - #parse(b) - pass \ No newline at end of file + + # b=u"σ age>1 and skill=='C' (peopleᐅᐊskills)" + # print b[0] + # parse(b) + pass diff --git a/relational/query.py b/relational/query.py index 33a95ac..949b1a1 100644 --- a/relational/query.py +++ b/relational/query.py @@ -1,39 +1,42 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli # # This module provides a classes to represent queries import parser + class TypeException(Exception): pass + class Query(object): - def __init__(self,query): - - if not isinstance(query,unicode): + + def __init__(self, query): + + if not isinstance(query, unicode): raise TypeException('Expected unicode') - + self.query = query self.tree = parser.tree(query) - #TODO self.query_code = parser - + # TODO self.query_code = parser + self.optimized = None self.optimized_query = None - self.optimized_code = None \ No newline at end of file + self.optimized_code = None diff --git a/relational/relation.py b/relational/relation.py index 8b74bb0..82bcfba 100644 --- a/relational/relation.py +++ b/relational/relation.py @@ -1,20 +1,20 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli # # This module provides a classes to represent relations and to perform @@ -23,410 +23,420 @@ from rtypes import * import csv + class relation (object): + '''This objects defines a relation (as a group of consistent tuples) and operations A relation can be represented using a table Calling an operation and providing a non relation parameter when it is expected will - result in a None value''' - __hash__=None - - def __init__(self,filename=""): + result in a None value''' + __hash__ = None + + def __init__(self, filename=""): '''Creates a relation, accepts a filename and then it will load the relation from that file. If no parameter is supplied an empty relation is created. Empty relations are used in internal operations. By default the file will be handled like a comma separated as described in RFC4180.''' - - self._readonly=False - - if len(filename)==0:#Empty relation - self.content=set() - self.header=header([]) - return - #Opening file - fp=file(filename) - reader=csv.reader(fp) #Creating a csv reader - self.header=header(reader.next()) # read 1st line - self.content=set() - - for i in reader.__iter__(): #Iterating rows + self._readonly = False + + if len(filename) == 0: # Empty relation + self.content = set() + self.header = header([]) + return + # Opening file + fp = file(filename) + + reader = csv.reader(fp) # Creating a csv reader + self.header = header(reader.next()) # read 1st line + self.content = set() + + for i in reader.__iter__(): # Iterating rows self.content.add(tuple(i)) - - #Closing file + + # Closing file fp.close() - + def _make_writable(self): - '''If this relation is marked as readonly, this + '''If this relation is marked as readonly, this method will copy the content to make it writable too''' - + if self._readonly: - self.content=set(self.content) - self._readonly=False - - def save(self,filename): + self.content = set(self.content) + self._readonly = False + + def save(self, filename): '''Saves the relation in a file. By default will save using the csv format as defined in RFC4180, but setting comma_separated to False, it will use the old format with space separated values. ''' - - fp=file(filename,'w') #Opening file in write mode - - writer=csv.writer(fp) #Creating csv writer - - #It wants an iterable containing iterables - head=(self.header.attributes,) + + fp = file(filename, 'w') # Opening file in write mode + + writer = csv.writer(fp) # Creating csv writer + + # It wants an iterable containing iterables + head = (self.header.attributes,) writer.writerows(head) - - #Writing content, already in the correct format + + # Writing content, already in the correct format writer.writerows(self.content) - fp.close() #Closing file - - def _rearrange_(self,other): + fp.close() # Closing file + + def _rearrange_(self, other): '''If two relations share the same attributes in a different order, this method will use projection to make them have the same attributes' order. - It is not exactely related to relational algebra. Just a method used + It is not exactely related to relational algebra. Just a method used internally. Will return None if they don't share the same attributes''' - if (self.__class__!=other.__class__): + if (self.__class__ != other.__class__): return None if self.header.sharedAttributes(other.header) == len(self.header.attributes) == len(other.header.attributes): return other.projection(list(self.header.attributes)) return None - - def _autocast(self,string): + + def _autocast(self, string): '''Depending on the regexp matched by the string, it will perform automatic casting''' - tmpstring=rstring(string) - if len(tmpstring)>0 and tmpstring.isInt(): + tmpstring = rstring(string) + if len(tmpstring) > 0 and tmpstring.isInt(): return int(tmpstring) - elif len(tmpstring)>0 and tmpstring.isFloat(): + elif len(tmpstring) > 0 and tmpstring.isFloat(): return float(tmpstring) - elif len(tmpstring)>0 and tmpstring.isDate(): + elif len(tmpstring) > 0 and tmpstring.isDate(): return rdate(tmpstring) else: return tmpstring - - def selection(self,expr): + + def selection(self, expr): '''Selection, expr must be a valid boolean expression, can contain field names, constant, math operations and boolean ones.''' - attributes={} - newt=relation() - newt.header=header(list(self.header.attributes)) + attributes = {} + newt = relation() + newt.header = header(list(self.header.attributes)) for i in self.content: - #Fills the attributes dictionary with the values of the tuple + # Fills the attributes dictionary with the values of the tuple for j in range(len(self.header.attributes)): - attributes[self.header.attributes[j]]=self._autocast(i[j]) - + attributes[self.header.attributes[j]] = self._autocast(i[j]) + try: - if eval(expr,attributes): + if eval(expr, attributes): newt.content.add(i) - except Exception,e: - raise Exception("Failed to evaluate %s\n%s" % (expr,e.__str__())) + except Exception, e: + raise Exception( + "Failed to evaluate %s\n%s" % (expr, e.__str__())) return newt - def product (self,other): + + def product(self, other): '''Cartesian product, attributes must be different to avoid collisions - Doing this operation on relations with colliding attributes will + Doing this operation on relations with colliding attributes will cause an exception. It is possible to use rename on attributes and then use the product''' - - if (self.__class__!=other.__class__)or(self.header.sharedAttributes(other.header)!=0): - raise Exception('Unable to perform product on relations with colliding attributes') - newt=relation() - newt.header=header(self.header.attributes+other.header.attributes) - + + if (self.__class__ != other.__class__)or(self.header.sharedAttributes(other.header) != 0): + raise Exception( + 'Unable to perform product on relations with colliding attributes') + newt = relation() + newt.header = header(self.header.attributes + other.header.attributes) + for i in self.content: for j in other.content: - newt.content.add(i+j) + newt.content.add(i + j) return newt - - - def projection(self,* attributes): + + def projection(self, * attributes): '''Projection operator, takes many parameters, for each field to use. Can also use a single parameter with a list. Will delete duplicate items - If an empty list or no parameters are provided, returns None''' - #Parameters are supplied in a list, instead with multiple parameters - if isinstance(attributes[0],list): - attributes=attributes[0] - - #Avoiding duplicated attributes - attributes1=[] + If an empty list or no parameters are provided, returns None''' + # Parameters are supplied in a list, instead with multiple parameters + if isinstance(attributes[0], list): + attributes = attributes[0] + + # Avoiding duplicated attributes + attributes1 = [] for i in attributes: if i not in attributes1: attributes1.append(i) - attributes=attributes1 - - ids=self.header.getAttributesId(attributes) - - if len(ids)==0 or len(ids)!=len(attributes): + attributes = attributes1 + + ids = self.header.getAttributesId(attributes) + + if len(ids) == 0 or len(ids) != len(attributes): raise Exception('Invalid attributes for projection') - newt=relation() - #Create the header - h=[] + newt = relation() + # Create the header + h = [] for i in ids: h.append(self.header.attributes[i]) - newt.header=header(h) - - #Create the body + newt.header = header(h) + + # Create the body for i in self.content: - row=[] + row = [] for j in ids: row.append(i[j]) newt.content.add(tuple(row)) return newt - - def rename(self,params): + + def rename(self, params): '''Operation rename. Takes a dictionary Will replace the itmem with its content. For example if you want to rename a to b, provide {"a":"b"} ''' - result=[] - - newt=relation() - newt.header=header(list(self.header.attributes)) - - for old,new in params.iteritems(): - if (newt.header.rename(old,new)) == False: + result = [] + + newt = relation() + newt.header = header(list(self.header.attributes)) + + for old, new in params.iteritems(): + if (newt.header.rename(old, new)) == False: raise Exception('Unable to find attribute: %s' % old) - - newt.content=self.content - newt._readonly=True + + newt.content = self.content + newt._readonly = True return newt - - def intersection(self,other): + + def intersection(self, other): '''Intersection operation. The result will contain items present in both operands. Will return an empty one if there are no common items. Will return None if headers are different. It is possible to use projection and rename to make headers match.''' - other=self._rearrange_(other) #Rearranges attributes' order - if (self.__class__!=other.__class__)or(self.header!=other.header): - raise Exception('Unable to perform intersection on relations with different attributes') - newt=relation() - newt.header=header(list(self.header.attributes)) - - newt.content=self.content.intersection(other.content) + other = self._rearrange_(other) # Rearranges attributes' order + if (self.__class__ != other.__class__)or(self.header != other.header): + raise Exception( + 'Unable to perform intersection on relations with different attributes') + newt = relation() + newt.header = header(list(self.header.attributes)) + + newt.content = self.content.intersection(other.content) return newt - - def difference(self,other): + + def difference(self, other): '''Difference operation. The result will contain items present in first operand but not in second one. Will return an empty one if the second is a superset of first. Will return None if headers are different. It is possible to use projection and rename to make headers match.''' - other=self._rearrange_(other) #Rearranges attributes' order - if (self.__class__!=other.__class__)or(self.header!=other.header): - raise Exception('Unable to perform difference on relations with different attributes') - newt=relation() - newt.header=header(list(self.header.attributes)) - - newt.content=self.content.difference(other.content) + other = self._rearrange_(other) # Rearranges attributes' order + if (self.__class__ != other.__class__)or(self.header != other.header): + raise Exception( + 'Unable to perform difference on relations with different attributes') + newt = relation() + newt.header = header(list(self.header.attributes)) + + newt.content = self.content.difference(other.content) return newt - def division(self,other): + + def division(self, other): '''Division operator The division is a binary operation that is written as R ÷ S. The result consists of the restrictions of tuples in R to the attribute names unique to R, i.e., in the header of R but not in the header of S, for which it holds that all their combinations with tuples - in S are present in R. + in S are present in R. ''' - - #d_headers are the headers from self that aren't also headers in other - d_headers=list(set(self.header.attributes) - set(other.header.attributes)) - - + + # d_headers are the headers from self that aren't also headers in other + d_headers = list( + set(self.header.attributes) - set(other.header.attributes)) + ''' Wikipedia defines the division as follows: - + a1,....,an are the d_headers - + T := πa1,...,an(R) × S U := T - R V := πa1,...,an(U) W := πa1,...,an(R) - V - + W is the result that we want ''' - - t=self.projection(d_headers).product(other) + + t = self.projection(d_headers).product(other) return self.projection(d_headers).difference(t.difference(self).projection(d_headers)) - - def union(self,other): + + def union(self, other): '''Union operation. The result will contain items present in first and second operands. Will return an empty one if both are empty. Will not insert tuplicated items. Will return None if headers are different. It is possible to use projection and rename to make headers match.''' - other=self._rearrange_(other) #Rearranges attributes' order - if (self.__class__!=other.__class__)or(self.header!=other.header): - raise Exception('Unable to perform union on relations with different attributes') - newt=relation() - newt.header=header(list(self.header.attributes)) - - newt.content=self.content.union(other.content) + other = self._rearrange_(other) # Rearranges attributes' order + if (self.__class__ != other.__class__)or(self.header != other.header): + raise Exception( + 'Unable to perform union on relations with different attributes') + newt = relation() + newt.header = header(list(self.header.attributes)) + + newt.content = self.content.union(other.content) return newt - def thetajoin(self,other,expr): + + def thetajoin(self, other, expr): '''Defined as product and then selection with the given expression.''' return self.product(other).selection(expr) - - def outer(self,other): + + def outer(self, other): '''Does a left and a right outer join and returns their union.''' - a=self.outer_right(other) - b=self.outer_left(other) - + a = self.outer_right(other) + b = self.outer_left(other) + return a.union(b) - - def outer_right(self,other): + + def outer_right(self, other): '''Outer right join. Considers self as left and param as right. If the tuple has no corrispondence, empy attributes are filled with a "---" string. This is due to the fact that empty string or a space would cause problems when saving the relation. Just like natural join, it works considering shared attributes.''' return other.outer_left(self) - - def outer_left(self,other,swap=False): - '''Outer left join. Considers self as left and param as right. If the - tuple has no corrispondence, empty attributes are filled with a "---" + + def outer_left(self, other, swap=False): + '''Outer left join. Considers self as left and param as right. If the + tuple has no corrispondence, empty attributes are filled with a "---" string. This is due to the fact that empty string or a space would cause problems when saving the relation. Just like natural join, it works considering shared attributes.''' - - shared=[] + + shared = [] for i in self.header.attributes: if i in other.header.attributes: shared.append(i) - - newt=relation() #Creates the new relation - - #Adds all the attributes of the 1st relation - newt.header=header(list(self.header.attributes)) - - #Adds all the attributes of the 2nd, when non shared + + newt = relation() # Creates the new relation + + # Adds all the attributes of the 1st relation + newt.header = header(list(self.header.attributes)) + + # Adds all the attributes of the 2nd, when non shared for i in other.header.attributes: if i not in shared: newt.header.attributes.append(i) - #Shared ids of self - sid=self.header.getAttributesId(shared) - #Shared ids of the other relation - oid=other.header.getAttributesId(shared) - - #Non shared ids of the other relation - noid=[] + # Shared ids of self + sid = self.header.getAttributesId(shared) + # Shared ids of the other relation + oid = other.header.getAttributesId(shared) + + # Non shared ids of the other relation + noid = [] for i in range(len(other.header.attributes)): if i not in oid: noid.append(i) - + for i in self.content: - #Tuple partecipated to the join? - added=False + # Tuple partecipated to the join? + added = False for j in other.content: - match=True + match = True for k in range(len(sid)): - match=match and ( i[sid[k]]== j[oid[k]]) - + match = match and (i[sid[k]] == j[oid[k]]) + if match: - item=list(i) + item = list(i) for l in noid: item.append(j[l]) - + newt.content.add(tuple(item)) - added=True - #If it didn't partecipate, adds it + added = True + # If it didn't partecipate, adds it if not added: - item=list(i) + item = list(i) for l in range(len(noid)): item.append("---") newt.content.add(tuple(item)) - + return newt - - def join(self,other): + + def join(self, other): '''Natural join, joins on shared attributes (one or more). If there are no shared attributes, it will behave as cartesian product.''' - - #List of attributes in common between the relations - shared=list(set(self.header.attributes).intersection(set(other.header.attributes))) - - newt=relation() #Creates the new relation - - #Adding to the headers all the fields, done like that because order is needed - newt.header=header(list(self.header.attributes)) + + # List of attributes in common between the relations + shared = list(set(self.header.attributes) + .intersection(set(other.header.attributes))) + + newt = relation() # Creates the new relation + + # Adding to the headers all the fields, done like that because order is + # needed + newt.header = header(list(self.header.attributes)) for i in other.header.attributes: if i not in shared: newt.header.attributes.append(i) - - #Shared ids of self - sid=self.header.getAttributesId(shared) - #Shared ids of the other relation - oid=other.header.getAttributesId(shared) - - #Non shared ids of the other relation - noid=[] + + # Shared ids of self + sid = self.header.getAttributesId(shared) + # Shared ids of the other relation + oid = other.header.getAttributesId(shared) + + # Non shared ids of the other relation + noid = [] for i in range(len(other.header.attributes)): if i not in oid: noid.append(i) - + for i in self.content: for j in other.content: - match=True + match = True for k in range(len(sid)): - match=match and ( i[sid[k]]== j[oid[k]]) - + match = match and (i[sid[k]] == j[oid[k]]) + if match: - item=list(i) + item = list(i) for l in noid: item.append(j[l]) - + newt.content.add(tuple(item)) - + return newt - def __eq__(self,other): + + def __eq__(self, other): '''Returns true if the relations are the same, ignoring order of items. This operation is rather heavy, since it requires sorting and comparing.''' - other=self._rearrange_(other) #Rearranges attributes' order so can compare tuples directly - - if (self.__class__!=other.__class__)or(self.header!=other.header): - return False #Both parameters must be a relation + other = self._rearrange_( + other) # Rearranges attributes' order so can compare tuples directly - if set(self.header.attributes)!=set(other.header.attributes): + if (self.__class__ != other.__class__)or(self.header != other.header): + return False # Both parameters must be a relation + + if set(self.header.attributes) != set(other.header.attributes): return False - - - - #comparing content - return self.content==other.content - + + # comparing content + return self.content == other.content + def __str__(self): - '''Returns a string representation of the relation, can be printed with + '''Returns a string representation of the relation, can be printed with monospaced fonts''' - m_len=[] #Maximum lenght string + m_len = [] # Maximum lenght string for f in self.header.attributes: m_len.append(len(f)) - + for f in self.content: - col=0 + col = 0 for i in f: - if len(i)>m_len[col]: - m_len[col]=len(i) - col+=1 - - res="" + if len(i) > m_len[col]: + m_len[col] = len(i) + col += 1 + + res = "" for f in range(len(self.header.attributes)): - res+="%s"%(self.header.attributes[f].ljust(2+m_len[f])) - - + res += "%s" % (self.header.attributes[f].ljust(2 + m_len[f])) + for r in self.content: - col=0 - res+="\n" + col = 0 + res += "\n" for i in r: - res+="%s"% (i.ljust(2+m_len[col])) - col+=1 - + res += "%s" % (i.ljust(2 + m_len[col])) + col += 1 + return res - def update(self,expr,dic): + def update(self, expr, dic): '''Update, expr must be a valid boolean expression, can contain field names, constant, math operations and boolean ones. This operation will change the relation itself instead of generating a new one, @@ -435,122 +445,123 @@ class relation (object): will be converted into a string. Returns the number of affected rows.''' self._make_writable() - affected=0 - attributes={} - keys=dic.keys() #List of headers to modify - f_ids=self.header.getAttributesId(keys) #List of indexes corresponding to keys - - #new_content=[] #New content of the relation + affected = 0 + attributes = {} + keys = dic.keys() # List of headers to modify + f_ids = self.header.getAttributesId( + keys) # List of indexes corresponding to keys + + # new_content=[] #New content of the relation for i in self.content: for j in range(len(self.header.attributes)): - attributes[self.header.attributes[j]]=self._autocast(i[j]) - - if eval(expr,attributes): #If expr is true, changing the tuple - affected+=1 - new_tuple=list(i) - #Deleting the tuple, instead of changing it, so other - #relations can still point to the same list without - #being affected. - self.content.remove(i) + attributes[self.header.attributes[j]] = self._autocast(i[j]) + + if eval(expr, attributes): # If expr is true, changing the tuple + affected += 1 + new_tuple = list(i) + # Deleting the tuple, instead of changing it, so other + # relations can still point to the same list without + # being affected. + self.content.remove(i) for k in range(len(keys)): - new_tuple[f_ids[k]]=str(dic[keys[k]]) + new_tuple[f_ids[k]] = str(dic[keys[k]]) self.content.add(tuple(new_tuple)) return affected - - def insert(self,values): + + def insert(self, values): '''Inserts a tuple in the relation. This function will not insert duplicate tuples. All the values will be converted in string. Will return the number of inserted rows.''' - - #Returns if tuple doesn't fit the number of attributes + + # Returns if tuple doesn't fit the number of attributes if len(self.header.attributes) != len(values): return 0 - + self._make_writable() - - #Creating list containing only strings - t=[] + + # Creating list containing only strings + t = [] for i in values: t.append(str(i)) - - prevlen=len(self.content) + + prevlen = len(self.content) self.content.add(tuple(t)) - return len(self.content)-prevlen - - def delete(self,expr): + return len(self.content) - prevlen + + def delete(self, expr): '''Delete, expr must be a valid boolean expression, can contain field names, constant, math operations and boolean ones. This operation will change the relation itself instead of generating a new one, deleting all the tuples that make expr true. Returns the number of affected rows.''' self._make_writable() - attributes={} - affected=len(self.content) - new_content=set() #New content of the relation + attributes = {} + affected = len(self.content) + new_content = set() # New content of the relation for i in self.content: for j in range(len(self.header.attributes)): - attributes[self.header.attributes[j]]=self._autocast(i[j]) - - - if not eval(expr,attributes): - affected-=1 + attributes[self.header.attributes[j]] = self._autocast(i[j]) + + if not eval(expr, attributes): + affected -= 1 new_content.add(i) - self.content=new_content + self.content = new_content return affected - + + class header (object): + '''This class defines the header of a relation. It is used within relations to know if requested operations are accepted''' - - #Since relations are mutalbe we explicitly block hashing them - __hash__=None - - def __init__(self,attributes): + + # Since relations are mutalbe we explicitly block hashing them + __hash__ = None + + def __init__(self, attributes): '''Accepts a list with attributes' names. Names MUST be unique''' - self.attributes=attributes - + self.attributes = attributes + for i in attributes: if not is_valid_relation_name(i): - raise Exception('"%s" is not a valid attribute name'% i) - + raise Exception('"%s" is not a valid attribute name' % i) + def __repr__(self): return "header(%s)" % (self.attributes.__repr__()) - - - def rename(self,old,new): + + def rename(self, old, new): '''Renames a field. Doesn't check if it is a duplicate. Returns True if the field was renamed, False otherwise''' - + if not is_valid_relation_name(new): - raise Exception('%s is not a valid attribute name'% new) - + raise Exception('%s is not a valid attribute name' % new) + try: - id_=self.attributes.index(old) - self.attributes[id_]=new + id_ = self.attributes.index(old) + self.attributes[id_] = new except: return False return True - - def sharedAttributes(self,other): + + def sharedAttributes(self, other): '''Returns how many attributes this header has in common with a given one''' return len(set(self.attributes).intersection(set(other.attributes))) - + def __str__(self): '''Returns String representation of the field's list''' return self.attributes.__str__() - - def __eq__(self,other): - return self.attributes==other.attributes - def __ne__(self,other): - return self.attributes!=other.attributes - - def getAttributesId(self,param): - '''Returns a list with numeric index corresponding to field's name''' - res=[] + + def __eq__(self, other): + return self.attributes == other.attributes + + def __ne__(self, other): + return self.attributes != other.attributes + + def getAttributesId(self, param): + '''Returns a list with numeric index corresponding to field's name''' + res = [] for i in param: for j in range(len(self.attributes)): - if i==self.attributes[j]: + if i == self.attributes[j]: res.append(j) return res - \ No newline at end of file diff --git a/relational/rtypes.py b/relational/rtypes.py index 533b708..7ddc068 100644 --- a/relational/rtypes.py +++ b/relational/rtypes.py @@ -1,20 +1,20 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relation is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli # # Custom types for relational algebra. @@ -24,29 +24,33 @@ import datetime import re + class rstring (str): + '''String subclass with some custom methods''' + def isInt(self): '''Returns true if the string represents an int number it only considers as int numbers the strings matching the following regexp: r'^[\+\-]{0,1}[0-9]+$' ''' - if re.match(r'^[\+\-]{0,1}[0-9]+$',self)==None: + if re.match(r'^[\+\-]{0,1}[0-9]+$', self) == None: return False else: return True + def isFloat(self): '''Returns true if the string represents a float number it only considers as float numbers, the strings matching the following regexp: r'^[\+\-]{0,1}[0-9]+(\.([0-9])+)?$' ''' - if re.match(r'^[\+\-]{0,1}[0-9]+(\.([0-9])+)?$',self)==None: + if re.match(r'^[\+\-]{0,1}[0-9]+(\.([0-9])+)?$', self) == None: return False else: return True - + def isDate(self): '''Returns true if the string represents a date, in the format YYYY-MM-DD. as separators '-' , '\', '/' are allowed. @@ -57,24 +61,25 @@ class rstring (str): return self._isdate except: pass - - r= re.match(r'^([0-9]{1,4})(\\|-|/)([0-9]{1,2})(\\|-|/)([0-9]{1,2})$',self) - if r==None: - self._isdate=False - self._date=None + + r = re.match( + r'^([0-9]{1,4})(\\|-|/)([0-9]{1,2})(\\|-|/)([0-9]{1,2})$', self) + if r == None: + self._isdate = False + self._date = None return False - - try: #Any of the following operations can generate an exception, if it happens, we aren't dealing with a date - year=int(r.group(1)) - month=int(r.group(3)) - day=int(r.group(5)) - d=datetime.date(year,month,day) - self._isdate=True - self._date=d + + try: # Any of the following operations can generate an exception, if it happens, we aren't dealing with a date + year = int(r.group(1)) + month = int(r.group(3)) + day = int(r.group(5)) + d = datetime.date(year, month, day) + self._isdate = True + self._date = d return True except: - self._isdate=False - self._date=None + self._isdate = False + self._date = None return False def getDate(self): @@ -84,46 +89,59 @@ class rstring (str): except: self.isDate() return self._date + + class rdate (object): + '''Represents a date''' - def __init__(self,date): + + def __init__(self, date): '''date: A string representing a date''' - if not isinstance(date,rstring): - date=rstring(date) - - self.intdate=date.getDate() - self.day= self.intdate.day - self.month=self.intdate.month - self.weekday=self.intdate.weekday() - self.year=self.intdate.year - + if not isinstance(date, rstring): + date = rstring(date) + + self.intdate = date.getDate() + self.day = self.intdate.day + self.month = self.intdate.month + self.weekday = self.intdate.weekday() + self.year = self.intdate.year + def __hash__(self): return self.intdate.__hash__() + def __str__(self): return self.intdate.__str__() - def __add__(self,days): - res=self.intdate+datetime.timedelta(days) + + def __add__(self, days): + res = self.intdate + datetime.timedelta(days) return rdate(res.__str__()) - def __eq__(self,other): - return self.intdate==other.intdate - def __ge__(self,other): - return self.intdate>=other.intdate - def __gt__ (self,other): - return self.intdate>other.intdate - def __le__ (self,other): - return self.intdate<=other.intdate - def __lt__ (self,other): - return self.intdate= other.intdate + + def __gt__(self, other): + return self.intdate > other.intdate + + def __le__(self, other): + return self.intdate <= other.intdate + + def __lt__(self, other): + return self.intdate < other.intdate + + def __ne__(self, other): + return self.intdate != other.intdate + + def __sub__(self, other): + return (self.intdate - other.intdate).days def is_valid_relation_name(name): '''Checks if a name is valid for a relation. Returns boolean''' - if re.match(r'^[_a-zA-Z]+[_a-zA-Z0-9]*$',name)==None: + if re.match(r'^[_a-zA-Z]+[_a-zA-Z0-9]*$', name) == None: return False else: - return True \ No newline at end of file + return True diff --git a/relational_curses/maingui.py b/relational_curses/maingui.py index ab5ffeb..ab5f242 100644 --- a/relational_curses/maingui.py +++ b/relational_curses/maingui.py @@ -1,20 +1,20 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2010 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli import curses import curses.panel @@ -23,57 +23,53 @@ import signal import sys from relational import * + def terminate(*a): '''Restores the terminal and terminates''' curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() - + sys.exit(0) + def main(): global stdscr - #Initializes the signal - signal.signal(signal.SIGINT,terminate) - - #Initialize locale, to print unicode chars - locale.setlocale(locale.LC_ALL,"") - #Initializes curses + # Initializes the signal + signal.signal(signal.SIGINT, terminate) + + # Initialize locale, to print unicode chars + locale.setlocale(locale.LC_ALL, "") + # Initializes curses stdscr = curses.initscr() - curses.start_color() + curses.start_color() curses.noecho() - curses.cbreak()#Handles keys immediately rather than awaiting for enter + curses.cbreak() # Handles keys immediately rather than awaiting for enter stdscr.keypad(1) - termsize=stdscr.getmaxyx() - symselect=init_symbol_list(termsize) - - lop=curses.panel.new_panel(stdscr) - - win=curses.panel.new_panel(curses.newwin(termsize[0],termsize[1])) - - - - #win.window().box() - win.window().addstr(0,(termsize[1]/2)-5,"Relational") + termsize = stdscr.getmaxyx() + symselect = init_symbol_list(termsize) + + lop = curses.panel.new_panel(stdscr) + + win = curses.panel.new_panel(curses.newwin(termsize[0], termsize[1])) + + # win.window().box() + win.window().addstr(0, (termsize[1] / 2) - 5, "Relational") win.window().refresh() - #curses.napms(1000) - - - - query=curses.panel.new_panel(curses.newwin(3,termsize[1],1,0)) + # curses.napms(1000) + + query = curses.panel.new_panel(curses.newwin(3, termsize[1], 1, 0)) query.window().box() - query.window().addstr(1,1,"") + query.window().addstr(1, 1, "") query.window().refresh() - #curses.napms(1000) - - #win.show() - - #curses.napms(1000) - - - #qq=curses.textpad.Textbox(stdscr) - + # curses.napms(1000) + + # win.show() + + # curses.napms(1000) + + # qq=curses.textpad.Textbox(stdscr) '''win = curses.newwin(0, 0)#New windows for the entire screen #stdscr.border(0) stdscr.addstr(str(dir (win))) @@ -83,85 +79,89 @@ def main(): stdscr.addstr(5, 30, "Welcome to Relational")#,curses.A_REVERSE) stdscr.refresh() - + stdscr.refresh() curses.napms(300) curses.flash() curses.textpad.rectangle(win,0,0,5,10)''' - squery='' - + squery = '' + while True: c = win.window().getch() - - if c==27: #Escape - squery+=add_symbol(symselect) - - - #elif c==curses.KEY_BACKSPACE: #Delete - elif c==13: - squery=squery[:-1] + + if c == 27: # Escape + squery += add_symbol(symselect) + + # elif c==curses.KEY_BACKSPACE: #Delete + elif c == 13: + squery = squery[:-1] else: - squery+=chr(c); - - + squery += chr(c) + query.window().box() query.top() - query.window().addstr(1,1,spaces(termsize[1]-2)) - query.window().addstr(1,1,squery) - + query.window().addstr(1, 1, spaces(termsize[1] - 2)) + query.window().addstr(1, 1, squery) + query.window().refresh() -def init_symbol_list(termsize,create=True): - + + +def init_symbol_list(termsize, create=True): + if create: - p=curses.panel.new_panel(curses.newwin(15,16,2,termsize[1]/2-7)) + p = curses.panel.new_panel( + curses.newwin(15, 16, 2, termsize[1] / 2 - 7)) else: - p=termsize + p = termsize p.window().box() - #p.window().addstr(1,1,"\n8 \na \nb \n") - p.window().addstr(01,2,"0 *") - p.window().addstr(02,2,"1 -") - p.window().addstr(03,2,"2 ᑌ") - p.window().addstr(04,2,"3 ᑎ") - p.window().addstr(05,2,"4 ᐅᐊ") - p.window().addstr(06,2,"5 ᐅLEFTᐊ") - p.window().addstr(07,2,"6 ᐅRIGHTᐊ") - p.window().addstr( 8,2,"7 ᐅFULLᐊ") - p.window().addstr( 9,2,"8 σ") - p.window().addstr(10,2,"9 ρ") - p.window().addstr(11,2,"a π") - p.window().addstr(12,2,"b ➡") - p.window().addstr(13,2,"") - - #p.hide() + # p.window().addstr(1,1,"\n8 \na \nb \n") + p.window().addstr(01, 2, "0 *") + p.window().addstr(02, 2, "1 -") + p.window().addstr(03, 2, "2 ᑌ") + p.window().addstr(04, 2, "3 ᑎ") + p.window().addstr(05, 2, "4 ᐅᐊ") + p.window().addstr(06, 2, "5 ᐅLEFTᐊ") + p.window().addstr(07, 2, "6 ᐅRIGHTᐊ") + p.window().addstr(8, 2, "7 ᐅFULLᐊ") + p.window().addstr(9, 2, "8 σ") + p.window().addstr(10, 2, "9 ρ") + p.window().addstr(11, 2, "a π") + p.window().addstr(12, 2, "b ➡") + p.window().addstr(13, 2, "") + + # p.hide() return p + + def add_symbol(p): '''Shows the panel to add a symbol and then returns the choosen symbol itself''' - init_symbol_list(p,False) - - d_={'0':'*','1':'-','2':'ᑌ','3':'ᑎ','4':'ᐅᐊ','5':'ᐅLEFTᐊ','6':'ᐅRIGHTᐊ','7':'ᐅFULLᐊ','8':'σ','9':'ρ','a':'π','b':'➡'} - - + init_symbol_list(p, False) + + d_ = {'0': '*', '1': '-', '2': 'ᑌ', '3': 'ᑎ', '4': 'ᐅᐊ', '5': 'ᐅLEFTᐊ', + '6': 'ᐅRIGHTᐊ', '7': 'ᐅFULLᐊ', '8': 'σ', '9': 'ρ', 'a': 'π', 'b': '➡'} + p.show() p.top() p.window().refresh() c = p.window().getch() - + p.hide() p.window().refresh() try: - char=d_[chr(c)] + char = d_[chr(c)] except: - char='' + char = '' return char + def spaces(t): '''Returns a number of spaces specified t''' - s='' + s = '' for i in range(t): - s+=' ' + s += ' ' return s -if __name__=='__main__': +if __name__ == '__main__': main() - terminate() \ No newline at end of file + terminate() diff --git a/relational_gui.py b/relational_gui.py index 0d31a63..a33ed02 100755 --- a/relational_gui.py +++ b/relational_gui.py @@ -3,20 +3,20 @@ # coding=UTF-8 # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli import sys @@ -24,7 +24,7 @@ import os import os.path import getopt from relational import relation, parser -version="1.2" +version = "1.2" def printver(exit=True): @@ -42,14 +42,15 @@ def printver(exit=True): if exit: sys.exit(0) + def printhelp(code=0): print "Relational" print print "Usage: %s [options] [files]" % sys.argv[0] - print + print print " -v Print version and exits" print " -h Print this help and exits" - + if sys.argv[0].endswith('relational-cli'): print " -q Uses QT user interface" print " -r Uses readline user interface (default)" @@ -60,80 +61,78 @@ def printhelp(code=0): if __name__ == "__main__": if sys.argv[0].endswith('relational-cli'): - x11=False + x11 = False else: - x11=True #Will try to use the x11 interface - - #Getting command line + x11 = True # Will try to use the x11 interface + + # Getting command line try: - switches,files=getopt.getopt(sys.argv[1:],"vhqr") + switches, files = getopt.getopt(sys.argv[1:], "vhqr") except: printhelp(1) - + for i in switches: - if i[0]=='-v': + if i[0] == '-v': printver() - elif i[0]=='-h': + elif i[0] == '-h': printhelp() - elif i[0]=='-q': - x11=True - elif i[0]=='-r': - x11=False - + elif i[0] == '-q': + x11 = True + elif i[0] == '-r': + x11 = False + if x11: - - pyqt=True - + + pyqt = True + try: - import sip #needed on windows + import sip # needed on windows from PyQt4 import QtGui except: print >> sys.stderr, "PyQt seems to be missing, trying to use Pyside" from PySide import QtCore, QtGui - pyqt=False - - + pyqt = False + if pyqt: try: - from relational_gui import maingui,guihandler, about, surveyForm + from relational_gui import maingui, guihandler, about, surveyForm except: print >> sys.stderr, "Module relational_gui is missing.\nPlease install relational package." sys.exit(3) else: try: - from relational_pyside import maingui,guihandler, about, surveyForm + from relational_pyside import maingui, guihandler, about, surveyForm except: print >> sys.stderr, "Module relational_pyside is missing.\nPlease install relational package." sys.exit(3) - - - about.version=version - surveyForm.version=version - guihandler.version=version + + about.version = version + surveyForm.version = version + guihandler.version = version app = QtGui.QApplication(sys.argv) - app.setOrganizationName('None'); - app.setApplicationName('relational'); - + app.setOrganizationName('None') + app.setApplicationName('relational') + ui = maingui.Ui_MainWindow() Form = guihandler.relForm(ui) - - #if os.name=='nt': + + # if os.name=='nt': Form.setFont(QtGui.QFont("Dejavu Sans Bold")) - + ui.setupUi(Form) Form.restore_settings() - + for i in range(len(files)): if not os.path.isfile(files[i]): print >> sys.stderr, "%s is not a file" % files[i] printhelp(12) - f=files[i].split('/') - defname=f[len(f)-1].lower() - if defname.endswith(".csv"): #removes the extension - defname=defname[:-4] - print 'Loading file "%s" with name "%s"' % (files[i],defname) - Form.loadRelation(files[i],defname) + f = files[i].split('/') + defname = f[len(f) - 1].lower() + if defname.endswith(".csv"): # removes the extension + defname = defname[:-4] + print 'Loading file "%s" with name "%s"' % (files[i], defname) + Form.loadRelation(files[i], defname) Form.show() sys.exit(app.exec_()) @@ -144,6 +143,5 @@ if __name__ == "__main__": except: print >> sys.stderr, "Module relational_readline is missing.\nPlease install relational-cli package." sys.exit(3) - relational_readline.linegui.version=version + relational_readline.linegui.version = version relational_readline.linegui.main(files) - diff --git a/relational_gui/about.py b/relational_gui/about.py index 571bf47..2a039c0 100644 --- a/relational_gui/about.py +++ b/relational_gui/about.py @@ -1,52 +1,54 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli import os try: from PyQt4 import QtCore, QtGui - try: #If QtWebKit is available, uses it + try: # If QtWebKit is available, uses it from PyQt4 import QtWebKit - webk=True + webk = True except: - webk=False + webk = False except: from PySide import QtCore, QtGui - try: #If QtWebKit is available, uses it + try: # If QtWebKit is available, uses it from PySide import QtWebKit - webk=True + webk = True except: - webk=False + webk = False + +version = 0 -version=0 class Ui_Dialog(object): + def setupUi(self, Dialog): Dialog.setObjectName("Dialog") - Dialog.resize(510,453) + Dialog.resize(510, 453) self.verticalLayout_2 = QtGui.QVBoxLayout(Dialog) self.verticalLayout_2.setObjectName("verticalLayout_2") self.tabWidget = QtGui.QTabWidget(Dialog) self.tabWidget.setObjectName("tabWidget") self.tab = QtGui.QWidget() - self.tab.setGeometry(QtCore.QRect(0,0,494,377)) + self.tab.setGeometry(QtCore.QRect(0, 0, 494, 377)) self.tab.setObjectName("tab") self.verticalLayout_3 = QtGui.QVBoxLayout(self.tab) self.verticalLayout_3.setObjectName("verticalLayout_3") @@ -80,43 +82,45 @@ class Ui_Dialog(object): self.label_4.setObjectName("label_4") self.verticalLayout_6.addWidget(self.label_4) self.verticalLayout_3.addWidget(self.groupBox_2) - self.tabWidget.addTab(self.tab,"") + self.tabWidget.addTab(self.tab, "") self.License = QtGui.QWidget() - self.License.setGeometry(QtCore.QRect(0,0,494,377)) + self.License.setGeometry(QtCore.QRect(0, 0, 494, 377)) self.License.setObjectName("License") self.verticalLayout = QtGui.QVBoxLayout(self.License) self.verticalLayout.setObjectName("verticalLayout") self.textEdit = QtGui.QTextEdit(self.License) self.textEdit.setObjectName("textEdit") self.verticalLayout.addWidget(self.textEdit) - self.tabWidget.addTab(self.License,"") + self.tabWidget.addTab(self.License, "") self.tab_2 = QtGui.QWidget() self.tab_2.setObjectName("tab_2") self.verticalLayout_7 = QtGui.QVBoxLayout(self.tab_2) self.verticalLayout_7.setObjectName("verticalLayout_7") if (webk): self.webView = QtWebKit.QWebView(self.tab_2) - self.webView.setUrl(QtCore.QUrl("http://galileo.dmi.unict.it/wiki/relational/doku.php")) + self.webView.setUrl( + QtCore.QUrl("https://github.com/ltworf/relational/wiki/Grammar-and-language")) self.webView.setObjectName("webView") self.verticalLayout_7.addWidget(self.webView) else: self.webLink = QtGui.QLabel(self.groupBox) self.webLink.setFont(font) self.webLink.setObjectName("lblLink") - self.webLink.setText(QtGui.QApplication.translate("Dialog", "Relational's website", None,)) + self.webLink.setText(QtGui.QApplication.translate( + "Dialog", "Relational's website", None,)) self.webLink.setOpenExternalLinks(True) self.webLink.setTextFormat(QtCore.Qt.AutoText) self.webLink.setTextInteractionFlags( - QtCore.Qt.LinksAccessibleByKeyboard | - QtCore.Qt.LinksAccessibleByMouse | - QtCore.Qt.TextBrowserInteraction | - QtCore.Qt.TextSelectableByKeyboard | + QtCore.Qt.LinksAccessibleByKeyboard | + QtCore.Qt.LinksAccessibleByMouse | + QtCore.Qt.TextBrowserInteraction | + QtCore.Qt.TextSelectableByKeyboard | QtCore.Qt.TextSelectableByMouse ) - + self.verticalLayout_7.addWidget(self.webLink) - - self.tabWidget.addTab(self.tab_2,"") + + self.tabWidget.addTab(self.tab_2, "") self.verticalLayout_2.addWidget(self.tabWidget) self.buttonBox = QtGui.QDialogButtonBox(Dialog) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) @@ -126,169 +130,185 @@ class Ui_Dialog(object): self.retranslateUi(Dialog) self.tabWidget.setCurrentIndex(0) - QtCore.QObject.connect(self.buttonBox,QtCore.SIGNAL("accepted()"),Dialog.accept) - QtCore.QObject.connect(self.buttonBox,QtCore.SIGNAL("rejected()"),Dialog.reject) + QtCore.QObject.connect( + self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept) + QtCore.QObject.connect( + self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject) QtCore.QMetaObject.connectSlotsByName(Dialog) - def retranslateUi(self, Dialog): - Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Documentation", None, QtGui.QApplication.UnicodeUTF8)) - self.groupBox.setTitle(QtGui.QApplication.translate("Dialog", "Relational", None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("Dialog", "Relational", None, QtGui.QApplication.UnicodeUTF8)) - self.label_3.setText(QtGui.QApplication.translate("Dialog", "Version "+version, None, QtGui.QApplication.UnicodeUTF8)) - self.label_3.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextSelectableByMouse) - self.groupBox_3.setTitle(QtGui.QApplication.translate("Dialog", "Author", None, QtGui.QApplication.UnicodeUTF8)) - self.label_2.setText(QtGui.QApplication.translate("Dialog", "Salvo \"LtWorf\" Tomaselli <tiposchi@tiscali.it>
Emilio Di Prima <emiliodiprima[at]msn[dot]com> (For the windows setup)", None, QtGui.QApplication.UnicodeUTF8)) - self.label_2.setOpenExternalLinks (True) - self.label_2.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextSelectableByMouse) - self.groupBox_2.setTitle(QtGui.QApplication.translate("Dialog", "Links", None, QtGui.QApplication.UnicodeUTF8)) - self.label_4.setText(QtGui.QApplication.translate("Dialog", "http://galileo.dmi.unict.it/wiki/relational/", None, QtGui.QApplication.UnicodeUTF8)) - self.label_4.setOpenExternalLinks (True) - self.label_4.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextSelectableByMouse) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("Dialog", "About", None, QtGui.QApplication.UnicodeUTF8)) - self.textEdit.setHtml(QtGui.QApplication.translate("Dialog", "\n" -"GNU General Public License - GNU Project - Free Software Foundation (FSF)\n" -"

GNU GENERAL PUBLIC LICENSE

\n" -"

Version 3, 29 June 2007

\n" -"

Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>

\n" -"

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

\n" -"

Preamble

\n" -"

The GNU General Public License is a free, copyleft license for software and other kinds of works.

\n" -"

The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.

\n" -"

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.

\n" -"

To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.

\n" -"

For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

\n" -"

Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

\n" -"

For the developers\' and authors\' protection, the GPL clearly explains that there is no warranty for this free software. For both users\' and authors\' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.

\n" -"

Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users\' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.

\n" -"

Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.

\n" -"

The precise terms and conditions for copying, distribution and modification follow.

\n" -"

TERMS AND CONDITIONS

\n" -"

0. Definitions.

\n" -"

“This License” refers to version 3 of the GNU General Public License.

\n" -"

“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.

\n" -"

“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.

\n" -"

To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.

\n" -"

A “covered work” means either the unmodified Program or a work based on the Program.

\n" -"

To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.

\n" -"

To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.

\n" -"

An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.

\n" -"

1. Source Code.

\n" -"

The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.

\n" -"

A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.

\n" -"

The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.

\n" -"

The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work\'s System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.

\n" -"

The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.

\n" -"

The Corresponding Source for a work in source code form is that same work.

\n" -"

2. Basic Permissions.

\n" -"

All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.

\n" -"

You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.

\n" -"

Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

\n" -"

3. Protecting Users\' Legal Rights From Anti-Circumvention Law.

\n" -"

No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.

\n" -"

When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work\'s users, your or third parties\' legal rights to forbid circumvention of technological measures.

\n" -"

4. Conveying Verbatim Copies.

\n" -"

You may convey verbatim copies of the Program\'s source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.

\n" -"

You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.

\n" -"

5. Conveying Modified Source Versions.

\n" -"

You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

\n" -"
  • a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
  • \n" -"
  • b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
  • \n" -"
  • c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
  • \n" -"
  • d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
\n" -"

A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation\'s users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.

\n" -"

6. Conveying Non-Source Forms.

\n" -"

You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:

\n" -"
  • a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
  • \n" -"
  • b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
  • \n" -"
  • c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
  • \n" -"
  • d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
  • \n" -"
  • e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
\n" -"

A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.

\n" -"

A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.

\n" -"

“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.

\n" -"

If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).

\n" -"

The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.

\n" -"

Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.

\n" -"

7. Additional Terms.

\n" -"

“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.

\n" -"

When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.

\n" -"

Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:

\n" -"
  • a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
  • \n" -"
  • b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
  • \n" -"
  • c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
  • \n" -"
  • d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
  • \n" -"
  • e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
  • \n" -"
  • f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
\n" -"

All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.

\n" -"

If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.

\n" -"

Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.

\n" -"

8. Termination.

\n" -"

You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

\n" -"

However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

\n" -"

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

\n" -"

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.

\n" -"

9. Acceptance Not Required for Having Copies.

\n" -"

You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.

\n" -"

10. Automatic Licensing of Downstream Recipients.

\n" -"

Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.

\n" -"

An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party\'s predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.

\n" -"

You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.

\n" -"

11. Patents.

\n" -"

A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor\'s “contributor version”.

\n" -"

A contributor\'s “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.

\n" -"

Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor\'s essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.

\n" -"

In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.

\n" -"

If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient\'s use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.

\n" -"

If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.

\n" -"

A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.

\n" -"

Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.

\n" -"

12. No Surrender of Others\' Freedom.

\n" -"

If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.

\n" -"

13. Use with the GNU Affero General Public License.

\n" -"

Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.

\n" -"

14. Revised Versions of this License.

\n" -"

The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

\n" -"

Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.

\n" -"

If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy\'s public statement of acceptance of a version permanently authorizes you to choose that version for the Program.

\n" -"

Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.

\n" -"

15. Disclaimer of Warranty.

\n" -"

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

\n" -"

16. Limitation of Liability.

\n" -"

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

\n" -"

17. Interpretation of Sections 15 and 16.

\n" -"

If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

\n" -"

END OF TERMS AND CONDITIONS

\n" -"

How to Apply These Terms to Your New Programs

\n" -"

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

\n" -"

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.

\n" -"
    <one line to give the program\'s name and a brief idea of what it does.>
\n" -"
    Copyright (C) <year>  <name of author>
\n" -"
\n"
-"
    This program is free software: you can redistribute it and/or modify
\n" -"
    it under the terms of the GNU General Public License as published by
\n" -"
    the Free Software Foundation, either version 3 of the License, or
\n" -"
    (at your option) any later version.
\n" -"
\n"
-"
    This program is distributed in the hope that it will be useful,
\n" -"
    but WITHOUT ANY WARRANTY; without even the implied warranty of
\n" -"
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
\n" -"
    GNU General Public License for more details.
\n" -"
\n"
-"
    You should have received a copy of the GNU General Public License
\n" -"
    along with this program.  If not, see <http://www.gnu.org/licenses/>. 
\n" -"

Also add information on how to contact you by electronic and paper mail.

\n" -"

If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:

\n" -"
    <program>  Copyright (C) <year>  <name of author>
\n" -"
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.
\n" -"
    This is free software, and you are welcome to redistribute it
\n" -"
    under certain conditions; type `show c\' for details. 
\n" -"

The hypothetical commands `show w\' and `show c\' should show the appropriate parts of the General Public License. Of course, your program\'s commands might be different; for a GUI interface, you would use an “about box”.

\n" -"

You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.

\n" -"

The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

", None, QtGui.QApplication.UnicodeUTF8)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.License), QtGui.QApplication.translate("Dialog", "License", None, QtGui.QApplication.UnicodeUTF8)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate("Dialog", "Docs", None, QtGui.QApplication.UnicodeUTF8)) + def retranslateUi(self, Dialog): + Dialog.setWindowTitle(QtGui.QApplication.translate( + "Dialog", "Documentation", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox.setTitle(QtGui.QApplication.translate( + "Dialog", "Relational", None, QtGui.QApplication.UnicodeUTF8)) + self.label.setText(QtGui.QApplication.translate( + "Dialog", "Relational", None, QtGui.QApplication.UnicodeUTF8)) + self.label_3.setText(QtGui.QApplication.translate( + "Dialog", "Version " + version, None, QtGui.QApplication.UnicodeUTF8)) + self.label_3.setTextInteractionFlags( + QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextSelectableByMouse) + self.groupBox_3.setTitle(QtGui.QApplication.translate( + "Dialog", "Author", None, QtGui.QApplication.UnicodeUTF8)) + self.label_2.setText(QtGui.QApplication.translate( + "Dialog", "Salvo \"LtWorf\" Tomaselli <tiposchi@tiscali.it>
Emilio Di Prima <emiliodiprima[at]msn[dot]com> (For the windows setup)", None, QtGui.QApplication.UnicodeUTF8)) + self.label_2.setOpenExternalLinks(True) + self.label_2.setTextInteractionFlags( + QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextSelectableByMouse) + self.groupBox_2.setTitle(QtGui.QApplication.translate( + "Dialog", "Links", None, QtGui.QApplication.UnicodeUTF8)) + self.label_4.setText(QtGui.QApplication.translate( + "Dialog", "https://github.com/ltworf/relational/", None, QtGui.QApplication.UnicodeUTF8)) + self.label_4.setOpenExternalLinks(True) + self.label_4.setTextInteractionFlags( + QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextSelectableByMouse) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate( + "Dialog", "About", None, QtGui.QApplication.UnicodeUTF8)) + self.textEdit.setHtml(QtGui.QApplication.translate("Dialog", "\n" + "GNU General Public License - GNU Project - Free Software Foundation (FSF)\n" + "

GNU GENERAL PUBLIC LICENSE

\n" + "

Version 3, 29 June 2007

\n" + "

Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>

\n" + "

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

\n" + "

Preamble

\n" + "

The GNU General Public License is a free, copyleft license for software and other kinds of works.

\n" + "

The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.

\n" + "

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.

\n" + "

To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.

\n" + "

For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

\n" + "

Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

\n" + "

For the developers\' and authors\' protection, the GPL clearly explains that there is no warranty for this free software. For both users\' and authors\' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.

\n" + "

Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users\' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.

\n" + "

Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.

\n" + "

The precise terms and conditions for copying, distribution and modification follow.

\n" + "

TERMS AND CONDITIONS

\n" + "

0. Definitions.

\n" + "

“This License” refers to version 3 of the GNU General Public License.

\n" + "

“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.

\n" + "

“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.

\n" + "

To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.

\n" + "

A “covered work” means either the unmodified Program or a work based on the Program.

\n" + "

To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.

\n" + "

To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.

\n" + "

An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.

\n" + "

1. Source Code.

\n" + "

The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.

\n" + "

A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.

\n" + "

The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.

\n" + "

The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work\'s System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.

\n" + "

The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.

\n" + "

The Corresponding Source for a work in source code form is that same work.

\n" + "

2. Basic Permissions.

\n" + "

All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.

\n" + "

You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.

\n" + "

Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

\n" + "

3. Protecting Users\' Legal Rights From Anti-Circumvention Law.

\n" + "

No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.

\n" + "

When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work\'s users, your or third parties\' legal rights to forbid circumvention of technological measures.

\n" + "

4. Conveying Verbatim Copies.

\n" + "

You may convey verbatim copies of the Program\'s source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.

\n" + "

You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.

\n" + "

5. Conveying Modified Source Versions.

\n" + "

You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

\n" + "
  • a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
  • \n" + "
  • b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
  • \n" + "
  • c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
  • \n" + "
  • d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
\n" + "

A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation\'s users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.

\n" + "

6. Conveying Non-Source Forms.

\n" + "

You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:

\n" + "
  • a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
  • \n" + "
  • b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
  • \n" + "
  • c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
  • \n" + "
  • d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
  • \n" + "
  • e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
\n" + "

A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.

\n" + "

A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.

\n" + "

“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.

\n" + "

If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).

\n" + "

The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.

\n" + "

Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.

\n" + "

7. Additional Terms.

\n" + "

“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.

\n" + "

When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.

\n" + "

Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:

\n" + "
  • a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
  • \n" + "
  • b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
  • \n" + "
  • c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
  • \n" + "
  • d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
  • \n" + "
  • e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
  • \n" + "
  • f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
\n" + "

All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.

\n" + "

If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.

\n" + "

Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.

\n" + "

8. Termination.

\n" + "

You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

\n" + "

However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

\n" + "

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

\n" + "

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.

\n" + "

9. Acceptance Not Required for Having Copies.

\n" + "

You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.

\n" + "

10. Automatic Licensing of Downstream Recipients.

\n" + "

Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.

\n" + "

An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party\'s predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.

\n" + "

You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.

\n" + "

11. Patents.

\n" + "

A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor\'s “contributor version”.

\n" + "

A contributor\'s “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.

\n" + "

Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor\'s essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.

\n" + "

In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.

\n" + "

If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient\'s use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.

\n" + "

If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.

\n" + "

A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.

\n" + "

Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.

\n" + "

12. No Surrender of Others\' Freedom.

\n" + "

If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.

\n" + "

13. Use with the GNU Affero General Public License.

\n" + "

Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.

\n" + "

14. Revised Versions of this License.

\n" + "

The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

\n" + "

Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.

\n" + "

If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy\'s public statement of acceptance of a version permanently authorizes you to choose that version for the Program.

\n" + "

Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.

\n" + "

15. Disclaimer of Warranty.

\n" + "

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

\n" + "

16. Limitation of Liability.

\n" + "

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

\n" + "

17. Interpretation of Sections 15 and 16.

\n" + "

If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

\n" + "

END OF TERMS AND CONDITIONS

\n" + "

How to Apply These Terms to Your New Programs

\n" + "

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

\n" + "

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.

\n" + "
    <one line to give the program\'s name and a brief idea of what it does.>
\n" + "
    Copyright (C) <year>  <name of author>
\n" + "
\n"
+                                                           "
    This program is free software: you can redistribute it and/or modify
\n" + "
    it under the terms of the GNU General Public License as published by
\n" + "
    the Free Software Foundation, either version 3 of the License, or
\n" + "
    (at your option) any later version.
\n" + "
\n"
+                                                           "
    This program is distributed in the hope that it will be useful,
\n" + "
    but WITHOUT ANY WARRANTY; without even the implied warranty of
\n" + "
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
\n" + "
    GNU General Public License for more details.
\n" + "
\n"
+                                                           "
    You should have received a copy of the GNU General Public License
\n" + "
    along with this program.  If not, see <http://www.gnu.org/licenses/>. 
\n" + "

Also add information on how to contact you by electronic and paper mail.

\n" + "

If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:

\n" + "
    <program>  Copyright (C) <year>  <name of author>
\n" + "
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.
\n" + "
    This is free software, and you are welcome to redistribute it
\n" + "
    under certain conditions; type `show c\' for details. 
\n" + "

The hypothetical commands `show w\' and `show c\' should show the appropriate parts of the General Public License. Of course, your program\'s commands might be different; for a GUI interface, you would use an “about box”.

\n" + "

You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.

\n" + "

The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

", None, QtGui.QApplication.UnicodeUTF8)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.License), QtGui.QApplication.translate( + "Dialog", "License", None, QtGui.QApplication.UnicodeUTF8)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate( + "Dialog", "Docs", None, QtGui.QApplication.UnicodeUTF8)) if __name__ == "__main__": @@ -299,4 +319,3 @@ if __name__ == "__main__": ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_()) - diff --git a/relational_gui/compatibility.py b/relational_gui/compatibility.py index 6019e6b..858613b 100644 --- a/relational_gui/compatibility.py +++ b/relational_gui/compatibility.py @@ -1,20 +1,20 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2011 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli # # Module to unify the use of both pyqt and pyside @@ -22,37 +22,42 @@ try: from PyQt4 import QtCore, QtGui - pyqt=True + pyqt = True except: from PySide import QtCore, QtGui - pyqt=False + pyqt = False def get_py_str(a): '''Returns a python string out of a QString''' if pyqt: - return unicode(a.toUtf8(),'utf-8') - return a #Already a python string in PySide + return unicode(a.toUtf8(), 'utf-8') + return a # Already a python string in PySide -def set_utf8_text(component,text): + +def set_utf8_text(component, text): if not pyqt: component.setText(text) else: component.setText(QtCore.QString.fromUtf8(text)) + + def get_filename(filename): if pyqt: return str(filename.toUtf8()) return filename[0] -def add_list_item(l,item): + + +def add_list_item(l, item): if pyqt: - history_item=QtCore.QString() + history_item = QtCore.QString() history_item.append(item) - hitem=QtGui.QListWidgetItem(None,0) + hitem = QtGui.QListWidgetItem(None, 0) hitem.setText(history_item) - l.addItem (hitem) + l.addItem(hitem) l.setCurrentItem(hitem) else: - hitem=QtGui.QListWidgetItem(None,0) + hitem = QtGui.QListWidgetItem(None, 0) hitem.setText(item) - l.addItem (hitem) - l.setCurrentItem(hitem) \ No newline at end of file + l.addItem(hitem) + l.setCurrentItem(hitem) diff --git a/relational_gui/creator.py b/relational_gui/creator.py index a32a378..401e872 100644 --- a/relational_gui/creator.py +++ b/relational_gui/creator.py @@ -1,20 +1,20 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli try: @@ -28,105 +28,119 @@ import rel_edit class creatorForm(QtGui.QDialog): - def __init__(self,rel=None): + + def __init__(self, rel=None): QtGui.QDialog.__init__(self) - + self.setSizeGripEnabled(True) - self.result_relation=None - self.rel=rel - def setUi(self,ui): - self.ui=ui - self.table=self.ui.table - - if self.rel==None: + self.result_relation = None + self.rel = rel + + def setUi(self, ui): + self.ui = ui + self.table = self.ui.table + + if self.rel == None: self.setup_empty() else: self.setup_relation(self.rel) - def setup_relation(self,rel): - + + def setup_relation(self, rel): + self.table.insertRow(0) - + for i in rel.header.attributes: - item=QtGui.QTableWidgetItem() + item = QtGui.QTableWidgetItem() item.setText(i) self.table.insertColumn(self.table.columnCount()) - self.table.setItem(0,self.table.columnCount()-1,item) - + self.table.setItem(0, self.table.columnCount() - 1, item) + for i in rel.content: self.table.insertRow(self.table.rowCount()) for j in range(len(i)): - item=QtGui.QTableWidgetItem() + item = QtGui.QTableWidgetItem() item.setText(i[j]) - self.table.setItem(self.table.rowCount()-1,j,item) - + self.table.setItem(self.table.rowCount() - 1, j, item) + pass + def setup_empty(self): self.table.insertColumn(0) self.table.insertColumn(0) self.table.insertRow(0) self.table.insertRow(0) - - i00=QtGui.QTableWidgetItem() - i01=QtGui.QTableWidgetItem() - i10=QtGui.QTableWidgetItem() - i11=QtGui.QTableWidgetItem() + + i00 = QtGui.QTableWidgetItem() + i01 = QtGui.QTableWidgetItem() + i10 = QtGui.QTableWidgetItem() + i11 = QtGui.QTableWidgetItem() i00.setText('Field name 1') i01.setText('Field name 2') i10.setText('Value 1') i11.setText('Value 2') - - self.table.setItem (0,0,i00) - self.table.setItem (0,1,i01) - self.table.setItem (1,0,i10) - self.table.setItem (1,1,i11) + + self.table.setItem(0, 0, i00) + self.table.setItem(0, 1, i01) + self.table.setItem(1, 0, i10) + self.table.setItem(1, 1, i11) + def create_relation(self): - hlist=[] - + hlist = [] + for i in range(self.table.columnCount()): - hlist.append(compatibility.get_py_str(self.table.item(0,i).text())) + hlist.append( + compatibility.get_py_str(self.table.item(0, i).text())) try: - header=relation.header(hlist) + header = relation.header(hlist) except Exception, e: - QtGui.QMessageBox.information(None,QtGui.QApplication.translate("Form", "Error"),"%s\n%s" % (QtGui.QApplication.translate("Form", "Header error!"),e.__str__()) ) + QtGui.QMessageBox.information(None, QtGui.QApplication.translate("Form", "Error"), "%s\n%s" % ( + QtGui.QApplication.translate("Form", "Header error!"), e.__str__())) return None - r=relation.relation() - r.header=header - - for i in range(1,self.table.rowCount()): - hlist=[] + r = relation.relation() + r.header = header + + for i in range(1, self.table.rowCount()): + hlist = [] for j in range(self.table.columnCount()): try: - hlist.append(compatibility.get_py_str(self.table.item(i,j).text())) + hlist.append( + compatibility.get_py_str(self.table.item(i, j).text())) except: - QtGui.QMessageBox.information(None,QtGui.QApplication.translate("Form", "Error"),QtGui.QApplication.translate("Form", "Unset value in %d,%d!"% (i+1,j+1)) ) + QtGui.QMessageBox.information(None, QtGui.QApplication.translate( + "Form", "Error"), QtGui.QApplication.translate("Form", "Unset value in %d,%d!" % (i + 1, j + 1))) return None r.content.add(tuple(hlist)) return r - + def accept(self): - - self.result_relation=self.create_relation() - - #Doesn't close the window in case of errors - if self.result_relation!=None: + + self.result_relation = self.create_relation() + + # Doesn't close the window in case of errors + if self.result_relation != None: QtGui.QDialog.accept(self) pass + def reject(self): - self.result_relation=None + self.result_relation = None QtGui.QDialog.reject(self) pass + def addColumn(self): self.table.insertColumn(self.table.columnCount()) pass + def addRow(self): self.table.insertRow(1) pass + def deleteColumn(self): - if self.table.columnCount()>1: + if self.table.columnCount() > 1: self.table.removeColumn(self.table.currentColumn()) pass + def deleteRow(self): - if self.table.rowCount()>2: + if self.table.rowCount() > 2: self.table.removeRow(self.table.currentRow()) pass @@ -135,19 +149,20 @@ def edit_relation(rel=None): '''Opens the editor for the given relation and returns a _new_ relation containing the new relation. If the user cancels, it returns None''' - + ui = rel_edit.Ui_Dialog() Form = creatorForm(rel) ui.setupUi(Form) Form.setUi(ui) - + Form.exec_() return Form.result_relation - + if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) - r=relation.relation("/home/salvo/dev/relational/trunk/samples/people.csv") + r = relation.relation( + "/home/salvo/dev/relational/trunk/samples/people.csv") print edit_relation(r) diff --git a/relational_gui/guihandler.py b/relational_gui/guihandler.py index 125a801..6192ece 100644 --- a/relational_gui/guihandler.py +++ b/relational_gui/guihandler.py @@ -26,8 +26,7 @@ except: from PySide import QtCore, QtGui - -from relational import relation, parser, optimizer,rtypes +from relational import relation, parser, optimizer, rtypes import about import survey @@ -38,277 +37,315 @@ import compatibility class relForm(QtGui.QMainWindow): - def __init__(self,ui): + def __init__(self, ui): QtGui.QMainWindow.__init__(self) - self.About=None - self.Survey=None - self.relations={} #Dictionary for relations - self.undo=None #UndoQueue for queries - self.selectedRelation=None - self.ui=ui - self.qcounter=1 #Query counter + self.About = None + self.Survey = None + self.relations = {} # Dictionary for relations + self.undo = None # UndoQueue for queries + self.selectedRelation = None + self.ui = ui + self.qcounter = 1 # Query counter self.settings = QtCore.QSettings() def checkVersion(self): from relational import maintenance - online=maintenance.check_latest_version() + online = maintenance.check_latest_version() - if online>version: - r=QtGui.QApplication.translate("Form", "New version available online: %s." % online) - elif online==version: - r=QtGui.QApplication.translate("Form", "Latest version installed.") + if online > version: + r = QtGui.QApplication.translate( + "Form", "New version available online: %s." % online) + elif online == version: + r = QtGui.QApplication.translate( + "Form", "Latest version installed.") else: - r=QtGui.QApplication.translate("Form", "You are using an unstable version.") + r = QtGui.QApplication.translate( + "Form", "You are using an unstable version.") - QtGui.QMessageBox.information(self,QtGui.QApplication.translate("Form", "Version"),r) + QtGui.QMessageBox.information( + self, QtGui.QApplication.translate("Form", "Version"), r) - - def load_query(self,*index): + def load_query(self, *index): self.ui.txtQuery.setText(self.savedQ.itemData(index[0]).toString()) def undoOptimize(self): '''Undoes the optimization on the query, popping one item from the undo list''' - if self.undo!=None: + if self.undo != None: self.ui.txtQuery.setText(self.undo) def optimize(self): '''Performs all the possible optimizations on the query''' - self.undo=self.ui.txtQuery.text() #Storing the query in undo list + self.undo = self.ui.txtQuery.text() # Storing the query in undo list - query=compatibility.get_py_str(self.ui.txtQuery.text()) + query = compatibility.get_py_str(self.ui.txtQuery.text()) try: - result=optimizer.optimize_all(query,self.relations) - compatibility.set_utf8_text(self.ui.txtQuery,result) + result = optimizer.optimize_all(query, self.relations) + compatibility.set_utf8_text(self.ui.txtQuery, result) except Exception, e: - QtGui.QMessageBox.information(None,QtGui.QApplication.translate("Form", "Error"),"%s\n%s" % (QtGui.QApplication.translate("Form", "Check your query!"),e.__str__()) ) + QtGui.QMessageBox.information(None, QtGui.QApplication.translate("Form", "Error"), "%s\n%s" % + (QtGui.QApplication.translate("Form", "Check your query!"), e.__str__())) - - - def resumeHistory(self,item): - itm=compatibility.get_py_str(item.text()).split(' = ',1) - compatibility.set_utf8_text(self.ui.txtResult,itm[0]) - compatibility.set_utf8_text(self.ui.txtQuery,itm[1]) + def resumeHistory(self, item): + itm = compatibility.get_py_str(item.text()).split(' = ', 1) + compatibility.set_utf8_text(self.ui.txtResult, itm[0]) + compatibility.set_utf8_text(self.ui.txtQuery, itm[1]) def execute(self): '''Executes the query''' - query=compatibility.get_py_str(self.ui.txtQuery.text()) - res_rel=compatibility.get_py_str(self.ui.txtResult.text())#result relation's name + query = compatibility.get_py_str(self.ui.txtQuery.text()) + res_rel = compatibility.get_py_str( + self.ui.txtResult.text()) # result relation's name if not rtypes.is_valid_relation_name(res_rel): - QtGui.QMessageBox.information(self,QtGui.QApplication.translate("Form", "Error"),QtGui.QApplication.translate("Form", "Wrong name for destination relation.")) + QtGui.QMessageBox.information(self, QtGui.QApplication.translate( + "Form", "Error"), QtGui.QApplication.translate("Form", "Wrong name for destination relation.")) return try: - #Converting string to utf8 and then from qstring to normal string - expr=parser.parse(query)#Converting expression to python code - print query,"-->" , expr #Printing debug - result=eval(expr,self.relations) #Evaluating the expression + # Converting string to utf8 and then from qstring to normal string + expr = parser.parse(query) # Converting expression to python code + print query, "-->", expr # Printing debug + result = eval(expr, self.relations) # Evaluating the expression - self.relations[res_rel]=result #Add the relation to the dictionary - self.updateRelations() #update the list - self.selectedRelation=result - self.showRelation(self.selectedRelation) #Show the result in the table + self.relations[ + res_rel] = result # Add the relation to the dictionary + self.updateRelations() # update the list + self.selectedRelation = result + self.showRelation(self.selectedRelation) + # Show the result in the table except Exception, e: print e.__unicode__() - QtGui.QMessageBox.information(None,QtGui.QApplication.translate("Form", "Error"),u"%s\n%s" % (QtGui.QApplication.translate("Form", "Check your query!"),e.__unicode__()) ) + QtGui.QMessageBox.information(None, QtGui.QApplication.translate("Form", "Error"), u"%s\n%s" % + (QtGui.QApplication.translate("Form", "Check your query!"), e.__unicode__())) return - #Adds to history - item=u'%s = %s' % (compatibility.get_py_str(self.ui.txtResult.text()),compatibility.get_py_str(self.ui.txtQuery.text())) - #item=item.decode('utf-8')) - compatibility.add_list_item(self.ui.lstHistory,item) + # Adds to history + item = u'%s = %s' % (compatibility.get_py_str( + self.ui.txtResult.text()), compatibility.get_py_str(self.ui.txtQuery.text())) + # item=item.decode('utf-8')) + compatibility.add_list_item(self.ui.lstHistory, item) - self.qcounter+=1 - compatibility.set_utf8_text(self.ui.txtResult,u"_last%d"% self.qcounter) #Sets the result relation name to none + self.qcounter += 1 + compatibility.set_utf8_text(self.ui.txtResult, u"_last%d" % + self.qcounter) # Sets the result relation name to none - def showRelation(self,rel): + def showRelation(self, rel): '''Shows the selected relation into the table''' self.ui.table.clear() - if rel==None: #No relation to show + if rel == None: # No relation to show self.ui.table.setColumnCount(1) - self.ui.table.headerItem().setText(0,"Empty relation") + self.ui.table.headerItem().setText(0, "Empty relation") return self.ui.table.setColumnCount(len(rel.header.attributes)) - #Set content + # Set content for i in rel.content: item = QtGui.QTreeWidgetItem() for j in range(len(i)): item.setText(j, i[j]) self.ui.table.addTopLevelItem(item) - #Sets columns + # Sets columns for i in range(len(rel.header.attributes)): - self.ui.table.headerItem().setText(i,rel.header.attributes[i]) - self.ui.table.resizeColumnToContents(i) #Must be done in order to avoid too small columns + self.ui.table.headerItem().setText(i, rel.header.attributes[i]) + self.ui.table.resizeColumnToContents( + i) # Must be done in order to avoid too small columns - - def printRelation(self,item): - self.selectedRelation=self.relations[compatibility.get_py_str(item.text())] + def printRelation(self, item): + self.selectedRelation = self.relations[ + compatibility.get_py_str(item.text())] self.showRelation(self.selectedRelation) - def showAttributes(self,item): + def showAttributes(self, item): '''Shows the attributes of the selected relation''' - rel=compatibility.get_py_str(item.text()) + rel = compatibility.get_py_str(item.text()) self.ui.lstAttributes.clear() for j in self.relations[rel].header.attributes: - self.ui.lstAttributes.addItem (j) + self.ui.lstAttributes.addItem(j) def updateRelations(self): self.ui.lstRelations.clear() for i in self.relations: if i != "__builtins__": self.ui.lstRelations.addItem(i) - def saveRelation(self): - filename = QtGui.QFileDialog.getSaveFileName(self,QtGui.QApplication.translate("Form", "Save Relation"),"",QtGui.QApplication.translate("Form", "Relations (*.csv)")) - filename=compatibility.get_filename(filename) - if (len(filename)==0):#Returns if no file was selected + def saveRelation(self): + filename = QtGui.QFileDialog.getSaveFileName(self, QtGui.QApplication.translate( + "Form", "Save Relation"), "", QtGui.QApplication.translate("Form", "Relations (*.csv)")) + + filename = compatibility.get_filename(filename) + if (len(filename) == 0): # Returns if no file was selected return self.selectedRelation.save(filename) return + def unloadRelation(self): for i in self.ui.lstRelations.selectedItems(): del self.relations[compatibility.get_py_str(i.text())] self.updateRelations() + def editRelation(self): import creator for i in self.ui.lstRelations.selectedItems(): - result=creator.edit_relation(self.relations[compatibility.get_py_str(i.text())]) - if result!=None: - self.relations[compatibility.get_py_str(i.text())]=result + result = creator.edit_relation( + self.relations[compatibility.get_py_str(i.text())]) + if result != None: + self.relations[compatibility.get_py_str(i.text())] = result self.updateRelations() + def newRelation(self): import creator - result=creator.edit_relation() + result = creator.edit_relation() - if result==None: + if result == None: return - res=QtGui.QInputDialog.getText( - self, - QtGui.QApplication.translate("Form", "New relation"), - QtGui.QApplication.translate("Form", "Insert the name for the new relation"), - QtGui.QLineEdit.Normal,'') - if res[1]==False or len(res[0])==0: + res = QtGui.QInputDialog.getText( + self, + QtGui.QApplication.translate("Form", "New relation"), + QtGui.QApplication.translate( + "Form", "Insert the name for the new relation"), + QtGui.QLineEdit.Normal, '') + if res[1] == False or len(res[0]) == 0: return - #Patch provided by Angelo 'Havoc' Puglisi - name=compatibility.get_py_str(res[0]) + # Patch provided by Angelo 'Havoc' Puglisi + name = compatibility.get_py_str(res[0]) if not rtypes.is_valid_relation_name(name): - r=QtGui.QApplication.translate("Form", str("Wrong name for destination relation: %s." % name)) - QtGui.QMessageBox.information(self,QtGui.QApplication.translate("Form", "Error"),r) + r = QtGui.QApplication.translate( + "Form", str("Wrong name for destination relation: %s." % name)) + QtGui.QMessageBox.information( + self, QtGui.QApplication.translate("Form", "Error"), r) return try: - self.relations[name]=result + self.relations[name] = result except Exception, e: print e - QtGui.QMessageBox.information(None,QtGui.QApplication.translate("Form", "Error"),"%s\n%s" % (QtGui.QApplication.translate("Form", "Check your query!"),e.__str__()) ) + QtGui.QMessageBox.information(None, QtGui.QApplication.translate("Form", "Error"), "%s\n%s" % + (QtGui.QApplication.translate("Form", "Check your query!"), e.__str__())) return - self.updateRelations() + def closeEvent(self, event): self.save_settings() event.accept() + def save_settings(self): - #self.settings.setValue("width",) + # self.settings.setValue("width",) pass def restore_settings(self): - #self.settings.value('session_name','default').toString() + # self.settings.value('session_name','default').toString() pass def showSurvey(self): - if self.Survey==None: - self.Survey=surveyForm.surveyForm() - ui = survey.Ui_Form() - self.Survey.setUi(ui) - ui.setupUi(self.Survey) - self.Survey.setDefaultValues() - self.Survey.show() + if self.Survey == None: + self.Survey = surveyForm.surveyForm() + ui = survey.Ui_Form() + self.Survey.setUi(ui) + ui.setupUi(self.Survey) + self.Survey.setDefaultValues() + self.Survey.show() def showAbout(self): - if self.About==None: + if self.About == None: self.About = QtGui.QDialog() ui = about.Ui_Dialog() ui.setupUi(self.About) self.About.show() - def loadRelation(self,filename=None,name=None): + def loadRelation(self, filename=None, name=None): '''Loads a relation. Without parameters it will ask the user which relation to load, otherwise it will load filename, giving it name. It shouldn't be called giving filename but not giving name.''' - #Asking for file to load - if filename==None: - filename = QtGui.QFileDialog.getOpenFileName(self,QtGui.QApplication.translate("Form", "Load Relation"),"",QtGui.QApplication.translate("Form", "Relations (*.csv);;Text Files (*.txt);;All Files (*)")) - filename=compatibility.get_filename(filename) + # Asking for file to load + if filename == None: + filename = QtGui.QFileDialog.getOpenFileName(self, QtGui.QApplication.translate( + "Form", "Load Relation"), "", QtGui.QApplication.translate("Form", "Relations (*.csv);;Text Files (*.txt);;All Files (*)")) + filename = compatibility.get_filename(filename) - #Default relation's name - f=filename.split('/') #Split the full path - defname=f[len(f)-1].lower() #Takes only the lowercase filename + # Default relation's name + f = filename.split('/') # Split the full path + defname = f[len(f) - 1].lower() # Takes only the lowercase filename - if len(defname)==0: + if len(defname) == 0: return - if (defname.endswith(".csv")): #removes the extension - defname=defname[:-4] + if (defname.endswith(".csv")): # removes the extension + defname = defname[:-4] - if name==None: #Prompt dialog to insert name for the relation - res=QtGui.QInputDialog.getText(self, QtGui.QApplication.translate("Form", "New relation"),QtGui.QApplication.translate("Form", "Insert the name for the new relation"), - QtGui.QLineEdit.Normal,defname) - if res[1]==False or len(res[0])==0: + if name == None: # Prompt dialog to insert name for the relation + res = QtGui.QInputDialog.getText( + self, QtGui.QApplication.translate("Form", "New relation"), QtGui.QApplication.translate( + "Form", "Insert the name for the new relation"), + QtGui.QLineEdit.Normal, defname) + if res[1] == False or len(res[0]) == 0: return - #Patch provided by Angelo 'Havoc' Puglisi - name=compatibility.get_py_str(res[0]) + # Patch provided by Angelo 'Havoc' Puglisi + name = compatibility.get_py_str(res[0]) if not rtypes.is_valid_relation_name(name): - r=QtGui.QApplication.translate("Form", str("Wrong name for destination relation: %s." % name)) - QtGui.QMessageBox.information(self,QtGui.QApplication.translate("Form", "Error"),r) + r = QtGui.QApplication.translate( + "Form", str("Wrong name for destination relation: %s." % name)) + QtGui.QMessageBox.information( + self, QtGui.QApplication.translate("Form", "Error"), r) return try: - self.relations[name]=relation.relation(filename) + self.relations[name] = relation.relation(filename) except Exception, e: print e - QtGui.QMessageBox.information(None,QtGui.QApplication.translate("Form", "Error"),"%s\n%s" % (QtGui.QApplication.translate("Form", "Check your query!"),e.__str__()) ) + QtGui.QMessageBox.information(None, QtGui.QApplication.translate("Form", "Error"), "%s\n%s" % + (QtGui.QApplication.translate("Form", "Check your query!"), e.__str__())) return - self.updateRelations() def addProduct(self): self.addSymbolInQuery(u"*") + def addDifference(self): self.addSymbolInQuery(u"-") + def addUnion(self): self.addSymbolInQuery(u"ᑌ") + def addIntersection(self): self.addSymbolInQuery(u"ᑎ") + def addDivision(self): self.addSymbolInQuery(u"÷") + def addOLeft(self): self.addSymbolInQuery(u"ᐅLEFTᐊ") + def addJoin(self): self.addSymbolInQuery(u"ᐅᐊ") + def addORight(self): self.addSymbolInQuery(u"ᐅRIGHTᐊ") + def addOuter(self): self.addSymbolInQuery(u"ᐅFULLᐊ") + def addProjection(self): self.addSymbolInQuery(u"π") + def addSelection(self): self.addSymbolInQuery(u"σ") + def addRename(self): self.addSymbolInQuery(u"ρ") + def addArrow(self): self.addSymbolInQuery(u"➡") - def addSymbolInQuery(self,symbol): + def addSymbolInQuery(self, symbol): self.ui.txtQuery.insert(symbol) self.ui.txtQuery.setFocus() diff --git a/relational_gui/maingui.py b/relational_gui/maingui.py index 18dbf48..eb7913c 100644 --- a/relational_gui/maingui.py +++ b/relational_gui/maingui.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'relational_gui/maingui.ui' # -# Created: Fri Dec 27 00:05:54 2013 +# Created: Fri Dec 27 00:23:51 2013 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! diff --git a/relational_gui/rel_edit.py b/relational_gui/rel_edit.py index 94018df..30c0811 100644 --- a/relational_gui/rel_edit.py +++ b/relational_gui/rel_edit.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'relational_gui/rel_edit.ui' # -# Created: Fri Dec 27 00:05:54 2013 +# Created: Fri Dec 27 00:23:51 2013 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! diff --git a/relational_gui/survey.py b/relational_gui/survey.py index 4c7d515..3b4fa81 100644 --- a/relational_gui/survey.py +++ b/relational_gui/survey.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'relational_gui/survey.ui' # -# Created: Fri Dec 27 00:05:54 2013 +# Created: Fri Dec 27 00:23:51 2013 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! diff --git a/relational_gui/surveyForm.py b/relational_gui/surveyForm.py index 7a522e3..105a4e6 100644 --- a/relational_gui/surveyForm.py +++ b/relational_gui/surveyForm.py @@ -1,20 +1,20 @@ # -*- coding: utf-8 -*- # Relational # Copyright (C) 2008 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli try: from PyQt4 import QtCore, QtGui @@ -26,49 +26,56 @@ from relational import maintenance import platform import locale + class surveyForm (QtGui.QWidget): + '''This class is the form used for the survey, needed to intercept the events. It also sends the data with http POST to a page hosted on galileo''' - def setUi(self,ui): - self.ui=ui + + def setUi(self, ui): + self.ui = ui + def setDefaultValues(self): '''Sets default values into the form GUI. It has to be called after the form has been initialized''' - - #Dictionary with country codes - countries={'BD': 'BANGLADESH', 'BE': 'BELGIUM', 'BF': 'BURKINA FASO', 'BG': 'BULGARIA', 'BA': 'BOSNIA AND HERZEGOVINA', 'BB': 'BARBADOS', 'WF': 'WALLIS AND FUTUNA', 'BL': 'SAINT BARTH\xc3\x89LEMY', 'BM': 'BERMUDA', 'BN': 'BRUNEI DARUSSALAM', 'BO': 'BOLIVIA, PLURINATIONAL STATE OF', 'BH': 'BAHRAIN', 'BI': 'BURUNDI', 'BJ': 'BENIN', 'BT': 'BHUTAN', 'JM': 'JAMAICA', 'BV': 'BOUVET ISLAND', 'BW': 'BOTSWANA', 'WS': 'SAMOA', 'BR': 'BRAZIL', 'BS': 'BAHAMAS', 'JE': 'JERSEY', 'BY': 'BELARUS', 'BZ': 'BELIZE', 'RU': 'RUSSIAN FEDERATION', 'RW': 'RWANDA', 'RS': 'SERBIA', 'TL': 'TIMOR-LESTE', 'RE': 'R\xc3\x89UNION', 'TM': 'TURKMENISTAN', 'TJ': 'TAJIKISTAN', 'RO': 'ROMANIA', 'TK': 'TOKELAU', 'GW': 'GUINEA-BISSAU', 'GU': 'GUAM', 'GT': 'GUATEMALA', 'GS': 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS', 'GR': 'GREECE', 'GQ': 'EQUATORIAL GUINEA', 'GP': 'GUADELOUPE', 'JP': 'JAPAN', 'GY': 'GUYANA', 'GG': 'GUERNSEY', 'GF': 'FRENCH GUIANA', 'GE': 'GEORGIA', 'GD': 'GRENADA', 'GB': 'UNITED KINGDOM', 'GA': 'GABON', 'GN': 'GUINEA', 'GM': 'GAMBIA', 'GL': 'GREENLAND', 'GI': 'GIBRALTAR', 'GH': 'GHANA', 'OM': 'OMAN', 'TN': 'TUNISIA', 'JO': 'JORDAN', 'HR': 'CROATIA', 'HT': 'HAITI', 'HU': 'HUNGARY', 'HK': 'HONG KONG', 'HN': 'HONDURAS', 'HM': 'HEARD ISLAND AND MCDONALD ISLANDS', 'VE': 'VENEZUELA, BOLIVARIAN REPUBLIC OF', 'PR': 'PUERTO RICO', 'PS': 'PALESTINIAN TERRITORY, OCCUPIED', 'PW': 'PALAU', 'PT': 'PORTUGAL', 'KN': 'SAINT KITTS AND NEVIS', 'PY': 'PARAGUAY', 'IQ': 'IRAQ', 'PA': 'PANAMA', 'PF': 'FRENCH POLYNESIA', 'PG': 'PAPUA NEW GUINEA', 'PE': 'PERU', 'PK': 'PAKISTAN', 'PH': 'PHILIPPINES', 'PN': 'PITCAIRN', 'PL': 'POLAND', 'PM': 'SAINT PIERRE AND MIQUELON', 'ZM': 'ZAMBIA', 'EH': 'WESTERN SAHARA', 'EE': 'ESTONIA', 'EG': 'EGYPT', 'ZA': 'SOUTH AFRICA', 'EC': 'ECUADOR', 'IT': 'ITALY', 'VN': 'VIET NAM', 'SB': 'SOLOMON ISLANDS', 'ET': 'ETHIOPIA', 'SO': 'SOMALIA', 'ZW': 'ZIMBABWE', 'SA': 'SAUDI ARABIA', 'ES': 'SPAIN', 'ER': 'ERITREA', 'ME': 'MONTENEGRO', 'MD': 'MOLDOVA, REPUBLIC OF', 'MG': 'MADAGASCAR', 'MF': 'SAINT MARTIN', 'MA': 'MOROCCO', 'MC': 'MONACO', 'UZ': 'UZBEKISTAN', 'MM': 'MYANMAR', 'ML': 'MALI', 'MO': 'MACAO', 'MN': 'MONGOLIA', 'MH': 'MARSHALL ISLANDS', 'MK': 'MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF', 'MU': 'MAURITIUS', 'MT': 'MALTA', 'MW': 'MALAWI', 'MV': 'MALDIVES', 'MQ': 'MARTINIQUE', 'MP': 'NORTHERN MARIANA ISLANDS', 'MS': 'MONTSERRAT', 'MR': 'MAURITANIA', 'IM': 'ISLE OF MAN', 'UG': 'UGANDA', 'TZ': 'TANZANIA, UNITED REPUBLIC OF', 'MY': 'MALAYSIA', 'MX': 'MEXICO', 'IL': 'ISRAEL', 'FR': 'FRANCE', 'AW': 'ARUBA', 'SH': 'SAINT HELENA', 'SJ': 'SVALBARD AND JAN MAYEN', 'FI': 'FINLAND', 'FJ': 'FIJI', 'FK': 'FALKLAND ISLANDS (MALVINAS)', 'FM': 'MICRONESIA, FEDERATED STATES OF', 'FO': 'FAROE ISLANDS', 'NI': 'NICARAGUA', 'NL': 'NETHERLANDS', 'NO': 'NORWAY', 'NA': 'NAMIBIA', 'VU': 'VANUATU', 'NC': 'NEW CALEDONIA', 'NE': 'NIGER', 'NF': 'NORFOLK ISLAND', 'NG': 'NIGERIA', 'NZ': 'NEW ZEALAND', 'NP': 'NEPAL', 'NR': 'NAURU', 'NU': 'NIUE', 'CK': 'COOK ISLANDS', 'CI': "C\xc3\x94TE D'IVOIRE", 'CH': 'SWITZERLAND', 'CO': 'COLOMBIA', 'CN': 'CHINA', 'CM': 'CAMEROON', 'CL': 'CHILE', 'CC': 'COCOS (KEELING) ISLANDS', 'CA': 'CANADA', 'CG': 'CONGO', 'CF': 'CENTRAL AFRICAN REPUBLIC', 'CD': 'CONGO, THE DEMOCRATIC REPUBLIC OF THE', 'CZ': 'CZECH REPUBLIC', 'CY': 'CYPRUS', 'CX': 'CHRISTMAS ISLAND', 'CR': 'COSTA RICA', 'CV': 'CAPE VERDE', 'CU': 'CUBA', 'SZ': 'SWAZILAND', 'SY': 'SYRIAN ARAB REPUBLIC', 'KG': 'KYRGYZSTAN', 'KE': 'KENYA', 'SR': 'SURINAME', 'KI': 'KIRIBATI', 'KH': 'CAMBODIA', 'SV': 'EL SALVADOR', 'KM': 'COMOROS', 'ST': 'SAO TOME AND PRINCIPE', 'SK': 'SLOVAKIA', 'KR': 'KOREA, REPUBLIC OF', 'SI': 'SLOVENIA', 'KP': "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF", 'KW': 'KUWAIT', 'SN': 'SENEGAL', 'SM': 'SAN MARINO', 'SL': 'SIERRA LEONE', 'SC': 'SEYCHELLES', 'KZ': 'KAZAKHSTAN', 'KY': 'CAYMAN ISLANDS', 'SG': 'SINGAPORE', 'SE': 'SWEDEN', 'SD': 'SUDAN', 'DO': 'DOMINICAN REPUBLIC', 'DM': 'DOMINICA', 'DJ': 'DJIBOUTI', 'DK': 'DENMARK', 'VG': 'VIRGIN ISLANDS, BRITISH', 'DE': 'GERMANY', 'YE': 'YEMEN', 'DZ': 'ALGERIA', 'US': 'UNITED STATES', 'UY': 'URUGUAY', 'YT': 'MAYOTTE', 'UM': 'UNITED STATES MINOR OUTLYING ISLANDS', 'LB': 'LEBANON', 'LC': 'SAINT LUCIA', 'LA': "LAO PEOPLE'S DEMOCRATIC REPUBLIC", 'TV': 'TUVALU', 'TW': 'TAIWAN, PROVINCE OF CHINA', 'TT': 'TRINIDAD AND TOBAGO', 'TR': 'TURKEY', 'LK': 'SRI LANKA', 'LI': 'LIECHTENSTEIN', 'LV': 'LATVIA', 'TO': 'TONGA', 'LT': 'LITHUANIA', 'LU': 'LUXEMBOURG', 'LR': 'LIBERIA', 'LS': 'LESOTHO', 'TH': 'THAILAND', 'TF': 'FRENCH SOUTHERN TERRITORIES', 'TG': 'TOGO', 'TD': 'CHAD', 'TC': 'TURKS AND CAICOS ISLANDS', 'LY': 'LIBYAN ARAB JAMAHIRIYA', 'VA': 'HOLY SEE (VATICAN CITY STATE)', 'VC': 'SAINT VINCENT AND THE GRENADINES', 'AE': 'UNITED ARAB EMIRATES', 'AD': 'ANDORRA', 'AG': 'ANTIGUA AND BARBUDA', 'AF': 'AFGHANISTAN', 'AI': 'ANGUILLA', 'VI': 'VIRGIN ISLANDS, U.S.', 'IS': 'ICELAND', 'IR': 'IRAN, ISLAMIC REPUBLIC OF', 'AM': 'ARMENIA', 'AL': 'ALBANIA', 'AO': 'ANGOLA', 'AN': 'NETHERLANDS ANTILLES', 'AQ': 'ANTARCTICA', 'AS': 'AMERICAN SAMOA', 'AR': 'ARGENTINA', 'AU': 'AUSTRALIA', 'AT': 'AUSTRIA', 'IO': 'BRITISH INDIAN OCEAN TERRITORY', 'IN': 'INDIA', 'AX': '\xc3\x85LAND ISLANDS', 'AZ': 'AZERBAIJAN', 'IE': 'IRELAND', 'ID': 'INDONESIA', 'UA': 'UKRAINE', 'QA': 'QATAR', 'MZ': 'MOZAMBIQUE'} - - #Setting system string + + # Dictionary with country codes + countries = {'BD': 'BANGLADESH', 'BE': 'BELGIUM', 'BF': 'BURKINA FASO', 'BG': 'BULGARIA', 'BA': 'BOSNIA AND HERZEGOVINA', 'BB': 'BARBADOS', 'WF': 'WALLIS AND FUTUNA', 'BL': 'SAINT BARTH\xc3\x89LEMY', 'BM': 'BERMUDA', 'BN': 'BRUNEI DARUSSALAM', 'BO': 'BOLIVIA, PLURINATIONAL STATE OF', 'BH': 'BAHRAIN', 'BI': 'BURUNDI', 'BJ': 'BENIN', 'BT': 'BHUTAN', 'JM': 'JAMAICA', 'BV': 'BOUVET ISLAND', 'BW': 'BOTSWANA', 'WS': 'SAMOA', 'BR': 'BRAZIL', 'BS': 'BAHAMAS', 'JE': 'JERSEY', 'BY': 'BELARUS', 'BZ': 'BELIZE', 'RU': 'RUSSIAN FEDERATION', 'RW': 'RWANDA', 'RS': 'SERBIA', 'TL': 'TIMOR-LESTE', 'RE': 'R\xc3\x89UNION', 'TM': 'TURKMENISTAN', 'TJ': 'TAJIKISTAN', 'RO': 'ROMANIA', 'TK': 'TOKELAU', 'GW': 'GUINEA-BISSAU', 'GU': 'GUAM', 'GT': 'GUATEMALA', 'GS': 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS', 'GR': 'GREECE', 'GQ': 'EQUATORIAL GUINEA', 'GP': 'GUADELOUPE', 'JP': 'JAPAN', 'GY': 'GUYANA', 'GG': 'GUERNSEY', 'GF': 'FRENCH GUIANA', 'GE': 'GEORGIA', 'GD': 'GRENADA', 'GB': 'UNITED KINGDOM', 'GA': 'GABON', 'GN': 'GUINEA', 'GM': 'GAMBIA', 'GL': 'GREENLAND', 'GI': 'GIBRALTAR', 'GH': 'GHANA', 'OM': 'OMAN', 'TN': 'TUNISIA', 'JO': 'JORDAN', 'HR': 'CROATIA', 'HT': 'HAITI', 'HU': 'HUNGARY', 'HK': 'HONG KONG', 'HN': 'HONDURAS', 'HM': 'HEARD ISLAND AND MCDONALD ISLANDS', 'VE': 'VENEZUELA, BOLIVARIAN REPUBLIC OF', 'PR': 'PUERTO RICO', 'PS': 'PALESTINIAN TERRITORY, OCCUPIED', 'PW': 'PALAU', 'PT': 'PORTUGAL', 'KN': 'SAINT KITTS AND NEVIS', 'PY': 'PARAGUAY', 'IQ': 'IRAQ', 'PA': 'PANAMA', 'PF': 'FRENCH POLYNESIA', 'PG': 'PAPUA NEW GUINEA', 'PE': 'PERU', 'PK': 'PAKISTAN', 'PH': 'PHILIPPINES', 'PN': 'PITCAIRN', 'PL': 'POLAND', 'PM': 'SAINT PIERRE AND MIQUELON', 'ZM': 'ZAMBIA', 'EH': 'WESTERN SAHARA', 'EE': 'ESTONIA', 'EG': 'EGYPT', 'ZA': 'SOUTH AFRICA', 'EC': 'ECUADOR', 'IT': 'ITALY', 'VN': 'VIET NAM', 'SB': 'SOLOMON ISLANDS', 'ET': 'ETHIOPIA', 'SO': 'SOMALIA', 'ZW': 'ZIMBABWE', 'SA': 'SAUDI ARABIA', 'ES': 'SPAIN', 'ER': 'ERITREA', 'ME': 'MONTENEGRO', 'MD': 'MOLDOVA, REPUBLIC OF', 'MG': 'MADAGASCAR', 'MF': 'SAINT MARTIN', 'MA': 'MOROCCO', 'MC': 'MONACO', 'UZ': 'UZBEKISTAN', 'MM': 'MYANMAR', 'ML': 'MALI', 'MO': 'MACAO', 'MN': 'MONGOLIA', 'MH': 'MARSHALL ISLANDS', 'MK': 'MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF', 'MU': 'MAURITIUS', 'MT': 'MALTA', 'MW': 'MALAWI', 'MV': 'MALDIVES', 'MQ': 'MARTINIQUE', 'MP': 'NORTHERN MARIANA ISLANDS', 'MS': 'MONTSERRAT', 'MR': 'MAURITANIA', 'IM': 'ISLE OF MAN', 'UG': 'UGANDA', 'TZ': 'TANZANIA, UNITED REPUBLIC OF', 'MY': 'MALAYSIA', 'MX': 'MEXICO', 'IL': 'ISRAEL', 'FR': 'FRANCE', 'AW': 'ARUBA', 'SH': 'SAINT HELENA', 'SJ': 'SVALBARD AND JAN MAYEN', 'FI': 'FINLAND', 'FJ': 'FIJI', 'FK': + 'FALKLAND ISLANDS (MALVINAS)', 'FM': 'MICRONESIA, FEDERATED STATES OF', 'FO': 'FAROE ISLANDS', 'NI': 'NICARAGUA', 'NL': 'NETHERLANDS', 'NO': 'NORWAY', 'NA': 'NAMIBIA', 'VU': 'VANUATU', 'NC': 'NEW CALEDONIA', 'NE': 'NIGER', 'NF': 'NORFOLK ISLAND', 'NG': 'NIGERIA', 'NZ': 'NEW ZEALAND', 'NP': 'NEPAL', 'NR': 'NAURU', 'NU': 'NIUE', 'CK': 'COOK ISLANDS', 'CI': "C\xc3\x94TE D'IVOIRE", 'CH': 'SWITZERLAND', 'CO': 'COLOMBIA', 'CN': 'CHINA', 'CM': 'CAMEROON', 'CL': 'CHILE', 'CC': 'COCOS (KEELING) ISLANDS', 'CA': 'CANADA', 'CG': 'CONGO', 'CF': 'CENTRAL AFRICAN REPUBLIC', 'CD': 'CONGO, THE DEMOCRATIC REPUBLIC OF THE', 'CZ': 'CZECH REPUBLIC', 'CY': 'CYPRUS', 'CX': 'CHRISTMAS ISLAND', 'CR': 'COSTA RICA', 'CV': 'CAPE VERDE', 'CU': 'CUBA', 'SZ': 'SWAZILAND', 'SY': 'SYRIAN ARAB REPUBLIC', 'KG': 'KYRGYZSTAN', 'KE': 'KENYA', 'SR': 'SURINAME', 'KI': 'KIRIBATI', 'KH': 'CAMBODIA', 'SV': 'EL SALVADOR', 'KM': 'COMOROS', 'ST': 'SAO TOME AND PRINCIPE', 'SK': 'SLOVAKIA', 'KR': 'KOREA, REPUBLIC OF', 'SI': 'SLOVENIA', 'KP': "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF", 'KW': 'KUWAIT', 'SN': 'SENEGAL', 'SM': 'SAN MARINO', 'SL': 'SIERRA LEONE', 'SC': 'SEYCHELLES', 'KZ': 'KAZAKHSTAN', 'KY': 'CAYMAN ISLANDS', 'SG': 'SINGAPORE', 'SE': 'SWEDEN', 'SD': 'SUDAN', 'DO': 'DOMINICAN REPUBLIC', 'DM': 'DOMINICA', 'DJ': 'DJIBOUTI', 'DK': 'DENMARK', 'VG': 'VIRGIN ISLANDS, BRITISH', 'DE': 'GERMANY', 'YE': 'YEMEN', 'DZ': 'ALGERIA', 'US': 'UNITED STATES', 'UY': 'URUGUAY', 'YT': 'MAYOTTE', 'UM': 'UNITED STATES MINOR OUTLYING ISLANDS', 'LB': 'LEBANON', 'LC': 'SAINT LUCIA', 'LA': "LAO PEOPLE'S DEMOCRATIC REPUBLIC", 'TV': 'TUVALU', 'TW': 'TAIWAN, PROVINCE OF CHINA', 'TT': 'TRINIDAD AND TOBAGO', 'TR': 'TURKEY', 'LK': 'SRI LANKA', 'LI': 'LIECHTENSTEIN', 'LV': 'LATVIA', 'TO': 'TONGA', 'LT': 'LITHUANIA', 'LU': 'LUXEMBOURG', 'LR': 'LIBERIA', 'LS': 'LESOTHO', 'TH': 'THAILAND', 'TF': 'FRENCH SOUTHERN TERRITORIES', 'TG': 'TOGO', 'TD': 'CHAD', 'TC': 'TURKS AND CAICOS ISLANDS', 'LY': 'LIBYAN ARAB JAMAHIRIYA', 'VA': 'HOLY SEE (VATICAN CITY STATE)', 'VC': 'SAINT VINCENT AND THE GRENADINES', 'AE': 'UNITED ARAB EMIRATES', 'AD': 'ANDORRA', 'AG': 'ANTIGUA AND BARBUDA', 'AF': 'AFGHANISTAN', 'AI': 'ANGUILLA', 'VI': 'VIRGIN ISLANDS, U.S.', 'IS': 'ICELAND', 'IR': 'IRAN, ISLAMIC REPUBLIC OF', 'AM': 'ARMENIA', 'AL': 'ALBANIA', 'AO': 'ANGOLA', 'AN': 'NETHERLANDS ANTILLES', 'AQ': 'ANTARCTICA', 'AS': 'AMERICAN SAMOA', 'AR': 'ARGENTINA', 'AU': 'AUSTRALIA', 'AT': 'AUSTRIA', 'IO': 'BRITISH INDIAN OCEAN TERRITORY', 'IN': 'INDIA', 'AX': '\xc3\x85LAND ISLANDS', 'AZ': 'AZERBAIJAN', 'IE': 'IRELAND', 'ID': 'INDONESIA', 'UA': 'UKRAINE', 'QA': 'QATAR', 'MZ': 'MOZAMBIQUE'} + + # Setting system string try: self.ui.txtSystem.setText(platform.platform()) self.ui.txtSystem.setCursorPosition(0) except: pass - - #Getting country from locale code + + # Getting country from locale code try: - locale.setlocale(locale.LC_ALL,'') - country_code=locale.getlocale()[0].split('_')[1] - + locale.setlocale(locale.LC_ALL, '') + country_code = locale.getlocale()[0].split('_')[1] + self.ui.txtCountry.setText(countries[country_code]) self.ui.txtCountry.setCursorPosition(0) except: pass + def send(self): '''Sends the data inserted in the form''' - - post={} - post['software']="Relational algebra" - post["version"]= version - post["system"]= compatibility.get_py_str(self.ui.txtSystem.text()) - post["country"]= compatibility.get_py_str(self.ui.txtCountry.text()) - post["school"]= compatibility.get_py_str(self.ui.txtSchool.text()) + + post = {} + post['software'] = "Relational algebra" + post["version"] = version + post["system"] = compatibility.get_py_str(self.ui.txtSystem.text()) + post["country"] = compatibility.get_py_str(self.ui.txtCountry.text()) + post["school"] = compatibility.get_py_str(self.ui.txtSchool.text()) post["age"] = compatibility.get_py_str(self.ui.txtAge.text()) post["find"] = compatibility.get_py_str(self.ui.txtFind.text()) post["email"] = compatibility.get_py_str(self.ui.txtEmail.text()) - post["comments"] = compatibility.get_py_str(self.ui.txtComments.toPlainText()) - - #Clears the form + post["comments"] = compatibility.get_py_str( + self.ui.txtComments.toPlainText()) + + # Clears the form self.ui.txtSystem.clear() self.ui.txtCountry.clear() self.ui.txtSchool.clear() @@ -76,12 +83,14 @@ class surveyForm (QtGui.QWidget): self.ui.txtFind.clear() self.ui.txtEmail.clear() self.ui.txtComments.clear() - - response=maintenance.send_survey(post) - - if response.status!=200: - QtGui.QMessageBox.information(None,QtGui.QApplication.translate("Form", "Error"),QtGui.QApplication.translate("Form", "Unable to send the data!") ) + + response = maintenance.send_survey(post) + + if response.status != 200: + QtGui.QMessageBox.information(None, QtGui.QApplication.translate( + "Form", "Error"), QtGui.QApplication.translate("Form", "Unable to send the data!")) else: - QtGui.QMessageBox.information(None,QtGui.QApplication.translate("Form", "Thanks"),QtGui.QApplication.translate("Form", "Thanks for sending!") ) - + QtGui.QMessageBox.information(None, QtGui.QApplication.translate( + "Form", "Thanks"), QtGui.QApplication.translate("Form", "Thanks for sending!")) + self.hide() diff --git a/relational_pyside/maingui.py b/relational_pyside/maingui.py index 433e7cb..b3d92a4 100644 --- a/relational_pyside/maingui.py +++ b/relational_pyside/maingui.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'relational_pyside/maingui.ui' # -# Created: Fri Dec 27 00:05:55 2013 +# Created: Fri Dec 27 00:23:51 2013 # by: pyside-uic 0.2.15 running on PySide 1.2.1 # # WARNING! All changes made in this file will be lost! diff --git a/relational_pyside/rel_edit.py b/relational_pyside/rel_edit.py index f94aed7..9347f85 100644 --- a/relational_pyside/rel_edit.py +++ b/relational_pyside/rel_edit.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'relational_pyside/rel_edit.ui' # -# Created: Fri Dec 27 00:05:55 2013 +# Created: Fri Dec 27 00:23:51 2013 # by: pyside-uic 0.2.15 running on PySide 1.2.1 # # WARNING! All changes made in this file will be lost! diff --git a/relational_pyside/survey.py b/relational_pyside/survey.py index 11b5396..f335228 100644 --- a/relational_pyside/survey.py +++ b/relational_pyside/survey.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'relational_pyside/survey.ui' # -# Created: Fri Dec 27 00:05:54 2013 +# Created: Fri Dec 27 00:23:51 2013 # by: pyside-uic 0.2.15 running on PySide 1.2.1 # # WARNING! All changes made in this file will be lost! diff --git a/relational_readline/linegui.py b/relational_readline/linegui.py index 5827355..573b851 100644 --- a/relational_readline/linegui.py +++ b/relational_readline/linegui.py @@ -2,22 +2,23 @@ # coding=UTF-8 # Relational # Copyright (C) 2010 Salvo "LtWorf" Tomaselli -# +# # Relational is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . -# +# # author Salvo "LtWorf" Tomaselli -# Initial readline code from http://www.doughellmann.com/PyMOTW/readline/index.html +# Initial readline code from +# http://www.doughellmann.com/PyMOTW/readline/index.html import readline import logging @@ -31,281 +32,290 @@ from xtermcolor import colorize PROMPT_COLOR = 0xffff00 ERROR_COLOR = 0xff0000 + class SimpleCompleter(object): + '''Handles completion''' - + def __init__(self, options): '''Takes a list of valid completion options''' self.options = sorted(options) return - - def add_completion(self,option): + + def add_completion(self, option): '''Adds one string to the list of the valid completion options''' if option not in self.options: self.options.append(option) self.options.sort() - - def remove_completion(self,option): + + def remove_completion(self, option): '''Removes one completion from the list of the valid completion options''' if option in self.options: self.options.remove(option) pass - + def complete(self, text, state): response = None if state == 0: # This is the first time for this text, so build a match list. if text: - - self.matches =[s + + self.matches = [s for s in self.options if s and s.startswith(text)] - - #Add the completion for files here + + # Add the completion for files here try: - d=os.path.dirname(text) - listf=os.listdir(d) - - d+="/" + d = os.path.dirname(text) + listf = os.listdir(d) + + d += "/" except: - d="" - listf=os.listdir('.') - + d = "" + listf = os.listdir('.') + for i in listf: - i=(d+i).replace('//','/') + i = (d + i).replace('//', '/') if i.startswith(text): if os.path.isdir(i): - i=i+"/" + i = i + "/" self.matches.append(i) - + logging.debug('%s matches: %s', repr(text), self.matches) else: self.matches = self.options[:] logging.debug('(empty input) matches: %s', self.matches) - + # Return the state'th item from the match list, # if we have that many. try: response = self.matches[state] except IndexError: response = None - logging.debug('complete(%s, %s) => %s', + logging.debug('complete(%s, %s) => %s', repr(text), state, repr(response)) return response -relations={} -completer=SimpleCompleter(['SURVEY','LIST','LOAD ','UNLOAD ','HELP ','QUIT','SAVE ','_PRODUCT ','_UNION ','_INTERSECTION ','_DIFFERENCE ','_JOIN ','_LJOIN ','_RJOIN ','_FJOIN ','_PROJECTION ','_RENAME_TO ','_SELECTION ','_RENAME ','_DIVISION ']) +relations = {} +completer = SimpleCompleter( + ['SURVEY', 'LIST', 'LOAD ', 'UNLOAD ', 'HELP ', 'QUIT', 'SAVE ', '_PRODUCT ', '_UNION ', '_INTERSECTION ', + '_DIFFERENCE ', '_JOIN ', '_LJOIN ', '_RJOIN ', '_FJOIN ', '_PROJECTION ', '_RENAME_TO ', '_SELECTION ', '_RENAME ', '_DIVISION ']) -def load_relation(filename,defname=None): + +def load_relation(filename, defname=None): if not os.path.isfile(filename): - print >> sys.stderr, colorize("%s is not a file" % filename,ERROR_COLOR) + print >> sys.stderr, colorize( + "%s is not a file" % filename, ERROR_COLOR) return None - f=filename.split('/') - if defname==None: - defname=f[len(f)-1].lower() - if defname.endswith(".csv"): #removes the extension - defname=defname[:-4] - + f = filename.split('/') + if defname == None: + defname = f[len(f) - 1].lower() + if defname.endswith(".csv"): # removes the extension + defname = defname[:-4] + if not rtypes.is_valid_relation_name(defname): - print >> sys.stderr, colorize("%s is not a valid relation name" % defname,ERROR_COLOR) + print >> sys.stderr, colorize( + "%s is not a valid relation name" % defname, ERROR_COLOR) return try: - relations[defname]=relation.relation(filename) - + relations[defname] = relation.relation(filename) + completer.add_completion(defname) - print colorize("Loaded relation %s"% defname,0x00ff00) + print colorize("Loaded relation %s" % defname, 0x00ff00) return defname except Exception, e: - print >>sys.stderr,colorize(e,ERROR_COLOR) + print >>sys.stderr, colorize(e, ERROR_COLOR) return None + def survey(): '''performs a survey''' from relational import maintenance - - post= {'software':'Relational algebra (cli)','version':version} - fields=('System','Country','School','Age','How did you find','email (only if you want a reply)','Comments') + post = {'software': 'Relational algebra (cli)', 'version': version} + + fields = ('System', 'Country', 'School', 'Age', 'How did you find', + 'email (only if you want a reply)', 'Comments') for i in fields: - a=raw_input('%s: '%i) - post[i]=a + a = raw_input('%s: ' % i) + post[i] = a maintenance.send_survey(post) + def help(command): '''Prints help on the various functions''' - p=command.split(' ',1) - if len(p)==1: + p = command.split(' ', 1) + if len(p) == 1: print 'HELP command' print 'To execute a query:\n[relation =] query\nIf the 1st part is omitted, the result will be stored in the relation last_.' print 'To prevent from printing the relation, append a ; to the end of the query.' print 'To insert relational operators, type _OPNAME, they will be internally replaced with the correct symbol.' print 'Rember: the tab key is enabled and can be very helpful if you can\'t remember something.' return - cmd=p[1] - - if cmd=='QUIT': + cmd = p[1] + + if cmd == 'QUIT': print 'Quits the program' - elif cmd=='LIST': + elif cmd == 'LIST': print "Lists the relations loaded" - elif cmd=='LOAD': + elif cmd == 'LOAD': print "LOAD filename [relationame]" print "Loads a relation into memory" - elif cmd=='UNLOAD': + elif cmd == 'UNLOAD': print "UNLOAD relationame" print "Unloads a relation from memory" - elif cmd=='SAVE': + elif cmd == 'SAVE': print "SAVE filename relationame" print "Saves a relation in a file" - elif cmd=='HELP': + elif cmd == 'HELP': print "Prints the help on a command" - elif cmd=='SURVEY': + elif cmd == 'SURVEY': print "Fill and send a survey" else: - print "Unknown command: %s" %cmd - + print "Unknown command: %s" % cmd + def exec_line(command): - command=command.strip() - + command = command.strip() + if command.startswith(';'): return - elif command=='QUIT': + elif command == 'QUIT': sys.exit(0) elif command.startswith('HELP'): help(command) - elif command=='LIST': #Lists all the loaded relations + elif command == 'LIST': # Lists all the loaded relations for i in relations: if not i.startswith('_'): print i - elif command=='SURVEY': + elif command == 'SURVEY': survey() - elif command.startswith('LOAD '): #Loads a relation - pars=command.split(' ') - if len(pars)==1: - print colorize("Missing parameter",ERROR_COLOR) + elif command.startswith('LOAD '): # Loads a relation + pars = command.split(' ') + if len(pars) == 1: + print colorize("Missing parameter", ERROR_COLOR) return - - filename=pars[1] - if len(pars)>2: - defname=pars[2] + + filename = pars[1] + if len(pars) > 2: + defname = pars[2] else: - defname=None - load_relation(filename,defname) - + defname = None + load_relation(filename, defname) + elif command.startswith('UNLOAD '): - pars=command.split(' ') - if len(pars)<2: - print colorize("Missing parameter",ERROR_COLOR) + pars = command.split(' ') + if len(pars) < 2: + print colorize("Missing parameter", ERROR_COLOR) return if pars[1] in relations: del relations[pars[1]] completer.remove_completion(pars[1]) else: - print colorize("No such relation %s" % pars[1],ERROR_COLOR) + print colorize("No such relation %s" % pars[1], ERROR_COLOR) pass elif command.startswith('SAVE '): - pars=command.split(' ') - if len(pars)!=3: - print colorize("Missing parameter",ERROR_COLOR) + pars = command.split(' ') + if len(pars) != 3: + print colorize("Missing parameter", ERROR_COLOR) return - - filename=pars[1] - defname=pars[2] - + + filename = pars[1] + defname = pars[2] + if defname not in relations: - print colorize("No such relation %s" % defname,ERROR_COLOR) + print colorize("No such relation %s" % defname, ERROR_COLOR) return - + try: relations[defname].save(filename) - except Exception,e: - print colorize(e,ERROR_COLOR) + except Exception, e: + print colorize(e, ERROR_COLOR) else: exec_query(command) + def replacements(query): '''This funcion replaces ascii easy operators with the correct ones''' - query=query.replace(u'_PRODUCT' , u'*') - query=query.replace(u'_UNION' , u'ᑌ') - query=query.replace(u'_INTERSECTION' , u'ᑎ') - query=query.replace(u'_DIFFERENCE' , u'-') - query=query.replace(u'_JOIN' , u'ᐅᐊ') - query=query.replace(u'_LJOIN' , u'ᐅLEFTᐊ') - query=query.replace(u'_RJOIN' , u'ᐅRIGHTᐊ') - query=query.replace(u'_FJOIN' , u'ᐅFULLᐊ') - query=query.replace(u'_PROJECTION' , u'π') - query=query.replace(u'_RENAME_TO' , u'➡') - query=query.replace(u'_SELECTION' , u'σ') - query=query.replace(u'_RENAME' , u'ρ') - query=query.replace(u'_DIVISION' , u'÷') + query = query.replace(u'_PRODUCT', u'*') + query = query.replace(u'_UNION', u'ᑌ') + query = query.replace(u'_INTERSECTION', u'ᑎ') + query = query.replace(u'_DIFFERENCE', u'-') + query = query.replace(u'_JOIN', u'ᐅᐊ') + query = query.replace(u'_LJOIN', u'ᐅLEFTᐊ') + query = query.replace(u'_RJOIN', u'ᐅRIGHTᐊ') + query = query.replace(u'_FJOIN', u'ᐅFULLᐊ') + query = query.replace(u'_PROJECTION', u'π') + query = query.replace(u'_RENAME_TO', u'➡') + query = query.replace(u'_SELECTION', u'σ') + query = query.replace(u'_RENAME', u'ρ') + query = query.replace(u'_DIVISION', u'÷') return query + def exec_query(command): '''This function executes a query and prints the result on the screen if the command terminates with ";" the result will not be printed ''' - command=unicode(command,'utf-8') - - #If it terminates with ; doesn't print the result + command = unicode(command, 'utf-8') + + # If it terminates with ; doesn't print the result if command.endswith(';'): - command=command[:-1] - printrel=False + command = command[:-1] + printrel = False else: - printrel=True - - - - #Performs replacements for weird operators - command=replacements(command) - - #Finds the name in where to save the query - parts=command.split('=',1) - - if len(parts)>1 and rtypes.is_valid_relation_name(parts[0]): - relname=parts[0] - query=parts[1] + printrel = True + + # Performs replacements for weird operators + command = replacements(command) + + # Finds the name in where to save the query + parts = command.split('=', 1) + + if len(parts) > 1 and rtypes.is_valid_relation_name(parts[0]): + relname = parts[0] + query = parts[1] else: - relname='last_' - query=command - - - #Execute query + relname = 'last_' + query = command + + # Execute query try: - pyquery=parser.parse(query) - result=eval(pyquery,relations) - - print colorize("-> query: %s" % pyquery.encode('utf-8'),0x00ff00) - + pyquery = parser.parse(query) + result = eval(pyquery, relations) + + print colorize("-> query: %s" % pyquery.encode('utf-8'), 0x00ff00) + if printrel: print print result - - relations[relname]=result - + + relations[relname] = result + completer.add_completion(relname) except Exception, e: - print colorize(e,ERROR_COLOR) - + print colorize(e, ERROR_COLOR) + + def main(files=[]): - print colorize('> ',PROMPT_COLOR) + "; Type HELP to get the HELP" - print colorize('> ',PROMPT_COLOR) + "; Completion is activated using the tab (if supported by the terminal)" - + print colorize('> ', PROMPT_COLOR) + "; Type HELP to get the HELP" + print colorize('> ', PROMPT_COLOR) + "; Completion is activated using the tab (if supported by the terminal)" + for i in files: load_relation(i) - + readline.set_completer(completer.complete) readline.parse_and_bind('tab: complete') readline.parse_and_bind('set editing-mode emacs') readline.set_completer_delims(" ") - while True: try: - line = raw_input(colorize('> ',PROMPT_COLOR)) - if isinstance(line,str) and len(line)>0: + line = raw_input(colorize('> ', PROMPT_COLOR)) + if isinstance(line, str) and len(line) > 0: exec_line(line) except KeyboardInterrupt: print @@ -317,4 +327,3 @@ def main(files=[]): if __name__ == "__main__": main() - \ No newline at end of file