Changed about and README to not point to galileo anymore

master
Salvo 'LtWorf' Tomaselli 2013-12-27 00:31:43 +07:00
parent f31d0dea28
commit 556eecc118
25 changed files with 2212 additions and 2023 deletions

@ -2,6 +2,9 @@ To launch the application, run
./relational_gui.py ./relational_gui.py
If it needs some dependencies, check this page: Language definition is here:
http://galileo.dmi.unict.it/wiki/relational/doku.php?id=download#install https://github.com/ltworf/relational/wiki/Grammar-and-language
If it needs some dependencies:
Qt4, Python 2.7, either PyQT4 or Pyside.

@ -33,14 +33,15 @@ COLOR_CYAN = 0x00ffff
print relation print relation
rels={} rels = {}
examples_path='samples/' examples_path = 'samples/'
tests_path='test/' tests_path = 'test/'
def readfile(fname): def readfile(fname):
'''Reads a file as string and returns its content''' '''Reads a file as string and returns its content'''
fd=open(fname) fd = open(fname)
expr=fd.read() expr = fd.read()
fd.close() fd.close()
return expr return expr
@ -50,141 +51,140 @@ def load_relations():
examples_path variable and stores them in the rels dictionary''' examples_path variable and stores them in the rels dictionary'''
print "Loading relations" print "Loading relations"
for i in os.listdir(examples_path): for i in os.listdir(examples_path):
if i.endswith('.csv'): #It's a relation, loading it if i.endswith('.csv'): # It's a relation, loading it
#Naming the relation # Naming the relation
relname=i[:-4] relname = i[:-4]
print ("Loading relation %s with name %s..." % (i,relname)), print ("Loading relation %s with name %s..." % (i, relname)),
rels[relname]=relation.relation('%s%s' % (examples_path,i)) rels[relname] = relation.relation('%s%s' % (examples_path, i))
print 'done' print 'done'
def execute_tests(): def execute_tests():
py_bad=0 py_bad = 0
py_good=0 py_good = 0
py_tot=0 py_tot = 0
q_bad=0 q_bad = 0
q_good=0 q_good = 0
q_tot=0 q_tot = 0
ex_bad=0 ex_bad = 0
ex_good=0 ex_good = 0
ex_tot=0 ex_tot = 0
for i in os.listdir(tests_path): for i in os.listdir(tests_path):
if i.endswith('.query'): if i.endswith('.query'):
q_tot+=1 q_tot += 1
if run_test(i[:-6]): if run_test(i[:-6]):
q_good+=1 q_good += 1
else: else:
q_bad+=1 q_bad += 1
elif i.endswith('.python'): elif i.endswith('.python'):
py_tot+=1 py_tot += 1
if run_py_test(i[:-7]): if run_py_test(i[:-7]):
py_good+=1 py_good += 1
else: else:
py_bad+=1 py_bad += 1
elif i.endswith('.exec'): elif i.endswith('.exec'):
ex_tot+=1 ex_tot += 1
if run_exec_test(i[:-5]): if run_exec_test(i[:-5]):
ex_good+=1 ex_good += 1
else: else:
ex_bad+=1 ex_bad += 1
print colorize("Resume of the results",COLOR_CYAN) print colorize("Resume of the results", COLOR_CYAN)
print colorize("Query tests",COLOR_MAGENTA) print colorize("Query tests", COLOR_MAGENTA)
print "Total test count: %d" % q_tot print "Total test count: %d" % q_tot
print "Passed tests: %d" % q_good print "Passed tests: %d" % q_good
if q_bad>0: if q_bad > 0:
print colorize("Failed tests count: %d" % q_bad,COLOR_RED) print colorize("Failed tests count: %d" % q_bad, COLOR_RED)
print colorize("Python tests",COLOR_MAGENTA) print colorize("Python tests", COLOR_MAGENTA)
print "Total test count: %d" % py_tot print "Total test count: %d" % py_tot
print "Passed tests: %d" % py_good print "Passed tests: %d" % py_good
if py_bad>0: if py_bad > 0:
print colorize("Failed tests count: %d" % py_bad,COLOR_RED) print colorize("Failed tests count: %d" % py_bad, COLOR_RED)
print colorize("Execute Python tests",COLOR_MAGENTA) print colorize("Execute Python tests", COLOR_MAGENTA)
print "Total test count: %d" % ex_tot print "Total test count: %d" % ex_tot
print "Passed tests: %d" % ex_good print "Passed tests: %d" % ex_good
if ex_bad>0: if ex_bad > 0:
print colorize("Failed tests count: %d" % ex_bad,COLOR_RED) print colorize("Failed tests count: %d" % ex_bad, COLOR_RED)
print colorize("Total results", COLOR_CYAN)
print colorize("Total results",COLOR_CYAN) if q_bad + py_bad + ex_bad == 0:
if q_bad+py_bad+ex_bad==0: print colorize("No failed tests", COLOR_GREEN)
print colorize("No failed tests",COLOR_GREEN)
return 0 return 0
else: 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 return 1
def run_exec_test(testname): def run_exec_test(testname):
'''Runs a python test, which executes code directly rather than queries''' '''Runs a python test, which executes code directly rather than queries'''
print "Running python test: " + colorize(testname,COLOR_MAGENTA) print "Running python test: " + colorize(testname, COLOR_MAGENTA)
glob=rels.copy() glob = rels.copy()
exp_result={} exp_result = {}
try: try:
expr=readfile('%s%s.exec' % (tests_path,testname)) expr = readfile('%s%s.exec' % (tests_path, testname))
exec(expr,glob) #Evaluating the expression exec(expr, glob) # Evaluating the expression
expr=readfile('%s%s.exec' % (tests_path,testname)) expr = readfile('%s%s.exec' % (tests_path, testname))
exec(expr,glob) #Evaluating the expression exec(expr, glob) # Evaluating the expression
expr = readfile('%s%s.result' % (tests_path, testname))
exp_result = eval(expr, rels) # Evaluating the expression
expr=readfile('%s%s.result' % (tests_path,testname)) if isinstance(exp_result, dict):
exp_result=eval(expr,rels) #Evaluating the expression fields_ok = True
if isinstance(exp_result,dict):
fields_ok=True
for i in exp_result: 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: if fields_ok:
print colorize('Test passed',COLOR_GREEN) print colorize('Test passed', COLOR_GREEN)
return True return True
except: except:
pass pass
print colorize('ERROR',COLOR_RED) print colorize('ERROR', COLOR_RED)
print colorize('=====================================',COLOR_RED) print colorize('=====================================', COLOR_RED)
print "Expected %s" % exp_result print "Expected %s" % exp_result
#print "Got %s" % result # print "Got %s" % result
print colorize('=====================================',COLOR_RED) print colorize('=====================================', COLOR_RED)
return False return False
def run_py_test(testname): def run_py_test(testname):
'''Runs a python test, which evaluates expressions directly rather than queries''' '''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: try:
expr=readfile('%s%s.python' % (tests_path,testname)) expr = readfile('%s%s.python' % (tests_path, testname))
result=eval(expr,rels) #Evaluating the expression result = eval(expr, rels) # Evaluating the expression
expr=readfile('%s%s.result' % (tests_path,testname)) expr = readfile('%s%s.result' % (tests_path, testname))
exp_result=eval(expr,rels) #Evaluating the expression exp_result = eval(expr, rels) # Evaluating the expression
if result==exp_result: if result == exp_result:
print colorize('Test passed',COLOR_GREEN) print colorize('Test passed', COLOR_GREEN)
return True return True
except: except:
pass pass
print colorize('ERROR',COLOR_RED) print colorize('ERROR', COLOR_RED)
print colorize('=====================================',COLOR_RED) print colorize('=====================================', COLOR_RED)
print "Expected %s" % exp_result print "Expected %s" % exp_result
print "Got %s" % result print "Got %s" % result
print colorize('=====================================',COLOR_RED) print colorize('=====================================', COLOR_RED)
return False return False
def run_test(testname): def run_test(testname):
'''Runs a specific test executing the file '''Runs a specific test executing the file
testname.query testname.query
@ -192,48 +192,52 @@ def run_test(testname):
testname.result testname.result
The query will be executed both unoptimized and The query will be executed both unoptimized and
optimized''' optimized'''
print "Running test: "+ colorize(testname,COLOR_MAGENTA) 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
query = None
expr = None
o_query = None
o_expr = None
result_rel = None
result = None
o_result = None
try: try:
result_rel=relation.relation('%s%s.result' % (tests_path,testname)) result_rel = relation.relation('%s%s.result' % (tests_path, testname))
query=unicode(readfile('%s%s.query' % (tests_path,testname)).strip(),'utf8') query = unicode(
o_query=optimizer.optimize_all(query,rels) 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 expr = parser.parse(query) # Converting expression to python string
result=eval(expr,rels) #Evaluating the expression result = eval(expr, rels) # Evaluating the expression
o_expr=parser.parse(o_query)#Converting expression to python string o_expr = parser.parse(
o_result=eval(o_expr,rels) #Evaluating the expression 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_expr = parser.tree(query).toCode() # Converting to python code
c_result=eval(c_expr,rels) c_result = eval(c_expr, rels)
if (o_result==result_rel) and (result==result_rel) and (c_result==result_rel): if (o_result == result_rel) and (result == result_rel) and (c_result == result_rel):
print colorize('Test passed',COLOR_GREEN) print colorize('Test passed', COLOR_GREEN)
return True return True
except Exception as inst: except Exception as inst:
print inst print inst
pass pass
print colorize('ERROR',COLOR_RED) print colorize('ERROR', COLOR_RED)
print "Query: %s -> %s" % (query,expr) print "Query: %s -> %s" % (query, expr)
print "Optimized query: %s -> %s" % (o_query,o_expr) print "Optimized query: %s -> %s" % (o_query, o_expr)
print colorize('=====================================',COLOR_RED) print colorize('=====================================', COLOR_RED)
print colorize("Expected result",COLOR_GREEN) print colorize("Expected result", COLOR_GREEN)
print result_rel print result_rel
print colorize("Result",COLOR_RED) print colorize("Result", COLOR_RED)
print result print result
print colorize("Optimized result",COLOR_RED) print colorize("Optimized result", COLOR_RED)
print o_result print o_result
print colorize("optimized result match %s" % str(result_rel==o_result),COLOR_MAGENTA) 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("result match %s" % str(result == result_rel), COLOR_MAGENTA)
print colorize('=====================================',COLOR_RED) print colorize('=====================================', COLOR_RED)
return False return False

@ -1,11 +1,11 @@
__all__ = ( __all__ = (
"relation", "relation",
"parser", "parser",
"optimizer", "optimizer",
"optimizations", "optimizations",
"rtypes", "rtypes",
"parallel", "parallel",
) )

@ -23,23 +23,21 @@ import httplib
import urllib import urllib
import relation import relation
def send_survey(data): def send_survey(data):
'''Sends the survey. Data must be a dictionary. '''Sends the survey. Data must be a dictionary.
returns the http response''' returns the http response'''
post='' post = ''
for i in data.keys(): for i in data.keys():
post+='%s: %s\n' %(i,data[i]) 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)
# 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 = httplib.HTTPConnection('feedback-ltworf.appspot.com')
connection.request("POST","/feedback/relational",params,headers) connection.request("POST", "/feedback/relational", params, headers)
return connection.getresponse() return connection.getresponse()
@ -49,46 +47,47 @@ def check_latest_version():
Heavely dependent on server and server configurations Heavely dependent on server and server configurations
not granted to work forever.''' not granted to work forever.'''
connection = httplib.HTTPConnection('feedback-ltworf.appspot.com') connection = httplib.HTTPConnection('feedback-ltworf.appspot.com')
connection.request("GET","/version/relational") connection.request("GET", "/version/relational")
r=connection.getresponse() r = connection.getresponse()
#html # html
s=r.read() s = r.read()
if len(s)==0: if len(s) == 0:
return None return None
return s.strip() return s.strip()
class interface (object): class interface (object):
'''It is used to provide services to the user interfaces, in order to '''It is used to provide services to the user interfaces, in order to
reduce the amount of duplicated code present in different user interfaces. reduce the amount of duplicated code present in different user interfaces.
''' '''
def __init__(self): 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 '''Loads a relation from file, and gives it a name to
be used in subsequent queries.''' be used in subsequent queries.'''
pass pass
def unload(self,name): def unload(self, name):
'''Unloads an existing relation.''' '''Unloads an existing relation.'''
pass pass
def store(self,filename,name): def store(self, filename, name):
'''Stores a relation to file.''' '''Stores a relation to file.'''
pass pass
def get_relation(self,name): def get_relation(self, name):
'''Returns the relation corresponding to name.''' '''Returns the relation corresponding to name.'''
pass pass
def set_relation(self,name,rel): def set_relation(self, name, rel):
'''Sets the relation corresponding to name.''' '''Sets the relation corresponding to name.'''
pass pass
def execute(self,query,relname='last_'): def execute(self, query, relname='last_'):
'''Executes a query, returns the result and if '''Executes a query, returns the result and if
relname is not None, adds the result to the relname is not None, adds the result to the
dictionary, with the name given in relname.''' dictionary, with the name given in relname.'''

@ -34,37 +34,40 @@ import parser
from cStringIO import StringIO from cStringIO import StringIO
from tokenize import generate_tokens from tokenize import generate_tokens
sel_op=('//=','**=','and','not','in','//','**','<<','>>','==','!=','>=','<=','+=','-=','*=','/=','%=','or','+','-','*','/','&','|','^','~','<','>','%','=','(',')',',','[',']') sel_op = (
'//=', '**=', 'and', 'not', 'in', '//', '**', '<<', '>>', '==', '!=', '>=', '<=', '+=', '-=',
'*=', '/=', '%=', 'or', '+', '-', '*', '/', '&', '|', '^', '~', '<', '>', '%', '=', '(', ')', ',', '[', ']')
PRODUCT=parser.PRODUCT PRODUCT = parser.PRODUCT
DIFFERENCE=parser.DIFFERENCE DIFFERENCE = parser.DIFFERENCE
UNION=parser.UNION UNION = parser.UNION
INTERSECTION=parser.INTERSECTION INTERSECTION = parser.INTERSECTION
DIVISION=parser.DIVISION DIVISION = parser.DIVISION
JOIN=parser.JOIN JOIN = parser.JOIN
JOIN_LEFT=parser.JOIN_LEFT JOIN_LEFT = parser.JOIN_LEFT
JOIN_RIGHT=parser.JOIN_RIGHT JOIN_RIGHT = parser.JOIN_RIGHT
JOIN_FULL=parser.JOIN_FULL JOIN_FULL = parser.JOIN_FULL
PROJECTION=parser.PROJECTION PROJECTION = parser.PROJECTION
SELECTION=parser.SELECTION SELECTION = parser.SELECTION
RENAME=parser.RENAME RENAME = parser.RENAME
ARROW=parser.ARROW ARROW = parser.ARROW
def replace_node(replace,replacement): def replace_node(replace, replacement):
'''This function replaces "replace" node with the node "with", '''This function replaces "replace" node with the node "with",
the father of the node will now point to the with node''' the father of the node will now point to the with node'''
replace.name=replacement.name replace.name = replacement.name
replace.kind=replacement.kind replace.kind = replacement.kind
if replace.kind==parser.UNARY: if replace.kind == parser.UNARY:
replace.child=replacement.child replace.child = replacement.child
replace.prop=replacement.prop replace.prop = replacement.prop
elif replace.kind==parser.BINARY: elif replace.kind == parser.BINARY:
replace.right=replacement.right replace.right = replacement.right
replace.left=replacement.left 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. '''Does a recoursive optimization on the tree.
This function will recoursively execute the function given This function will recoursively execute the function given
@ -76,20 +79,20 @@ def recoursive_scan(function,node,rels=None):
it has performed on the tree. it has performed on the tree.
The various result will be added up and this final value will be the The various result will be added up and this final value will be the
returned value.''' returned value.'''
changes=0 changes = 0
#recoursive scan # recoursive scan
if node.kind==parser.UNARY: if node.kind == parser.UNARY:
if rels!=None: if rels != None:
changes+=function(node.child,rels) changes += function(node.child, rels)
else: else:
changes+=function(node.child) changes += function(node.child)
elif node.kind==parser.BINARY: elif node.kind == parser.BINARY:
if rels!=None: if rels != None:
changes+=function(node.right,rels) changes += function(node.right, rels)
changes+=function(node.left,rels) changes += function(node.left, rels)
else: else:
changes+=function(node.right) changes += function(node.right)
changes+=function(node.left) changes += function(node.left)
return changes return changes
@ -100,20 +103,21 @@ def duplicated_select(n):
the 2nd one with a single select with both conditions the 2nd one with a single select with both conditions
in and in and
''' '''
changes=0 changes = 0
if n.name==SELECTION and n.child.name==SELECTION: if n.name == SELECTION and n.child.name == SELECTION:
if n.prop != n.child.prop: #Nested but different, joining them if n.prop != n.child.prop: # Nested but different, joining them
n.prop = n.prop + " and " + n.child.prop 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('('): if n.child.prop.startswith('(') or n.prop.startswith('('):
n.prop= '(%s)' % n.prop n.prop = '(%s)' % n.prop
n.child=n.child.child n.child = n.child.child
changes=1 changes = 1
changes+=duplicated_select(n) changes += duplicated_select(n)
return changes + recoursive_scan(duplicated_select, n)
return changes+recoursive_scan(duplicated_select,n)
def futile_union_intersection_subtraction(n): def futile_union_intersection_subtraction(n):
'''This function locates things like r r, and replaces them with r. '''This function locates things like r r, and replaces them with r.
@ -126,105 +130,109 @@ def futile_union_intersection_subtraction(n):
σ k (R) R --> σ k (R) σ k (R) R --> σ k (R)
''' '''
changes=0 changes = 0
#Union and intersection of the same thing # Union and intersection of the same thing
if n.name in (UNION,INTERSECTION) and n.left==n.right: if n.name in (UNION, INTERSECTION) and n.left == n.right:
changes=1 changes = 1
replace_node(n,n.left) replace_node(n, n.left)
#selection and union of the same thing # selection and union of the same thing
elif (n.name == UNION): elif (n.name == UNION):
if n.left.name==SELECTION and n.left.child==n.right: if n.left.name == SELECTION and n.left.child == n.right:
changes=1 changes = 1
replace_node(n,n.right) replace_node(n, n.right)
elif n.right.name==SELECTION and n.right.child==n.left: elif n.right.name == SELECTION and n.right.child == n.left:
changes=1 changes = 1
replace_node(n,n.left) replace_node(n, n.left)
#selection and intersection of the same thing # selection and intersection of the same thing
elif n.name == INTERSECTION: elif n.name == INTERSECTION:
if n.left.name==SELECTION and n.left.child==n.right: if n.left.name == SELECTION and n.left.child == n.right:
changes=1 changes = 1
replace_node(n,n.left) replace_node(n, n.left)
elif n.right.name==SELECTION and n.right.child==n.left: elif n.right.name == SELECTION and n.right.child == n.left:
changes=1 changes = 1
replace_node(n,n.right) replace_node(n, n.right)
#Subtraction and selection of the same thing # 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 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.name = n.right.name
n.kind=n.right.kind n.kind = n.right.kind
n.child=n.right.child n.child = n.right.child
n.prop='(not (%s))' % n.right.prop n.prop = '(not (%s))' % n.right.prop
n.left=n.right=None n.left = n.right = None
#Subtraction of the same thing or with selection on the left child # 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 elif (n.name == DIFFERENCE and ((n.left == n.right) or (n.left.name == SELECTION and n.left.child == n.right))): # Empty relation
changes=1 changes = 1
n.kind=parser.UNARY n.kind = parser.UNARY
n.name=SELECTION n.name = SELECTION
n.prop='False' n.prop = 'False'
n.child=n.left.get_left_leaf() n.child = n.left.get_left_leaf()
#n.left=n.right=None # n.left=n.right=None
return changes + recoursive_scan(futile_union_intersection_subtraction, n)
return changes+recoursive_scan(futile_union_intersection_subtraction,n)
def down_to_unions_subtractions_intersections(n): def down_to_unions_subtractions_intersections(n):
'''This funcion locates things like σ i==2 (c d), where the union '''This funcion locates things like σ i==2 (c d), where the union
can be a subtraction and an intersection and replaces them with 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 changes = 0
_o=(UNION,DIFFERENCE,INTERSECTION) _o = (UNION, DIFFERENCE, INTERSECTION)
if n.name==SELECTION and n.child.name in _o: if n.name == SELECTION and n.child.name in _o:
left=parser.node() left = parser.node()
left.prop=n.prop left.prop = n.prop
left.name=n.name left.name = n.name
left.child=n.child.left left.child = n.child.left
left.kind=parser.UNARY left.kind = parser.UNARY
right=parser.node() right = parser.node()
right.prop=n.prop right.prop = n.prop
right.name=n.name right.name = n.name
right.child=n.child.right right.child = n.child.right
right.kind=parser.UNARY right.kind = parser.UNARY
n.name=n.child.name n.name = n.child.name
n.left=left n.left = left
n.right=right n.right = right
n.child=None n.child = None
n.prop=None n.prop = None
n.kind=parser.BINARY n.kind = parser.BINARY
changes+=1 changes += 1
return changes + recoursive_scan(down_to_unions_subtractions_intersections, n)
return changes+recoursive_scan(down_to_unions_subtractions_intersections,n)
def duplicated_projection(n): def duplicated_projection(n):
'''This function locates thing like π i ( π j (R)) and replaces '''This function locates thing like π i ( π j (R)) and replaces
them with π i (R)''' them with π i (R)'''
changes=0 changes = 0
if n.name==PROJECTION and n.child.name==PROJECTION: if n.name == PROJECTION and n.child.name == PROJECTION:
n.child=n.child.child n.child = n.child.child
changes+=1 changes += 1
return changes + recoursive_scan(duplicated_projection, n)
return changes+recoursive_scan(duplicated_projection,n)
def selection_inside_projection(n): def selection_inside_projection(n):
'''This function locates things like σ j (π k(R)) and '''This function locates things like σ j (π k(R)) and
converts them into π k(σ j (R))''' converts them into π k(σ j (R))'''
changes=0 changes = 0
if n.name==SELECTION and n.child.name==PROJECTION: if n.name == SELECTION and n.child.name == PROJECTION:
changes=1 changes = 1
temp=n.prop temp = n.prop
n.prop=n.child.prop n.prop = n.child.prop
n.child.prop=temp n.child.prop = temp
n.name=PROJECTION n.name = PROJECTION
n.child.name=SELECTION n.child.name = SELECTION
return changes + recoursive_scan(selection_inside_projection, n)
return changes+recoursive_scan(selection_inside_projection,n)
def swap_union_renames(n): def swap_union_renames(n):
'''This function locates things like '''This function locates things like
@ -232,70 +240,73 @@ def swap_union_renames(n):
and replaces them with and replaces them with
ρ ab(R Q). ρ ab(R Q).
Does the same with subtraction and intersection''' Does the same with subtraction and intersection'''
changes=0 changes = 0
if n.name in (DIFFERENCE,UNION,INTERSECTION) and n.left.name==n.right.name and n.left.name==RENAME: if n.name in (DIFFERENCE, UNION, INTERSECTION) and n.left.name == n.right.name and n.left.name == RENAME:
l_vars={} l_vars = {}
for i in n.left.prop.split(','): for i in n.left.prop.split(','):
q=i.split(ARROW) q = i.split(ARROW)
l_vars[q[0].strip()]=q[1].strip() l_vars[q[0].strip()] = q[1].strip()
r_vars={} r_vars = {}
for i in n.right.prop.split(','): for i in n.right.prop.split(','):
q=i.split(ARROW) q = i.split(ARROW)
r_vars[q[0].strip()]=q[1].strip() r_vars[q[0].strip()] = q[1].strip()
if r_vars==l_vars: if r_vars == l_vars:
changes=1 changes = 1
#Copying self, but child will be child of renames # Copying self, but child will be child of renames
q=parser.node() q = parser.node()
q.name=n.name q.name = n.name
q.kind=parser.BINARY q.kind = parser.BINARY
q.left=n.left.child q.left = n.left.child
q.right=n.right.child q.right = n.right.child
n.name=RENAME n.name = RENAME
n.kind=parser.UNARY n.kind = parser.UNARY
n.child=q n.child = q
n.prop=n.left.prop n.prop = n.left.prop
n.left=n.right=None n.left = n.right = None
return changes + recoursive_scan(swap_union_renames, n)
return changes+recoursive_scan(swap_union_renames,n)
def futile_renames(n): def futile_renames(n):
'''This function purges renames like id->id''' '''This function purges renames like id->id'''
changes=0 changes = 0
if n.name==RENAME: if n.name == RENAME:
#Located two nested renames. # Located two nested renames.
changes=1 changes = 1
#Creating a dictionary with the attributes # Creating a dictionary with the attributes
_vars={} _vars = {}
for i in n.prop.split(','): for i in n.prop.split(','):
q=i.split(ARROW) q = i.split(ARROW)
_vars[q[0].strip()]=q[1].strip() _vars[q[0].strip()] = q[1].strip()
#Scans dictionary to locate things like "a->b,b->c" and replace them with "a->c" # Scans dictionary to locate things like "a->b,b->c" and replace them
# with "a->c"
for key in list(_vars.keys()): for key in list(_vars.keys()):
try: try:
value=_vars[key] value = _vars[key]
except: except:
value=None value = None
if key==value: if key == value:
_vars.pop(value) #Removes the unused one _vars.pop(value) # Removes the unused one
#Reset prop var # Reset prop var
n.prop="" n.prop = ""
#Generates new prop var # Generates new prop var
for i in _vars.items(): for i in _vars.items():
n.prop+=u"%s%s%s," % (i[0],ARROW,i[1]) n.prop += u"%s%s%s," % (i[0], ARROW, i[1])
n.prop=n.prop[:-1] #Removing ending comma n.prop = n.prop[:-1] # Removing ending comma
if len(n.prop)==0: #Nothing to rename, removing the rename op if len(n.prop) == 0: # Nothing to rename, removing the rename op
replace_node(n,n.child) replace_node(n, n.child)
return changes + recoursive_scan(futile_renames, n)
return changes+recoursive_scan(futile_renames,n)
def subsequent_renames(n): def subsequent_renames(n):
'''This function removes redoundant subsequent renames joining them into one''' '''This function removes redoundant subsequent renames joining them into one'''
@ -303,84 +314,87 @@ def subsequent_renames(n):
'''Purges renames like id->id Since it's needed to be performed BEFORE this 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''' so it is not in the list with the other optimizations'''
futile_renames(n) futile_renames(n)
changes=0 changes = 0
if n.name==RENAME and n.child.name==n.name: if n.name == RENAME and n.child.name == n.name:
#Located two nested renames. # Located two nested renames.
changes=1 changes = 1
#Joining the attribute into one # Joining the attribute into one
n.prop+=','+n.child.prop n.prop += ',' + n.child.prop
n.child=n.child.child n.child = n.child.child
#Creating a dictionary with the attributes # Creating a dictionary with the attributes
_vars={} _vars = {}
for i in n.prop.split(','): for i in n.prop.split(','):
q=i.split(ARROW) q = i.split(ARROW)
_vars[q[0].strip()]=q[1].strip() _vars[q[0].strip()] = q[1].strip()
#Scans dictionary to locate things like "a->b,b->c" and replace them with "a->c" # Scans dictionary to locate things like "a->b,b->c" and replace them
# with "a->c"
for key in list(_vars.keys()): for key in list(_vars.keys()):
try: try:
value=_vars[key] value = _vars[key]
except: except:
value=None value = None
if value in _vars.keys(): if value in _vars.keys():
if _vars[value]!=key: if _vars[value] != key:
#Double rename on attribute # Double rename on attribute
_vars[key] = _vars[_vars[key]] #Sets value _vars[key] = _vars[_vars[key]] # Sets value
_vars.pop(value) #Removes the unused one _vars.pop(value) # Removes the unused one
else: #Cycle rename a->b,b->a else: # Cycle rename a->b,b->a
_vars.pop(value) #Removes the unused one _vars.pop(value) # Removes the unused one
_vars.pop(key) #Removes the unused one _vars.pop(key) # Removes the unused one
#Reset prop var # Reset prop var
n.prop="" n.prop = ""
#Generates new prop var # Generates new prop var
for i in _vars.items(): for i in _vars.items():
n.prop+=u"%s%s%s," % (i[0],ARROW,i[1]) n.prop += u"%s%s%s," % (i[0], ARROW, i[1])
n.prop=n.prop[:-1] #Removing ending comma n.prop = n.prop[:-1] # Removing ending comma
if len(n.prop)==0: #Nothing to rename, removing the rename op if len(n.prop) == 0: # Nothing to rename, removing the rename op
replace_node(n,n.child) replace_node(n, n.child)
return changes + recoursive_scan(subsequent_renames, n)
return changes+recoursive_scan(subsequent_renames,n)
class level_string(str): class level_string(str):
level=0 level = 0
def tokenize_select(expression): def tokenize_select(expression):
'''This function returns the list of tokens present in a '''This function returns the list of tokens present in a
selection. The expression can contain parenthesis. selection. The expression can contain parenthesis.
It will use a subclass of str with the attribute level, which It will use a subclass of str with the attribute level, which
will specify the nesting level of the token into parenthesis.''' will specify the nesting level of the token into parenthesis.'''
g=generate_tokens(StringIO(str(expression)).readline) g = generate_tokens(StringIO(str(expression)).readline)
l=list(token[1] for token in g) l = list(token[1] for token in g)
l.remove('') 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: try:
while True: while True:
dot=l.index('.') dot = l.index('.')
l[dot]='%s.%s' % (l[dot-1],l[dot+1]) l[dot] = '%s.%s' % (l[dot - 1], l[dot + 1])
l.pop(dot+1) l.pop(dot + 1)
l.pop(dot-1) l.pop(dot - 1)
except: except:
pass pass
level = 0
level=0
for i in range(len(l)): for i in range(len(l)):
l[i]=level_string(l[i]) l[i] = level_string(l[i])
l[i].level=level l[i].level = level
if l[i]=='(': if l[i] == '(':
level+=1 level += 1
elif l[i]==')': elif l[i] == ')':
level-=1 level -= 1
return l return l
def swap_rename_projection(n): def swap_rename_projection(n):
'''This function locates things like π k(ρ j(R)) '''This function locates things like π k(ρ j(R))
and replaces them with ρ j(π k(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. and more important, will hopefully allow further optimizations.
Will also eliminate fields in the rename that are cutted in the projection. Will also eliminate fields in the rename that are cutted in the projection.
''' '''
changes=0 changes = 0
if n.name==PROJECTION and n.child.name==RENAME: if n.name == PROJECTION and n.child.name == RENAME:
changes=1 changes = 1
#π index,name(ρ id➡index(R)) # π index,name(ρ id➡index(R))
_vars={} _vars = {}
for i in n.child.prop.split(','): for i in n.child.prop.split(','):
q=i.split(ARROW) q = i.split(ARROW)
_vars[q[1].strip()]=q[0].strip() _vars[q[1].strip()] = q[0].strip()
_pr=n.prop.split(',') _pr = n.prop.split(',')
for i in range(len(_pr)): for i in range(len(_pr)):
try: try:
_pr[i]=_vars[_pr[i].strip()] _pr[i] = _vars[_pr[i].strip()]
except: except:
pass pass
_pr_reborn=n.prop.split(',') _pr_reborn = n.prop.split(',')
for i in list(_vars.keys()): for i in list(_vars.keys()):
if i not in _pr_reborn: if i not in _pr_reborn:
_vars.pop(i) _vars.pop(i)
n.name=n.child.name n.name = n.child.name
n.prop='' n.prop = ''
for i in _vars.keys(): for i in _vars.keys():
n.prop+=u'%s%s%s,' % (_vars[i],ARROW,i) n.prop += u'%s%s%s,' % (_vars[i], ARROW, i)
n.prop=n.prop[:-1] n.prop = n.prop[:-1]
n.child.name=PROJECTION n.child.name = PROJECTION
n.child.prop='' n.child.prop = ''
for i in _pr: for i in _pr:
n.child.prop+=i+',' n.child.prop += i + ','
n.child.prop=n.child.prop[:-1] n.child.prop = n.child.prop[:-1]
return changes + recoursive_scan(swap_rename_projection, n)
return changes+recoursive_scan(swap_rename_projection,n)
def swap_rename_select(n): def swap_rename_select(n):
'''This function locates things like σ k(ρ j(R)) and replaces '''This function locates things like σ k(ρ j(R)) and replaces
them with ρ j(σ k(R)). Renaming the attributes used in the them with ρ j(σ k(R)). Renaming the attributes used in the
selection, so the operation is still valid.''' selection, so the operation is still valid.'''
changes=0 changes = 0
if n.name==SELECTION and n.child.name==RENAME: if n.name == SELECTION and n.child.name == RENAME:
changes=1 changes = 1
#Dictionary containing attributes of rename # Dictionary containing attributes of rename
_vars={} _vars = {}
for i in n.child.prop.split(','): for i in n.child.prop.split(','):
q=i.split(ARROW) q = i.split(ARROW)
_vars[q[1].strip()]=q[0].strip() _vars[q[1].strip()] = q[0].strip()
#tokenizes expression in select # tokenizes expression in select
_tokens=tokenize_select(n.prop) _tokens = tokenize_select(n.prop)
#Renaming stuff # Renaming stuff
for i in range(len(_tokens)): for i in range(len(_tokens)):
splitted=_tokens[i].split('.',1) splitted = _tokens[i].split('.', 1)
if splitted[0] in _vars: if splitted[0] in _vars:
if len(splitted)==1: if len(splitted) == 1:
_tokens[i]=_vars[_tokens[i].split('.')[0]] _tokens[i] = _vars[_tokens[i].split('.')[0]]
else: else:
_tokens[i]=_vars[_tokens[i].split('.')[0]]+'.'+splitted[1] _tokens[i] = _vars[
_tokens[i].split('.')[0]] + '.' + splitted[1]
#Swapping operators # Swapping operators
n.name=RENAME n.name = RENAME
n.child.name=SELECTION n.child.name = SELECTION
n.prop=n.child.prop n.prop = n.child.prop
n.child.prop='' n.child.prop = ''
for i in _tokens: for i in _tokens:
n.child.prop+=i+ ' ' n.child.prop += i + ' '
return changes + recoursive_scan(swap_rename_select, n)
return changes+recoursive_scan(swap_rename_select,n)
def select_union_intersect_subtract(n): def select_union_intersect_subtract(n):
'''This function locates things like σ i(a) σ q(a) '''This function locates things like σ i(a) σ q(a)
and replaces them with σ (i OR q) (a) and replaces them with σ (i OR q) (a)
Removing a O() operation like the union''' Removing a O() operation like the union'''
changes=0 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: 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 cahnges = 1
d={UNION:'or', INTERSECTION:'and', DIFFERENCE:'and not'} d = {UNION: 'or', INTERSECTION: 'and', DIFFERENCE: 'and not'}
op=d[n.name] op = d[n.name]
newnode=parser.node() newnode = parser.node()
if n.left.prop.startswith('(') or n.right.prop.startswith('('): if n.left.prop.startswith('(') or n.right.prop.startswith('('):
t_str='(' t_str = '('
if n.left.prop.startswith('('): if n.left.prop.startswith('('):
t_str+='(%s)' t_str += '(%s)'
else: else:
t_str+='%s' t_str += '%s'
t_str+=' %s ' t_str += ' %s '
if n.right.prop.startswith('('): if n.right.prop.startswith('('):
t_str+='(%s)' t_str += '(%s)'
else: else:
t_str+='%s' t_str += '%s'
t_str+=')' t_str += ')'
newnode.prop= t_str % (n.left.prop,op,n.right.prop) newnode.prop = t_str % (n.left.prop, op, n.right.prop)
else: else:
newnode.prop='%s %s %s' % (n.left.prop,op,n.right.prop) newnode.prop = '%s %s %s' % (n.left.prop, op, n.right.prop)
newnode.name=SELECTION newnode.name = SELECTION
newnode.child=n.left.child newnode.child = n.left.child
newnode.kind=parser.UNARY newnode.kind = parser.UNARY
replace_node(n,newnode) replace_node(n, newnode)
return changes+recoursive_scan(select_union_intersect_subtract,n) return changes + recoursive_scan(select_union_intersect_subtract, n)
def selection_and_product(n,rels):
def selection_and_product(n, rels):
'''This function locates things like σ k (R*Q) and converts them into '''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, σ 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''' i contains attributes belonging to Q and l contains attributes belonging to both'''
changes=0 changes = 0
if n.name==SELECTION and n.child.name in (PRODUCT,JOIN,JOIN_LEFT,JOIN_RIGHT,JOIN_FULL): 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) l_attr = n.child.left.result_format(rels)
r_attr=n.child.right.result_format(rels) r_attr = n.child.right.result_format(rels)
tokens=tokenize_select(n.prop) tokens = tokenize_select(n.prop)
groups=[] groups = []
temp=[] temp = []
for i in tokens: for i in tokens:
if i=='and' and i.level==0: if i == 'and' and i.level == 0:
groups.append(temp) groups.append(temp)
temp=[] temp = []
else: else:
temp.append(i) temp.append(i)
if len(temp)!=0: if len(temp) != 0:
groups.append(temp) groups.append(temp)
temp=[] temp = []
left=[] left = []
right=[] right = []
both=[] both = []
for i in groups: for i in groups:
l_fields=False #has fields in left? l_fields = False # has fields in left?
r_fields=False #has fields in left? r_fields = False # has fields in left?
for j in set(i).difference(sel_op): for j in set(i).difference(sel_op):
j=j.split('.')[0] j = j.split('.')[0]
if j in l_attr:#Field in left if j in l_attr: # Field in left
l_fields=True l_fields = True
if j in r_attr:#Field in right if j in r_attr: # Field in right
r_fields=True r_fields = True
if l_fields and r_fields:#Fields in both if l_fields and r_fields: # Fields in both
both.append(i) both.append(i)
elif l_fields: elif l_fields:
left.append(i) left.append(i)
elif r_fields: elif r_fields:
right.append(i) right.append(i)
else:#Unknown.. adding in both else: # Unknown.. adding in both
both.append(i) both.append(i)
#Preparing left selection # Preparing left selection
if len(left)>0: if len(left) > 0:
changes=1 changes = 1
l_node=parser.node() l_node = parser.node()
l_node.name=SELECTION l_node.name = SELECTION
l_node.kind=parser.UNARY l_node.kind = parser.UNARY
l_node.child=n.child.left l_node.child = n.child.left
l_node.prop='' l_node.prop = ''
n.child.left=l_node n.child.left = l_node
while len(left)>0: while len(left) > 0:
c=left.pop(0) c = left.pop(0)
for i in c: for i in c:
l_node.prop+=i+ ' ' l_node.prop += i + ' '
if len(left)>0: if len(left) > 0:
l_node.prop+=' and ' l_node.prop += ' and '
if '(' in l_node.prop: if '(' in l_node.prop:
l_node.prop='(%s)' % l_node.prop l_node.prop = '(%s)' % l_node.prop
#Preparing right selection # Preparing right selection
if len(right)>0: if len(right) > 0:
changes=1 changes = 1
r_node=parser.node() r_node = parser.node()
r_node.name=SELECTION r_node.name = SELECTION
r_node.prop='' r_node.prop = ''
r_node.kind=parser.UNARY r_node.kind = parser.UNARY
r_node.child=n.child.right r_node.child = n.child.right
n.child.right=r_node n.child.right = r_node
while len(right)>0: while len(right) > 0:
c=right.pop(0) c = right.pop(0)
for i in c: for i in c:
r_node.prop+=i+ ' ' r_node.prop += i + ' '
if len(right)>0: if len(right) > 0:
r_node.prop+=' and ' r_node.prop += ' and '
if '(' in r_node.prop: if '(' in r_node.prop:
r_node.prop='(%s)' % r_node.prop r_node.prop = '(%s)' % r_node.prop
#Changing main selection # Changing main selection
n.prop='' n.prop = ''
if len(both)!=0: if len(both) != 0:
while len(both)>0: while len(both) > 0:
c=both.pop(0) c = both.pop(0)
for i in c: for i in c:
n.prop+=i+ ' ' n.prop += i + ' '
if len(both)>0: if len(both) > 0:
n.prop+=' and ' n.prop += ' and '
if '(' in n.prop: if '(' in n.prop:
n.prop='(%s)' % n.prop n.prop = '(%s)' % n.prop
else:#No need for general select else: # No need for general select
replace_node(n,n.child) replace_node(n, n.child)
return changes+recoursive_scan(selection_and_product,n,rels) 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] general_optimizations = [
specific_optimizations=[selection_and_product] 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__": if __name__ == "__main__":
print tokenize_select("skill == 'C' and id % 2 == 0") print tokenize_select("skill == 'C' and id % 2 == 0")

@ -29,21 +29,22 @@ import optimizations
import parser import parser
#Stuff that was here before, keeping it for compatibility # Stuff that was here before, keeping it for compatibility
RELATION=parser.RELATION RELATION = parser.RELATION
UNARY=parser.UNARY UNARY = parser.UNARY
BINARY=parser.BINARY BINARY = parser.BINARY
b_operators=parser.b_operators b_operators = parser.b_operators
u_operators=parser.u_operators u_operators = parser.u_operators
op_functions=parser.op_functions op_functions = parser.op_functions
node=parser.node node = parser.node
tokenize=parser.tokenize tokenize = parser.tokenize
tree=parser.tree tree = parser.tree
#End of the stuff # 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. '''This function performs all the available optimizations.
expression : see documentation of this module expression : see documentation of this module
@ -55,34 +56,37 @@ def optimize_all(expression,rels,specific=True,general=True,debug=None):
steps. steps.
Return value: this will return an optimized version of the expression''' Return value: this will return an optimized version of the expression'''
if isinstance(expression,unicode): if isinstance(expression, unicode):
n=tree(expression) #Gets the tree n = tree(expression) # Gets the tree
elif isinstance(expression,node): elif isinstance(expression, node):
n=expression n = expression
else: else:
raise (TypeError("expression must be a unicode string or a node")) raise (TypeError("expression must be a unicode string or a node"))
if isinstance(debug,list): if isinstance(debug, list):
dbg=True dbg = True
else: else:
dbg=False dbg = False
total=1 total = 1
while total!=0: while total != 0:
total=0 total = 0
if specific: if specific:
for i in optimizations.specific_optimizations: for i in optimizations.specific_optimizations:
res=i(n,rels) #Performs the optimization res = i(n, rels) # Performs the optimization
if res!=0 and dbg: debug.append(n.__str__()) if res != 0 and dbg:
total+=res debug.append(n.__str__())
total += res
if general: if general:
for i in optimizations.general_optimizations: for i in optimizations.general_optimizations:
res=i(n) #Performs the optimization res = i(n) # Performs the optimization
if res!=0 and dbg: debug.append(n.__str__()) if res != 0 and dbg:
total+=res debug.append(n.__str__())
total += res
return n.__str__() return n.__str__()
def specific_optimize(expression,rels):
def specific_optimize(expression, rels):
'''This function performs specific optimizations. Means that it will need to '''This function performs specific optimizations. Means that it will need to
know the fields used by the relations. know the fields used by the relations.
@ -90,7 +94,8 @@ def specific_optimize(expression,rels):
rels: dic with relation name as key, and relation istance as value rels: dic with relation name as key, and relation istance as value
Return value: this will return an optimized version of the expression''' 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): def general_optimize(expression):
'''This function performs general optimizations. Means that it will not need to '''This function performs general optimizations. Means that it will not need to
@ -99,18 +104,19 @@ def general_optimize(expression):
expression : see documentation of this module expression : see documentation of this module
Return value: this will return an optimized version of the expression''' Return value: this will return an optimized version of the expression'''
return optimize_all(expression,None,specific=False,general=True) return optimize_all(expression, None, specific=False, general=True)
if __name__=="__main__": if __name__ == "__main__":
#n=node(u"((a b) - c d) - b") # n=node(u"((a b) - c d) - b")
#n=node(u"π a,b (d-a*b)") # n=node(u"π a,b (d-a*b)")
#print n.__str__() # print n.__str__()
#a= tokenize("(a - (a b) * π a,b (a-b)) - ρ 123 (a)") # a= tokenize("(a - (a b) * π a,b (a-b)) - ρ 123 (a)")
#a= tokenize(u"π a,b (a*b)") # a= tokenize(u"π a,b (a*b)")
#a=tokenize("(a-b*c)*(b-c)") # a=tokenize("(a-b*c)*(b-c)")
import relation,optimizations import relation
import optimizations
'''rels={} '''rels={}
rels["P1"]= relation.relation("/home/salvo/dev/relational/trunk/samples/people.csv") rels["P1"]= 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["D1"]= relation.relation("/home/salvo/dev/relational/trunk/samples/dates.csv")
rels["S1"]= relation.relation("/home/salvo/dev/relational/trunk/samples/skillo.csv") rels["S1"]= relation.relation("/home/salvo/dev/relational/trunk/samples/skillo.csv")
print rels''' print rels'''
n=tree(u"π indice,qq,name (ρ age➡qq,id➡indice (P1-P2))") 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("σ id==3 and indice==2 and name==5 or name<2(P1 * S1)")
print n print n
print n.toPython() 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 (ρ idi,agea(π id,age(people))*people)) ᐅᐊ skills) σ skill=='C' (π id,name,chief,age (σ chief==i and age>a (ρ idi,agea(π id,age(people))*people)) ᐅᐊ skills)
(π id,name,chief,age (σ chief == i and age > a ((ρ agea,idi (π id,age (people)))*people)))ᐅᐊ(σ skill == 'C' (skills)) (π id,name,chief,age (σ chief == i and age > a ((ρ agea,idi (π 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 specific_optimize("σ name==skill and age>21 and id==indice and
# skill=='C'(P1ᐅᐊS1)",rels)
#print n # print n
#print n.result_format(rels) # print n.result_format(rels)
'''σ k (r) r with r '''σ k (r) r with r
σ k (r) r with σ k (r)''' σ k (r) r with σ k (r)'''
#a=general_optimize('π indice,qq,name (ρ age➡qq,id➡indice (P1-P2))') # a=general_optimize('π indice,qq,name (ρ age➡qq,id➡indice (P1-P2))')
#a=general_optimize("σ i==2 (σ b>5 (d))") # a=general_optimize("σ i==2 (σ b>5 (d))")
#print a # print a
#print node(a) # print node(a)
#print tokenize("(a)") # print tokenize("(a)")

@ -23,89 +23,95 @@ import optimizer
import multiprocessing import multiprocessing
import parser import parser
def execute(tree,rels):
def execute(tree, rels):
'''This funcion executes a query in parallel. '''This funcion executes a query in parallel.
Tree is the tree describing the query (usually obtained with Tree is the tree describing the query (usually obtained with
parser.tree(querystring) parser.tree(querystring)
rels is a dictionary containing the relations associated with the names''' rels is a dictionary containing the relations associated with the names'''
q = multiprocessing.Queue() 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() p.start()
result= q.get() result = q.get()
p.join() p.join()
return result return result
def __p_exec__(tree,rels,q):
def __p_exec__(tree, rels, q):
'''q is the queue used for communication''' '''q is the queue used for communication'''
if tree.kind==parser.RELATION: if tree.kind == parser.RELATION:
q.put(rels[tree.name]) q.put(rels[tree.name])
elif tree.kind==parser.UNARY: elif tree.kind == parser.UNARY:
#Obtain the relation # Obtain the relation
temp_q = multiprocessing.Queue() temp_q = multiprocessing.Queue()
__p_exec__(tree.child,rels,temp_q) __p_exec__(tree.child, rels, temp_q)
rel=temp_q.get() rel = temp_q.get()
#Execute the query # Execute the query
result=__p_exec_unary__(tree,rel) result = __p_exec_unary__(tree, rel)
q.put(result) q.put(result)
elif tree.kind==parser.BINARY: elif tree.kind == parser.BINARY:
left_q = multiprocessing.Queue() 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_q = multiprocessing.Queue()
right_p = multiprocessing.Process(target=__p_exec__, args=(tree.right,rels,right_q,)) right_p = multiprocessing.Process(
target=__p_exec__, args=(tree.right, rels, right_q,))
# Spawn the children
#Spawn the children
left_p.start() left_p.start()
right_p.start() right_p.start()
#Get the left and right relations # Get the left and right relations
left= left_q.get() left = left_q.get()
right= right_q.get() right = right_q.get()
#Wait for the children to terminate # Wait for the children to terminate
left_p.join() left_p.join()
right_p.join() right_p.join()
result = __p_exec_binary__(tree,left,right) result = __p_exec_binary__(tree, left, right)
q.put(result) q.put(result)
return 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) return left.product(right)
elif tree.name=='-': elif tree.name == '-':
return left.difference(right) return left.difference(right)
elif tree.name=='': elif tree.name == '':
return left.union(right) return left.union(right)
elif tree.name=='': elif tree.name == '':
return left.intersection(right) return left.intersection(right)
elif tree.name=='÷': elif tree.name == '÷':
return left.division(right) return left.division(right)
elif tree.name=='ᐅᐊ': elif tree.name == 'ᐅᐊ':
return left.join(right) return left.join(right)
elif tree.name=='ᐅLEFTᐊ': elif tree.name == 'ᐅLEFTᐊ':
return left.outer_left(right) return left.outer_left(right)
elif tree.name=='ᐅRIGHTᐊ': elif tree.name == 'ᐅRIGHTᐊ':
return left.outer_right(right) return left.outer_right(right)
else: # tree.name=='ᐅFULLᐊ': else: # tree.name=='ᐅFULLᐊ':
return left.outer(right) return left.outer(right)
def __p_exec_unary__(tree,rel):
if tree.name=='π':#Projection def __p_exec_unary__(tree, rel):
tree.prop=tree.prop.replace(' ','').split(',') if tree.name == 'π': # Projection
result= rel.projection(tree.prop) tree.prop = tree.prop.replace(' ', '').split(',')
elif tree.name=="ρ": #Rename result = rel.projection(tree.prop)
#tree.prop='{\"%s\"}' % tree.prop.replace(',','\",\"').replace('➡','\":\"').replace(' ','') elif tree.name == "ρ": # Rename
d={} # tree.prop='{\"%s\"}' %
tree.prop=tree.prop.replace(' ','') # tree.prop.replace(',','\",\"').replace('➡','\":\"').replace(' ','')
d = {}
tree.prop = tree.prop.replace(' ', '')
for i in tree.prop.split(','): for i in tree.prop.split(','):
rename_=i.split('') rename_ = i.split('')
d[rename_[0]]=rename_[1] d[rename_[0]] = rename_[1]
result= rel.rename(d) result = rel.rename(d)
else: #Selection else: # Selection
result= rel.selection(tree.prop) result = rel.selection(tree.prop)
return result return result

@ -43,36 +43,44 @@
import re import re
import rtypes import rtypes
RELATION=0 RELATION = 0
UNARY=1 UNARY = 1
BINARY=2 BINARY = 2
PRODUCT=u'*' PRODUCT = u'*'
DIFFERENCE=u'-' DIFFERENCE = u'-'
UNION=u'' UNION = u''
INTERSECTION=u'' INTERSECTION = u''
DIVISION=u'÷' DIVISION = u'÷'
JOIN=u'ᐅᐊ' JOIN = u'ᐅᐊ'
JOIN_LEFT=u'ᐅLEFTᐊ' JOIN_LEFT = u'ᐅLEFTᐊ'
JOIN_RIGHT=u'ᐅRIGHTᐊ' JOIN_RIGHT = u'ᐅRIGHTᐊ'
JOIN_FULL=u'ᐅFULLᐊ' JOIN_FULL = u'ᐅFULLᐊ'
PROJECTION=u'π' PROJECTION = u'π'
SELECTION=u'σ' SELECTION = u'σ'
RENAME=u'ρ' RENAME = u'ρ'
ARROW=u'' ARROW = u''
b_operators=(PRODUCT,DIFFERENCE,UNION,INTERSECTION,DIVISION,JOIN,JOIN_LEFT,JOIN_RIGHT,JOIN_FULL) # List of binary operators b_operators = (PRODUCT, DIFFERENCE, UNION, INTERSECTION, DIVISION,
u_operators=(PROJECTION,SELECTION,RENAME) # List of unary operators 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 # 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): class TokenizerException (Exception):
pass pass
class ParserException (Exception): class ParserException (Exception):
pass pass
class node (object): class node (object):
'''This class is a node of a relational expression. Leaves are relations and internal nodes are operations. '''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. The kind property says if the node is a binary operator, unary operator or relation.
@ -84,26 +92,27 @@ class node (object):
the string with the props of the operation. the string with the props of the operation.
This class is used to convert an expression into python code.''' This class is used to convert an expression into python code.'''
kind=None kind = None
__hash__=None __hash__ = None
def __init__(self,expression=None): def __init__(self, expression=None):
'''Generates the tree from the tokenized expression '''Generates the tree from the tokenized expression
If no expression is specified then it will create an empty node''' 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 return
#If the list contains only a list, it will consider the lower level list. # If the list contains only a list, it will consider the lower level list.
#This will allow things like ((((((a))))) to work # This will allow things like ((((((a))))) to work
while len(expression)==1 and isinstance(expression[0],list): while len(expression) == 1 and isinstance(expression[0], list):
expression=expression[0] expression = expression[0]
#The list contains only 1 string. Means it is the name of a relation # The list contains only 1 string. Means it is the name of a relation
if len(expression)==1 and isinstance(expression[0],unicode): if len(expression) == 1 and isinstance(expression[0], unicode):
self.kind=RELATION self.kind = RELATION
self.name=expression[0] self.name = expression[0]
if not rtypes.is_valid_relation_name(self.name): 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 return
'''Expression from right to left, searching for binary operators '''Expression from right to left, searching for binary operators
@ -116,169 +125,178 @@ class node (object):
Since it searches for strings, and expressions into parenthesis are Since it searches for strings, and expressions into parenthesis are
within sub-lists, they won't be found here, ensuring that they will within sub-lists, they won't be found here, ensuring that they will
have highest priority.''' have highest priority.'''
for i in xrange(len(expression)-1,-1,-1): for i in xrange(len(expression) - 1, -1, -1):
if expression[i] in b_operators: #Binary operator if expression[i] in b_operators: # Binary operator
self.kind=BINARY self.kind = BINARY
self.name=expression[i] self.name = expression[i]
if len(expression[:i])==0: if len(expression[:i]) == 0:
raise ParserException(u"Expected left operand for '%s'" % self.name) raise ParserException(
u"Expected left operand for '%s'" % self.name)
if len(expression[i+1:])==0: if len(expression[i + 1:]) == 0:
raise ParserException(u"Expected right operand for '%s'" % self.name) raise ParserException(
u"Expected right operand for '%s'" % self.name)
self.left=node(expression[:i]) self.left = node(expression[:i])
self.right=node(expression[i+1:]) self.right = node(expression[i + 1:])
return return
'''Searches for unary operators, parsing from right to left''' '''Searches for unary operators, parsing from right to left'''
for i in xrange(len(expression)-1,-1,-1): for i in xrange(len(expression) - 1, -1, -1):
if expression[i] in u_operators: #Unary operator if expression[i] in u_operators: # Unary operator
self.kind=UNARY self.kind = UNARY
self.name=expression[i] self.name = expression[i]
if len(expression)<=i+2: if len(expression) <= i + 2:
raise ParserException(u"Expected more tokens in '%s'"%self.name) raise ParserException(
u"Expected more tokens in '%s'" % self.name)
self.prop=expression[1+i].strip() self.prop = expression[1 + i].strip()
self.child=node(expression[2+i]) self.child = node(expression[2 + i])
return return
raise ParserException(u"Unable to parse tokens") raise ParserException(u"Unable to parse tokens")
pass pass
def toCode(self): def toCode(self):
'''This method converts the tree into a python code object''' '''This method converts the tree into a python code object'''
code = self.toPython() code = self.toPython()
return compile(code,'<relational_expression>','eval') return compile(code, '<relational_expression>', 'eval')
def toPython(self): 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.''' will require the relation module to be executed.'''
if self.name in b_operators: 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: elif self.name in u_operators:
prop =self.prop prop = self.prop
#Converting parameters # Converting parameters
if self.name==PROJECTION: if self.name == PROJECTION:
prop='\"%s\"' % prop.replace(' ','').replace(',','\",\"') prop = '\"%s\"' % prop.replace(' ', '').replace(',', '\",\"')
elif self.name==RENAME: elif self.name == RENAME:
prop='{\"%s\"}' % prop.replace(',','\",\"').replace(ARROW,'\":\"').replace(' ','') prop = '{\"%s\"}' % prop.replace(
else: #Selection ',', '\",\"').replace(ARROW, '\":\"').replace(' ', '')
prop='\"%s\"' % prop else: # Selection
prop = '\"%s\"' % prop
return '%s.%s(%s)' % (self.child.toPython(),op_functions[self.name],prop) return '%s.%s(%s)' % (self.child.toPython(), op_functions[self.name], prop)
else: else:
return self.name return self.name
pass pass
def printtree(self,level=0):
'''returns a representation of the tree using indentation'''
r=''
for i in range(level):
r+=' '
r+=self.name
if self.name in b_operators:
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 def printtree(self, level=0):
'''returns a representation of the tree using indentation'''
r = ''
for i in range(level):
r += ' '
r += self.name
if self.name in b_operators:
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
def get_left_leaf(self): def get_left_leaf(self):
'''This function returns the leftmost leaf in the tree. It is needed by some optimizations.''' '''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 return self
elif self.kind==UNARY: elif self.kind == UNARY:
return self.child.get_left_leaf() return self.child.get_left_leaf()
elif self.kind==BINARY: elif self.kind == BINARY:
return self.left.get_left_leaf() 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. '''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 It requires a dictionary where keys are the names of the relations and the values are
the relation objects.''' the relation objects.'''
if rels==None: if rels == None:
return return
if self.kind==RELATION: if self.kind == RELATION:
return list(rels[self.name].header.attributes) 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) 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))) return list(set(self.left.result_format(rels)) - set(self.right.result_format(rels)))
elif self.name==PROJECTION: elif self.name == PROJECTION:
l=[] l = []
for i in self.prop.split(','): for i in self.prop.split(','):
l.append(i.strip()) l.append(i.strip())
return l return l
elif self.name==PRODUCT: elif self.name == PRODUCT:
return self.left.result_format(rels)+self.right.result_format(rels) return self.left.result_format(rels) + self.right.result_format(rels)
elif self.name==SELECTION: elif self.name == SELECTION:
return self.child.result_format(rels) return self.child.result_format(rels)
elif self.name==RENAME: elif self.name == RENAME:
_vars={} _vars = {}
for i in self.prop.split(','): for i in self.prop.split(','):
q=i.split(ARROW) q = i.split(ARROW)
_vars[q[0].strip()]=q[1].strip() _vars[q[0].strip()] = q[1].strip()
_fields=self.child.result_format(rels) _fields = self.child.result_format(rels)
for i in range(len(_fields)): for i in range(len(_fields)):
if _fields[i] in _vars: if _fields[i] in _vars:
_fields[i]=_vars[_fields[i]] _fields[i] = _vars[_fields[i]]
return _fields 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)))) 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): def __eq__(self, other):
if not (isinstance(other, node) and self.name == other.name and self.kind == other.kind):
return False return False
if self.kind==UNARY: if self.kind == UNARY:
if other.prop!=self.prop: if other.prop != self.prop:
return False return False
return self.child==other.child return self.child == other.child
if self.kind==BINARY: if self.kind == BINARY:
return self.left==other.left and self.right==other.right return self.left == other.left and self.right == other.right
return True return True
def __str__(self): def __str__(self):
if (self.kind==RELATION): if (self.kind == RELATION):
return self.name return self.name
elif (self.kind==UNARY): elif (self.kind == UNARY):
return self.name + " "+ self.prop+ " (" + self.child.__str__() +")" return self.name + " " + self.prop + " (" + self.child.__str__() + ")"
elif (self.kind==BINARY): elif (self.kind == BINARY):
if self.left.kind==RELATION: if self.left.kind == RELATION:
le=self.left.__str__() le = self.left.__str__()
else: else:
le="("+self.left.__str__()+")" le = "(" + self.left.__str__() + ")"
if self.right.kind==RELATION: if self.right.kind == RELATION:
re=self.right.__str__() re = self.right.__str__()
else: else:
re="("+self.right.__str__()+")" re = "(" + self.right.__str__() + ")"
return (le+ self.name +re) return (le + self.name + re)
def _find_matching_parenthesis(expression,start=0,openpar=u'(',closepar=u')'):
def _find_matching_parenthesis(expression, start=0, openpar=u'(', closepar=u')'):
'''This function returns the position of the matching '''This function returns the position of the matching
close parenthesis to the 1st open parenthesis found close parenthesis to the 1st open parenthesis found
starting from start (0 by default)''' starting from start (0 by default)'''
par_count=0 #Count of parenthesis par_count = 0 # Count of parenthesis
for i in range(start,len(expression)): for i in range(start, len(expression)):
if expression[i]==openpar: if expression[i] == openpar:
par_count+=1 par_count += 1
elif expression[i]==closepar: elif expression[i] == closepar:
par_count-=1 par_count -= 1
if par_count==0: if par_count == 0:
return i #Closing parenthesis of the parameter return i # Closing parenthesis of the parameter
def tokenize(expression): def tokenize(expression):
'''This function converts an expression into a list where '''This function converts an expression into a list where
every token of the expression is an item of a list. Expressions into every token of the expression is an item of a list. Expressions into
parenthesis will be converted into sublists.''' parenthesis will be converted into sublists.'''
if not isinstance(expression,unicode): if not isinstance(expression, unicode):
raise TokenizerException('expected 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 '''This is a state machine. Initial status is determined by the starting of the
expression. There are the following statuses: expression. There are the following statuses:
@ -291,8 +309,8 @@ def tokenize(expression):
sub-expression: this status is entered when finding a '(' and will be exited when finding a ')'. 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.''' means that the others open must be counted to determine which close is the right one.'''
expression=expression.strip() #Removes initial and endind spaces expression = expression.strip() # Removes initial and endind spaces
state=0 state = 0
''' '''
0 initial and useless 0 initial and useless
1 previous stuff was a relation 1 previous stuff was a relation
@ -301,61 +319,70 @@ def tokenize(expression):
4 previous stuff was a binary operator 4 previous stuff was a binary operator
''' '''
while len(expression)>0: while len(expression) > 0:
if expression.startswith('('): #Parenthesis state if expression.startswith('('): # Parenthesis state
state=2 state = 2
end=_find_matching_parenthesis(expression) end = _find_matching_parenthesis(expression)
if end==None: if end == None:
raise TokenizerException("Missing matching ')' in '%s'" %expression) raise TokenizerException(
#Appends the tokenization of the content of the parenthesis "Missing matching ')' in '%s'" % expression)
# Appends the tokenization of the content of the parenthesis
items.append(tokenize(expression[1:end])) items.append(tokenize(expression[1:end]))
#Removes the entire parentesis and content from the expression # Removes the entire parentesis and content from the expression
expression=expression[end+1:].strip() expression = expression[end + 1:].strip()
elif expression.startswith((u"σ",u"π",u"ρ")): #Unary 2 bytes elif expression.startswith((u"σ", u"π", u"ρ")): # Unary 2 bytes
items.append(expression[0:1]) #Adding operator in the top of the list items.append(expression[0:1])
expression=expression[1:].strip() #Removing operator from the expression #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 if expression.startswith('('): # Expression with parenthesis, so adding what's between open and close without tokenization
par=expression.find('(',_find_matching_parenthesis(expression)) par = expression.find(
else: #Expression without parenthesis, so adding what's between start and parenthesis as whole '(', _find_matching_parenthesis(expression))
par=expression.find('(') 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 items.append(expression[:par].strip())
expression=expression[par:].strip() #Removing parameter from the expression #Inserting parameter of the operator
elif expression.startswith((u"÷",u"",u"",u"*",u"-")): expression = expression[
par:].strip() # Removing parameter from the expression
elif expression.startswith((u"÷", u"", u"", u"*", u"-")):
items.append(expression[0]) items.append(expression[0])
expression=expression[1:].strip() #1 char from the expression expression = expression[1:].strip() # 1 char from the expression
state=4 state = 4
elif expression.startswith(u""): #Binary long elif expression.startswith(u""): # Binary long
i=expression.find(u"") i = expression.find(u"")
if i==-1: if i == -1:
raise TokenizerException(u"Expected ᐊ in %s" % (expression,)) raise TokenizerException(u"Expected ᐊ in %s" % (expression,))
items.append(expression[:i+1]) items.append(expression[:i + 1])
expression=expression[i+1:].strip() expression = expression[i + 1:].strip()
state=4 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 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)) raise TokenizerException(
else: #Relation (hopefully) "Unexpected '%c' in '%s'" % (expression[0], expression))
if state==1: #Previous was a relation, appending to the last token else: # Relation (hopefully)
i=items.pop() if state == 1: # Previous was a relation, appending to the last token
items.append(i+expression[0]) i = items.pop()
expression=expression[1:].strip() #1 char from the expression items.append(i + expression[0])
expression = expression[
1:].strip() # 1 char from the expression
else: else:
state=1 state = 1
items.append(expression[0]) items.append(expression[0])
expression=expression[1:].strip() #1 char from the expression expression = expression[
1:].strip() # 1 char from the expression
return items return items
def tree(expression): def tree(expression):
'''This function parses a relational algebra expression into a tree and returns '''This function parses a relational algebra expression into a tree and returns
the root node using the Node class defined in this module.''' the root node using the Node class defined in this module.'''
return node(tokenize(expression)) return node(tokenize(expression))
def parse(expr): 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. executable by eval function to get the result of the expression.
@ -388,12 +415,12 @@ def parse(expr):
''' '''
return tree(expr).toPython() return tree(expr).toPython()
if __name__=="__main__": if __name__ == "__main__":
while True: while True:
e=unicode(raw_input("Expression: "),'utf-8') e = unicode(raw_input("Expression: "), 'utf-8')
print parse(e) print parse(e)
#b=u"σ age>1 and skill=='C' (peopleᐅᐊskills)" # b=u"σ age>1 and skill=='C' (peopleᐅᐊskills)"
#print b[0] # print b[0]
#parse(b) # parse(b)
pass pass

@ -21,18 +21,21 @@
import parser import parser
class TypeException(Exception): class TypeException(Exception):
pass pass
class Query(object):
def __init__(self,query):
if not isinstance(query,unicode): class Query(object):
def __init__(self, query):
if not isinstance(query, unicode):
raise TypeException('Expected unicode') raise TypeException('Expected unicode')
self.query = query self.query = query
self.tree = parser.tree(query) self.tree = parser.tree(query)
#TODO self.query_code = parser # TODO self.query_code = parser
self.optimized = None self.optimized = None
self.optimized_query = None self.optimized_query = None

@ -23,37 +23,39 @@
from rtypes import * from rtypes import *
import csv import csv
class relation (object): class relation (object):
'''This objects defines a relation (as a group of consistent tuples) and operations '''This objects defines a relation (as a group of consistent tuples) and operations
A relation can be represented using a table A relation can be represented using a table
Calling an operation and providing a non relation parameter when it is expected will Calling an operation and providing a non relation parameter when it is expected will
result in a None value''' result in a None value'''
__hash__=None __hash__ = None
def __init__(self,filename=""): def __init__(self, filename=""):
'''Creates a relation, accepts a filename and then it will load the relation from '''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 that file. If no parameter is supplied an empty relation is created. Empty
relations are used in internal operations. relations are used in internal operations.
By default the file will be handled like a comma separated as described in By default the file will be handled like a comma separated as described in
RFC4180.''' RFC4180.'''
self._readonly=False self._readonly = False
if len(filename)==0:#Empty relation if len(filename) == 0: # Empty relation
self.content=set() self.content = set()
self.header=header([]) self.header = header([])
return return
#Opening file # Opening file
fp=file(filename) fp = file(filename)
reader=csv.reader(fp) #Creating a csv reader reader = csv.reader(fp) # Creating a csv reader
self.header=header(reader.next()) # read 1st line self.header = header(reader.next()) # read 1st line
self.content=set() self.content = set()
for i in reader.__iter__(): #Iterating rows for i in reader.__iter__(): # Iterating rows
self.content.add(tuple(i)) self.content.add(tuple(i))
#Closing file # Closing file
fp.close() fp.close()
def _make_writable(self): def _make_writable(self):
@ -61,169 +63,174 @@ class relation (object):
method will copy the content to make it writable too''' method will copy the content to make it writable too'''
if self._readonly: if self._readonly:
self.content=set(self.content) self.content = set(self.content)
self._readonly=False self._readonly = False
def save(self,filename): def save(self, filename):
'''Saves the relation in a file. By default will save using the csv '''Saves the relation in a file. By default will save using the csv
format as defined in RFC4180, but setting comma_separated to False, format as defined in RFC4180, but setting comma_separated to False,
it will use the old format with space separated values. it will use the old format with space separated values.
''' '''
fp=file(filename,'w') #Opening file in write mode fp = file(filename, 'w') # Opening file in write mode
writer=csv.writer(fp) #Creating csv writer writer = csv.writer(fp) # Creating csv writer
#It wants an iterable containing iterables # It wants an iterable containing iterables
head=(self.header.attributes,) head = (self.header.attributes,)
writer.writerows(head) writer.writerows(head)
#Writing content, already in the correct format # Writing content, already in the correct format
writer.writerows(self.content) writer.writerows(self.content)
fp.close() #Closing file fp.close() # Closing file
def _rearrange_(self,other): def _rearrange_(self, other):
'''If two relations share the same attributes in a different order, this method '''If two relations share the same attributes in a different order, this method
will use projection to make them have the same attributes' order. 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. internally.
Will return None if they don't share the same attributes''' Will return None if they don't share the same attributes'''
if (self.__class__!=other.__class__): if (self.__class__ != other.__class__):
return None return None
if self.header.sharedAttributes(other.header) == len(self.header.attributes) == len(other.header.attributes): if self.header.sharedAttributes(other.header) == len(self.header.attributes) == len(other.header.attributes):
return other.projection(list(self.header.attributes)) return other.projection(list(self.header.attributes))
return None return None
def _autocast(self,string): def _autocast(self, string):
'''Depending on the regexp matched by the string, '''Depending on the regexp matched by the string,
it will perform automatic casting''' it will perform automatic casting'''
tmpstring=rstring(string) tmpstring = rstring(string)
if len(tmpstring)>0 and tmpstring.isInt(): if len(tmpstring) > 0 and tmpstring.isInt():
return int(tmpstring) return int(tmpstring)
elif len(tmpstring)>0 and tmpstring.isFloat(): elif len(tmpstring) > 0 and tmpstring.isFloat():
return float(tmpstring) return float(tmpstring)
elif len(tmpstring)>0 and tmpstring.isDate(): elif len(tmpstring) > 0 and tmpstring.isDate():
return rdate(tmpstring) return rdate(tmpstring)
else: else:
return tmpstring return tmpstring
def selection(self,expr): def selection(self, expr):
'''Selection, expr must be a valid boolean expression, can contain field names, '''Selection, expr must be a valid boolean expression, can contain field names,
constant, math operations and boolean ones.''' constant, math operations and boolean ones.'''
attributes={} attributes = {}
newt=relation() newt = relation()
newt.header=header(list(self.header.attributes)) newt.header = header(list(self.header.attributes))
for i in self.content: 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)): 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: try:
if eval(expr,attributes): if eval(expr, attributes):
newt.content.add(i) newt.content.add(i)
except Exception,e: except Exception, e:
raise Exception("Failed to evaluate %s\n%s" % (expr,e.__str__())) raise Exception(
"Failed to evaluate %s\n%s" % (expr, e.__str__()))
return newt return newt
def product (self,other):
def product(self, other):
'''Cartesian product, attributes must be different to avoid collisions '''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. cause an exception.
It is possible to use rename on attributes and then use the product''' 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): if (self.__class__ != other.__class__)or(self.header.sharedAttributes(other.header) != 0):
raise Exception('Unable to perform product on relations with colliding attributes') raise Exception(
newt=relation() 'Unable to perform product on relations with colliding attributes')
newt.header=header(self.header.attributes+other.header.attributes) newt = relation()
newt.header = header(self.header.attributes + other.header.attributes)
for i in self.content: for i in self.content:
for j in other.content: for j in other.content:
newt.content.add(i+j) newt.content.add(i + j)
return newt return newt
def projection(self, * attributes):
def projection(self,* attributes):
'''Projection operator, takes many parameters, for each field to use. '''Projection operator, takes many parameters, for each field to use.
Can also use a single parameter with a list. Can also use a single parameter with a list.
Will delete duplicate items Will delete duplicate items
If an empty list or no parameters are provided, returns None''' If an empty list or no parameters are provided, returns None'''
#Parameters are supplied in a list, instead with multiple parameters # Parameters are supplied in a list, instead with multiple parameters
if isinstance(attributes[0],list): if isinstance(attributes[0], list):
attributes=attributes[0] attributes = attributes[0]
#Avoiding duplicated attributes # Avoiding duplicated attributes
attributes1=[] attributes1 = []
for i in attributes: for i in attributes:
if i not in attributes1: if i not in attributes1:
attributes1.append(i) attributes1.append(i)
attributes=attributes1 attributes = attributes1
ids=self.header.getAttributesId(attributes) ids = self.header.getAttributesId(attributes)
if len(ids)==0 or len(ids)!=len(attributes): if len(ids) == 0 or len(ids) != len(attributes):
raise Exception('Invalid attributes for projection') raise Exception('Invalid attributes for projection')
newt=relation() newt = relation()
#Create the header # Create the header
h=[] h = []
for i in ids: for i in ids:
h.append(self.header.attributes[i]) h.append(self.header.attributes[i])
newt.header=header(h) newt.header = header(h)
#Create the body # Create the body
for i in self.content: for i in self.content:
row=[] row = []
for j in ids: for j in ids:
row.append(i[j]) row.append(i[j])
newt.content.add(tuple(row)) newt.content.add(tuple(row))
return newt return newt
def rename(self,params): def rename(self, params):
'''Operation rename. Takes a dictionary '''Operation rename. Takes a dictionary
Will replace the itmem with its content. Will replace the itmem with its content.
For example if you want to rename a to b, provide {"a":"b"} For example if you want to rename a to b, provide {"a":"b"}
''' '''
result=[] result = []
newt=relation() newt = relation()
newt.header=header(list(self.header.attributes)) newt.header = header(list(self.header.attributes))
for old,new in params.iteritems(): for old, new in params.iteritems():
if (newt.header.rename(old,new)) == False: if (newt.header.rename(old, new)) == False:
raise Exception('Unable to find attribute: %s' % old) raise Exception('Unable to find attribute: %s' % old)
newt.content=self.content newt.content = self.content
newt._readonly=True newt._readonly = True
return newt return newt
def intersection(self,other): def intersection(self, other):
'''Intersection operation. The result will contain items present in both '''Intersection operation. The result will contain items present in both
operands. operands.
Will return an empty one if there are no common items. Will return an empty one if there are no common items.
Will return None if headers are different. Will return None if headers are different.
It is possible to use projection and rename to make headers match.''' It is possible to use projection and rename to make headers match.'''
other=self._rearrange_(other) #Rearranges attributes' order other = self._rearrange_(other) # Rearranges attributes' order
if (self.__class__!=other.__class__)or(self.header!=other.header): if (self.__class__ != other.__class__)or(self.header != other.header):
raise Exception('Unable to perform intersection on relations with different attributes') raise Exception(
newt=relation() 'Unable to perform intersection on relations with different attributes')
newt.header=header(list(self.header.attributes)) newt = relation()
newt.header = header(list(self.header.attributes))
newt.content=self.content.intersection(other.content) newt.content = self.content.intersection(other.content)
return newt return newt
def difference(self,other): def difference(self, other):
'''Difference operation. The result will contain items present in first '''Difference operation. The result will contain items present in first
operand but not in second one. operand but not in second one.
Will return an empty one if the second is a superset of first. Will return an empty one if the second is a superset of first.
Will return None if headers are different. Will return None if headers are different.
It is possible to use projection and rename to make headers match.''' It is possible to use projection and rename to make headers match.'''
other=self._rearrange_(other) #Rearranges attributes' order other = self._rearrange_(other) # Rearranges attributes' order
if (self.__class__!=other.__class__)or(self.header!=other.header): if (self.__class__ != other.__class__)or(self.header != other.header):
raise Exception('Unable to perform difference on relations with different attributes') raise Exception(
newt=relation() 'Unable to perform difference on relations with different attributes')
newt.header=header(list(self.header.attributes)) newt = relation()
newt.header = header(list(self.header.attributes))
newt.content=self.content.difference(other.content) newt.content = self.content.difference(other.content)
return newt return newt
def division(self,other):
def division(self, other):
'''Division operator '''Division operator
The division is a binary operation that is written as R ÷ S. The The division is a binary operation that is written as R ÷ S. The
result consists of the restrictions of tuples in R to the result consists of the restrictions of tuples in R to the
@ -232,9 +239,9 @@ class relation (object):
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 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 = list(
set(self.header.attributes) - set(other.header.attributes))
''' '''
Wikipedia defines the division as follows: Wikipedia defines the division as follows:
@ -249,36 +256,38 @@ class relation (object):
W is the result that we want 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)) 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 '''Union operation. The result will contain items present in first
and second operands. and second operands.
Will return an empty one if both are empty. Will return an empty one if both are empty.
Will not insert tuplicated items. Will not insert tuplicated items.
Will return None if headers are different. Will return None if headers are different.
It is possible to use projection and rename to make headers match.''' It is possible to use projection and rename to make headers match.'''
other=self._rearrange_(other) #Rearranges attributes' order other = self._rearrange_(other) # Rearranges attributes' order
if (self.__class__!=other.__class__)or(self.header!=other.header): if (self.__class__ != other.__class__)or(self.header != other.header):
raise Exception('Unable to perform union on relations with different attributes') raise Exception(
newt=relation() 'Unable to perform union on relations with different attributes')
newt.header=header(list(self.header.attributes)) newt = relation()
newt.header = header(list(self.header.attributes))
newt.content=self.content.union(other.content) newt.content = self.content.union(other.content)
return newt return newt
def thetajoin(self,other,expr):
def thetajoin(self, other, expr):
'''Defined as product and then selection with the given expression.''' '''Defined as product and then selection with the given expression.'''
return self.product(other).selection(expr) 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.''' '''Does a left and a right outer join and returns their union.'''
a=self.outer_right(other) a = self.outer_right(other)
b=self.outer_left(other) b = self.outer_left(other)
return a.union(b) 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 '''Outer right join. Considers self as left and param as right. If the
tuple has no corrispondence, empy attributes are filled with a "---" 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 string. This is due to the fact that empty string or a space would cause
@ -286,147 +295,148 @@ class relation (object):
Just like natural join, it works considering shared attributes.''' Just like natural join, it works considering shared attributes.'''
return other.outer_left(self) return other.outer_left(self)
def outer_left(self,other,swap=False): def outer_left(self, other, swap=False):
'''Outer left join. Considers self as left and param as right. If the '''Outer left join. Considers self as left and param as right. If the
tuple has no corrispondence, empty attributes are filled with a "---" 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 string. This is due to the fact that empty string or a space would cause
problems when saving the relation. problems when saving the relation.
Just like natural join, it works considering shared attributes.''' Just like natural join, it works considering shared attributes.'''
shared=[] shared = []
for i in self.header.attributes: for i in self.header.attributes:
if i in other.header.attributes: if i in other.header.attributes:
shared.append(i) shared.append(i)
newt=relation() #Creates the new relation newt = relation() # Creates the new relation
#Adds all the attributes of the 1st relation # Adds all the attributes of the 1st relation
newt.header=header(list(self.header.attributes)) newt.header = header(list(self.header.attributes))
#Adds all the attributes of the 2nd, when non shared # Adds all the attributes of the 2nd, when non shared
for i in other.header.attributes: for i in other.header.attributes:
if i not in shared: if i not in shared:
newt.header.attributes.append(i) newt.header.attributes.append(i)
#Shared ids of self # Shared ids of self
sid=self.header.getAttributesId(shared) sid = self.header.getAttributesId(shared)
#Shared ids of the other relation # Shared ids of the other relation
oid=other.header.getAttributesId(shared) oid = other.header.getAttributesId(shared)
#Non shared ids of the other relation # Non shared ids of the other relation
noid=[] noid = []
for i in range(len(other.header.attributes)): for i in range(len(other.header.attributes)):
if i not in oid: if i not in oid:
noid.append(i) noid.append(i)
for i in self.content: for i in self.content:
#Tuple partecipated to the join? # Tuple partecipated to the join?
added=False added = False
for j in other.content: for j in other.content:
match=True match = True
for k in range(len(sid)): 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: if match:
item=list(i) item = list(i)
for l in noid: for l in noid:
item.append(j[l]) item.append(j[l])
newt.content.add(tuple(item)) newt.content.add(tuple(item))
added=True added = True
#If it didn't partecipate, adds it # If it didn't partecipate, adds it
if not added: if not added:
item=list(i) item = list(i)
for l in range(len(noid)): for l in range(len(noid)):
item.append("---") item.append("---")
newt.content.add(tuple(item)) newt.content.add(tuple(item))
return newt return newt
def join(self,other): def join(self, other):
'''Natural join, joins on shared attributes (one or more). If there are no '''Natural join, joins on shared attributes (one or more). If there are no
shared attributes, it will behave as cartesian product.''' shared attributes, it will behave as cartesian product.'''
#List of attributes in common between the relations # List of attributes in common between the relations
shared=list(set(self.header.attributes).intersection(set(other.header.attributes))) shared = list(set(self.header.attributes)
.intersection(set(other.header.attributes)))
newt=relation() #Creates the new relation newt = relation() # Creates the new relation
#Adding to the headers all the fields, done like that because order is needed # Adding to the headers all the fields, done like that because order is
newt.header=header(list(self.header.attributes)) # needed
newt.header = header(list(self.header.attributes))
for i in other.header.attributes: for i in other.header.attributes:
if i not in shared: if i not in shared:
newt.header.attributes.append(i) newt.header.attributes.append(i)
#Shared ids of self # Shared ids of self
sid=self.header.getAttributesId(shared) sid = self.header.getAttributesId(shared)
#Shared ids of the other relation # Shared ids of the other relation
oid=other.header.getAttributesId(shared) oid = other.header.getAttributesId(shared)
#Non shared ids of the other relation # Non shared ids of the other relation
noid=[] noid = []
for i in range(len(other.header.attributes)): for i in range(len(other.header.attributes)):
if i not in oid: if i not in oid:
noid.append(i) noid.append(i)
for i in self.content: for i in self.content:
for j in other.content: for j in other.content:
match=True match = True
for k in range(len(sid)): 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: if match:
item=list(i) item = list(i)
for l in noid: for l in noid:
item.append(j[l]) item.append(j[l])
newt.content.add(tuple(item)) newt.content.add(tuple(item))
return newt return newt
def __eq__(self,other):
def __eq__(self, other):
'''Returns true if the relations are the same, ignoring order of items. '''Returns true if the relations are the same, ignoring order of items.
This operation is rather heavy, since it requires sorting and comparing.''' This operation is rather heavy, since it requires sorting and comparing.'''
other=self._rearrange_(other) #Rearranges attributes' order so can compare tuples directly other = self._rearrange_(
other) # Rearranges attributes' order so can compare tuples directly
if (self.__class__!=other.__class__)or(self.header!=other.header): if (self.__class__ != other.__class__)or(self.header != other.header):
return False #Both parameters must be a relation return False # Both parameters must be a relation
if set(self.header.attributes)!=set(other.header.attributes): if set(self.header.attributes) != set(other.header.attributes):
return False return False
# comparing content
return self.content == other.content
#comparing content
return self.content==other.content
def __str__(self): 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''' monospaced fonts'''
m_len=[] #Maximum lenght string m_len = [] # Maximum lenght string
for f in self.header.attributes: for f in self.header.attributes:
m_len.append(len(f)) m_len.append(len(f))
for f in self.content: for f in self.content:
col=0 col = 0
for i in f: for i in f:
if len(i)>m_len[col]: if len(i) > m_len[col]:
m_len[col]=len(i) m_len[col] = len(i)
col+=1 col += 1
res="" res = ""
for f in range(len(self.header.attributes)): 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: for r in self.content:
col=0 col = 0
res+="\n" res += "\n"
for i in r: for i in r:
res+="%s"% (i.ljust(2+m_len[col])) res += "%s" % (i.ljust(2 + m_len[col]))
col+=1 col += 1
return res return res
def update(self,expr,dic): def update(self, expr, dic):
'''Update, expr must be a valid boolean expression, can contain field names, '''Update, expr must be a valid boolean expression, can contain field names,
constant, math operations and boolean ones. constant, math operations and boolean ones.
This operation will change the relation itself instead of generating a new one, This operation will change the relation itself instead of generating a new one,
@ -435,104 +445,105 @@ class relation (object):
will be converted into a string. will be converted into a string.
Returns the number of affected rows.''' Returns the number of affected rows.'''
self._make_writable() self._make_writable()
affected=0 affected = 0
attributes={} attributes = {}
keys=dic.keys() #List of headers to modify keys = dic.keys() # List of headers to modify
f_ids=self.header.getAttributesId(keys) #List of indexes corresponding to keys f_ids = self.header.getAttributesId(
keys) # List of indexes corresponding to keys
#new_content=[] #New content of the relation # new_content=[] #New content of the relation
for i in self.content: for i in self.content:
for j in range(len(self.header.attributes)): 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])
if eval(expr,attributes): #If expr is true, changing the tuple if eval(expr, attributes): # If expr is true, changing the tuple
affected+=1 affected += 1
new_tuple=list(i) new_tuple = list(i)
#Deleting the tuple, instead of changing it, so other # Deleting the tuple, instead of changing it, so other
#relations can still point to the same list without # relations can still point to the same list without
#being affected. # being affected.
self.content.remove(i) self.content.remove(i)
for k in range(len(keys)): 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)) self.content.add(tuple(new_tuple))
return affected return affected
def insert(self,values): def insert(self, values):
'''Inserts a tuple in the relation. '''Inserts a tuple in the relation.
This function will not insert duplicate tuples. This function will not insert duplicate tuples.
All the values will be converted in string. All the values will be converted in string.
Will return the number of inserted rows.''' 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): if len(self.header.attributes) != len(values):
return 0 return 0
self._make_writable() self._make_writable()
#Creating list containing only strings # Creating list containing only strings
t=[] t = []
for i in values: for i in values:
t.append(str(i)) t.append(str(i))
prevlen=len(self.content) prevlen = len(self.content)
self.content.add(tuple(t)) self.content.add(tuple(t))
return len(self.content)-prevlen return len(self.content) - prevlen
def delete(self,expr): def delete(self, expr):
'''Delete, expr must be a valid boolean expression, can contain field names, '''Delete, expr must be a valid boolean expression, can contain field names,
constant, math operations and boolean ones. constant, math operations and boolean ones.
This operation will change the relation itself instead of generating a new one, This operation will change the relation itself instead of generating a new one,
deleting all the tuples that make expr true. deleting all the tuples that make expr true.
Returns the number of affected rows.''' Returns the number of affected rows.'''
self._make_writable() self._make_writable()
attributes={} attributes = {}
affected=len(self.content) affected = len(self.content)
new_content=set() #New content of the relation new_content = set() # New content of the relation
for i in self.content: for i in self.content:
for j in range(len(self.header.attributes)): 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])
if not eval(expr, attributes):
if not eval(expr,attributes): affected -= 1
affected-=1
new_content.add(i) new_content.add(i)
self.content=new_content self.content = new_content
return affected return affected
class header (object): class header (object):
'''This class defines the header of a relation. '''This class defines the header of a relation.
It is used within relations to know if requested operations are accepted''' It is used within relations to know if requested operations are accepted'''
#Since relations are mutalbe we explicitly block hashing them # Since relations are mutalbe we explicitly block hashing them
__hash__=None __hash__ = None
def __init__(self,attributes): def __init__(self, attributes):
'''Accepts a list with attributes' names. Names MUST be unique''' '''Accepts a list with attributes' names. Names MUST be unique'''
self.attributes=attributes self.attributes = attributes
for i in attributes: for i in attributes:
if not is_valid_relation_name(i): 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): def __repr__(self):
return "header(%s)" % (self.attributes.__repr__()) 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. '''Renames a field. Doesn't check if it is a duplicate.
Returns True if the field was renamed, False otherwise''' Returns True if the field was renamed, False otherwise'''
if not is_valid_relation_name(new): 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: try:
id_=self.attributes.index(old) id_ = self.attributes.index(old)
self.attributes[id_]=new self.attributes[id_] = new
except: except:
return False return False
return True return True
def sharedAttributes(self,other): def sharedAttributes(self, other):
'''Returns how many attributes this header has in common with a given one''' '''Returns how many attributes this header has in common with a given one'''
return len(set(self.attributes).intersection(set(other.attributes))) return len(set(self.attributes).intersection(set(other.attributes)))
@ -540,17 +551,17 @@ class header (object):
'''Returns String representation of the field's list''' '''Returns String representation of the field's list'''
return self.attributes.__str__() return self.attributes.__str__()
def __eq__(self,other): def __eq__(self, other):
return self.attributes==other.attributes return self.attributes == other.attributes
def __ne__(self,other):
return self.attributes!=other.attributes
def getAttributesId(self,param): def __ne__(self, other):
return self.attributes != other.attributes
def getAttributesId(self, param):
'''Returns a list with numeric index corresponding to field's name''' '''Returns a list with numeric index corresponding to field's name'''
res=[] res = []
for i in param: for i in param:
for j in range(len(self.attributes)): for j in range(len(self.attributes)):
if i==self.attributes[j]: if i == self.attributes[j]:
res.append(j) res.append(j)
return res return res

@ -24,25 +24,29 @@
import datetime import datetime
import re import re
class rstring (str): class rstring (str):
'''String subclass with some custom methods''' '''String subclass with some custom methods'''
def isInt(self): def isInt(self):
'''Returns true if the string represents an int number '''Returns true if the string represents an int number
it only considers as int numbers the strings matching it only considers as int numbers the strings matching
the following regexp: the following regexp:
r'^[\+\-]{0,1}[0-9]+$' 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 return False
else: else:
return True return True
def isFloat(self): def isFloat(self):
'''Returns true if the string represents a float number '''Returns true if the string represents a float number
it only considers as float numbers, the strings matching it only considers as float numbers, the strings matching
the following regexp: the following regexp:
r'^[\+\-]{0,1}[0-9]+(\.([0-9])+)?$' 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 return False
else: else:
return True return True
@ -58,23 +62,24 @@ class rstring (str):
except: except:
pass pass
r= re.match(r'^([0-9]{1,4})(\\|-|/)([0-9]{1,2})(\\|-|/)([0-9]{1,2})$',self) r = re.match(
if r==None: r'^([0-9]{1,4})(\\|-|/)([0-9]{1,2})(\\|-|/)([0-9]{1,2})$', self)
self._isdate=False if r == None:
self._date=None self._isdate = False
self._date = None
return False return False
try: #Any of the following operations can generate an exception, if it happens, we aren't dealing with a date 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)) year = int(r.group(1))
month=int(r.group(3)) month = int(r.group(3))
day=int(r.group(5)) day = int(r.group(5))
d=datetime.date(year,month,day) d = datetime.date(year, month, day)
self._isdate=True self._isdate = True
self._date=d self._date = d
return True return True
except: except:
self._isdate=False self._isdate = False
self._date=None self._date = None
return False return False
def getDate(self): def getDate(self):
@ -84,46 +89,59 @@ class rstring (str):
except: except:
self.isDate() self.isDate()
return self._date return self._date
class rdate (object):
'''Represents a 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 class rdate (object):
self.month=self.intdate.month
self.weekday=self.intdate.weekday() '''Represents a date'''
self.year=self.intdate.year
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
def __hash__(self): def __hash__(self):
return self.intdate.__hash__() return self.intdate.__hash__()
def __str__(self): def __str__(self):
return self.intdate.__str__() 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__()) return rdate(res.__str__())
def __eq__(self,other):
return self.intdate==other.intdate def __eq__(self, other):
def __ge__(self,other): return self.intdate == other.intdate
return self.intdate>=other.intdate
def __gt__ (self,other): def __ge__(self, other):
return self.intdate>other.intdate return self.intdate >= other.intdate
def __le__ (self,other):
return self.intdate<=other.intdate def __gt__(self, other):
def __lt__ (self,other): return self.intdate > other.intdate
return self.intdate<other.intdate
def __ne__(self,other): def __le__(self, other):
return self.intdate!=other.intdate return self.intdate <= other.intdate
def __sub__ (self,other):
return (self.intdate-other.intdate).days 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): def is_valid_relation_name(name):
'''Checks if a name is valid for a relation. '''Checks if a name is valid for a relation.
Returns boolean''' 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 return False
else: else:
return True return True

@ -23,6 +23,7 @@ import signal
import sys import sys
from relational import * from relational import *
def terminate(*a): def terminate(*a):
'''Restores the terminal and terminates''' '''Restores the terminal and terminates'''
curses.nocbreak() curses.nocbreak()
@ -32,48 +33,43 @@ def terminate(*a):
sys.exit(0) sys.exit(0)
def main(): def main():
global stdscr global stdscr
#Initializes the signal # Initializes the signal
signal.signal(signal.SIGINT,terminate) signal.signal(signal.SIGINT, terminate)
#Initialize locale, to print unicode chars # Initialize locale, to print unicode chars
locale.setlocale(locale.LC_ALL,"") locale.setlocale(locale.LC_ALL, "")
#Initializes curses # Initializes curses
stdscr = curses.initscr() stdscr = curses.initscr()
curses.start_color() curses.start_color()
curses.noecho() 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) stdscr.keypad(1)
termsize=stdscr.getmaxyx() termsize = stdscr.getmaxyx()
symselect=init_symbol_list(termsize) symselect = init_symbol_list(termsize)
lop=curses.panel.new_panel(stdscr) lop = curses.panel.new_panel(stdscr)
win=curses.panel.new_panel(curses.newwin(termsize[0],termsize[1])) 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().box()
win.window().addstr(0,(termsize[1]/2)-5,"Relational")
win.window().refresh() win.window().refresh()
#curses.napms(1000) # curses.napms(1000)
query = curses.panel.new_panel(curses.newwin(3, termsize[1], 1, 0))
query=curses.panel.new_panel(curses.newwin(3,termsize[1],1,0))
query.window().box() query.window().box()
query.window().addstr(1,1,"") query.window().addstr(1, 1, "")
query.window().refresh() query.window().refresh()
#curses.napms(1000) # curses.napms(1000)
#win.show() # win.show()
#curses.napms(1000) # curses.napms(1000)
#qq=curses.textpad.Textbox(stdscr)
# qq=curses.textpad.Textbox(stdscr)
'''win = curses.newwin(0, 0)#New windows for the entire screen '''win = curses.newwin(0, 0)#New windows for the entire screen
#stdscr.border(0) #stdscr.border(0)
stdscr.addstr(str(dir (win))) stdscr.addstr(str(dir (win)))
@ -89,59 +85,62 @@ def main():
curses.flash() curses.flash()
curses.textpad.rectangle(win,0,0,5,10)''' curses.textpad.rectangle(win,0,0,5,10)'''
squery='' squery = ''
while True: while True:
c = win.window().getch() c = win.window().getch()
if c==27: #Escape if c == 27: # Escape
squery+=add_symbol(symselect) squery += add_symbol(symselect)
# elif c==curses.KEY_BACKSPACE: #Delete
#elif c==curses.KEY_BACKSPACE: #Delete elif c == 13:
elif c==13: squery = squery[:-1]
squery=squery[:-1]
else: else:
squery+=chr(c); squery += chr(c)
query.window().box() query.window().box()
query.top() query.top()
query.window().addstr(1,1,spaces(termsize[1]-2)) query.window().addstr(1, 1, spaces(termsize[1] - 2))
query.window().addstr(1,1,squery) query.window().addstr(1, 1, squery)
query.window().refresh() query.window().refresh()
def init_symbol_list(termsize,create=True):
def init_symbol_list(termsize, create=True):
if create: 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: else:
p=termsize p = termsize
p.window().box() p.window().box()
#p.window().addstr(1,1,"\n8 \na \nb \n") # p.window().addstr(1,1,"\n8 \na \nb \n")
p.window().addstr(01,2,"0 *") p.window().addstr(01, 2, "0 *")
p.window().addstr(02,2,"1 -") p.window().addstr(02, 2, "1 -")
p.window().addstr(03,2,"2 ") p.window().addstr(03, 2, "2 ")
p.window().addstr(04,2,"3 ᑎ") p.window().addstr(04, 2, "3 ᑎ")
p.window().addstr(05,2,"4 ᐅᐊ") p.window().addstr(05, 2, "4 ᐅᐊ")
p.window().addstr(06,2,"5 ᐅLEFTᐊ") p.window().addstr(06, 2, "5 ᐅLEFTᐊ")
p.window().addstr(07,2,"6 ᐅRIGHTᐊ") p.window().addstr(07, 2, "6 ᐅRIGHTᐊ")
p.window().addstr( 8,2,"7 ᐅFULLᐊ") p.window().addstr(8, 2, "7 ᐅFULLᐊ")
p.window().addstr( 9,2,"8 σ") p.window().addstr(9, 2, "8 σ")
p.window().addstr(10,2,"9 ρ") p.window().addstr(10, 2, "9 ρ")
p.window().addstr(11,2,"a π") p.window().addstr(11, 2, "a π")
p.window().addstr(12,2,"b ➡") p.window().addstr(12, 2, "b ➡")
p.window().addstr(13,2,"") p.window().addstr(13, 2, "")
#p.hide() # p.hide()
return p return p
def add_symbol(p): def add_symbol(p):
'''Shows the panel to add a symbol '''Shows the panel to add a symbol
and then returns the choosen symbol itself''' and then returns the choosen symbol itself'''
init_symbol_list(p,False) init_symbol_list(p, False)
d_={'0':'*','1':'-','2':'','3':'','4':'ᐅᐊ','5':'ᐅLEFTᐊ','6':'ᐅRIGHTᐊ','7':'ᐅFULLᐊ','8':'σ','9':'ρ','a':'π','b':''}
d_ = {'0': '*', '1': '-', '2': '', '3': '', '4': 'ᐅᐊ', '5': 'ᐅLEFTᐊ',
'6': 'ᐅRIGHTᐊ', '7': 'ᐅFULLᐊ', '8': 'σ', '9': 'ρ', 'a': 'π', 'b': ''}
p.show() p.show()
p.top() p.top()
@ -151,17 +150,18 @@ def add_symbol(p):
p.hide() p.hide()
p.window().refresh() p.window().refresh()
try: try:
char=d_[chr(c)] char = d_[chr(c)]
except: except:
char='' char = ''
return char return char
def spaces(t): def spaces(t):
'''Returns a number of spaces specified t''' '''Returns a number of spaces specified t'''
s='' s = ''
for i in range(t): for i in range(t):
s+=' ' s += ' '
return s return s
if __name__=='__main__': if __name__ == '__main__':
main() main()
terminate() terminate()

@ -24,7 +24,7 @@ import os
import os.path import os.path
import getopt import getopt
from relational import relation, parser from relational import relation, parser
version="1.2" version = "1.2"
def printver(exit=True): def printver(exit=True):
@ -42,6 +42,7 @@ def printver(exit=True):
if exit: if exit:
sys.exit(0) sys.exit(0)
def printhelp(code=0): def printhelp(code=0):
print "Relational" print "Relational"
print print
@ -60,65 +61,63 @@ def printhelp(code=0):
if __name__ == "__main__": if __name__ == "__main__":
if sys.argv[0].endswith('relational-cli'): if sys.argv[0].endswith('relational-cli'):
x11=False x11 = False
else: else:
x11=True #Will try to use the x11 interface x11 = True # Will try to use the x11 interface
#Getting command line # Getting command line
try: try:
switches,files=getopt.getopt(sys.argv[1:],"vhqr") switches, files = getopt.getopt(sys.argv[1:], "vhqr")
except: except:
printhelp(1) printhelp(1)
for i in switches: for i in switches:
if i[0]=='-v': if i[0] == '-v':
printver() printver()
elif i[0]=='-h': elif i[0] == '-h':
printhelp() printhelp()
elif i[0]=='-q': elif i[0] == '-q':
x11=True x11 = True
elif i[0]=='-r': elif i[0] == '-r':
x11=False x11 = False
if x11: if x11:
pyqt=True pyqt = True
try: try:
import sip #needed on windows import sip # needed on windows
from PyQt4 import QtGui from PyQt4 import QtGui
except: except:
print >> sys.stderr, "PyQt seems to be missing, trying to use Pyside" print >> sys.stderr, "PyQt seems to be missing, trying to use Pyside"
from PySide import QtCore, QtGui from PySide import QtCore, QtGui
pyqt=False pyqt = False
if pyqt: if pyqt:
try: try:
from relational_gui import maingui,guihandler, about, surveyForm from relational_gui import maingui, guihandler, about, surveyForm
except: except:
print >> sys.stderr, "Module relational_gui is missing.\nPlease install relational package." print >> sys.stderr, "Module relational_gui is missing.\nPlease install relational package."
sys.exit(3) sys.exit(3)
else: else:
try: try:
from relational_pyside import maingui,guihandler, about, surveyForm from relational_pyside import maingui, guihandler, about, surveyForm
except: except:
print >> sys.stderr, "Module relational_pyside is missing.\nPlease install relational package." print >> sys.stderr, "Module relational_pyside is missing.\nPlease install relational package."
sys.exit(3) sys.exit(3)
about.version = version
about.version=version surveyForm.version = version
surveyForm.version=version guihandler.version = version
guihandler.version=version
app = QtGui.QApplication(sys.argv) app = QtGui.QApplication(sys.argv)
app.setOrganizationName('None'); app.setOrganizationName('None')
app.setApplicationName('relational'); app.setApplicationName('relational')
ui = maingui.Ui_MainWindow() ui = maingui.Ui_MainWindow()
Form = guihandler.relForm(ui) Form = guihandler.relForm(ui)
#if os.name=='nt': # if os.name=='nt':
Form.setFont(QtGui.QFont("Dejavu Sans Bold")) Form.setFont(QtGui.QFont("Dejavu Sans Bold"))
ui.setupUi(Form) ui.setupUi(Form)
@ -128,12 +127,12 @@ if __name__ == "__main__":
if not os.path.isfile(files[i]): if not os.path.isfile(files[i]):
print >> sys.stderr, "%s is not a file" % files[i] print >> sys.stderr, "%s is not a file" % files[i]
printhelp(12) printhelp(12)
f=files[i].split('/') f = files[i].split('/')
defname=f[len(f)-1].lower() defname = f[len(f) - 1].lower()
if defname.endswith(".csv"): #removes the extension if defname.endswith(".csv"): # removes the extension
defname=defname[:-4] defname = defname[:-4]
print 'Loading file "%s" with name "%s"' % (files[i],defname) print 'Loading file "%s" with name "%s"' % (files[i], defname)
Form.loadRelation(files[i],defname) Form.loadRelation(files[i], defname)
Form.show() Form.show()
sys.exit(app.exec_()) sys.exit(app.exec_())
@ -144,6 +143,5 @@ if __name__ == "__main__":
except: except:
print >> sys.stderr, "Module relational_readline is missing.\nPlease install relational-cli package." print >> sys.stderr, "Module relational_readline is missing.\nPlease install relational-cli package."
sys.exit(3) sys.exit(3)
relational_readline.linegui.version=version relational_readline.linegui.version = version
relational_readline.linegui.main(files) relational_readline.linegui.main(files)

@ -21,32 +21,34 @@ import os
try: try:
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
try: #If QtWebKit is available, uses it try: # If QtWebKit is available, uses it
from PyQt4 import QtWebKit from PyQt4 import QtWebKit
webk=True webk = True
except: except:
webk=False webk = False
except: except:
from PySide import QtCore, QtGui from PySide import QtCore, QtGui
try: #If QtWebKit is available, uses it try: # If QtWebKit is available, uses it
from PySide import QtWebKit from PySide import QtWebKit
webk=True webk = True
except: except:
webk=False webk = False
version = 0
version=0
class Ui_Dialog(object): class Ui_Dialog(object):
def setupUi(self, Dialog): def setupUi(self, Dialog):
Dialog.setObjectName("Dialog") Dialog.setObjectName("Dialog")
Dialog.resize(510,453) Dialog.resize(510, 453)
self.verticalLayout_2 = QtGui.QVBoxLayout(Dialog) self.verticalLayout_2 = QtGui.QVBoxLayout(Dialog)
self.verticalLayout_2.setObjectName("verticalLayout_2") self.verticalLayout_2.setObjectName("verticalLayout_2")
self.tabWidget = QtGui.QTabWidget(Dialog) self.tabWidget = QtGui.QTabWidget(Dialog)
self.tabWidget.setObjectName("tabWidget") self.tabWidget.setObjectName("tabWidget")
self.tab = QtGui.QWidget() 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.tab.setObjectName("tab")
self.verticalLayout_3 = QtGui.QVBoxLayout(self.tab) self.verticalLayout_3 = QtGui.QVBoxLayout(self.tab)
self.verticalLayout_3.setObjectName("verticalLayout_3") self.verticalLayout_3.setObjectName("verticalLayout_3")
@ -80,30 +82,32 @@ class Ui_Dialog(object):
self.label_4.setObjectName("label_4") self.label_4.setObjectName("label_4")
self.verticalLayout_6.addWidget(self.label_4) self.verticalLayout_6.addWidget(self.label_4)
self.verticalLayout_3.addWidget(self.groupBox_2) self.verticalLayout_3.addWidget(self.groupBox_2)
self.tabWidget.addTab(self.tab,"") self.tabWidget.addTab(self.tab, "")
self.License = QtGui.QWidget() 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.License.setObjectName("License")
self.verticalLayout = QtGui.QVBoxLayout(self.License) self.verticalLayout = QtGui.QVBoxLayout(self.License)
self.verticalLayout.setObjectName("verticalLayout") self.verticalLayout.setObjectName("verticalLayout")
self.textEdit = QtGui.QTextEdit(self.License) self.textEdit = QtGui.QTextEdit(self.License)
self.textEdit.setObjectName("textEdit") self.textEdit.setObjectName("textEdit")
self.verticalLayout.addWidget(self.textEdit) self.verticalLayout.addWidget(self.textEdit)
self.tabWidget.addTab(self.License,"") self.tabWidget.addTab(self.License, "")
self.tab_2 = QtGui.QWidget() self.tab_2 = QtGui.QWidget()
self.tab_2.setObjectName("tab_2") self.tab_2.setObjectName("tab_2")
self.verticalLayout_7 = QtGui.QVBoxLayout(self.tab_2) self.verticalLayout_7 = QtGui.QVBoxLayout(self.tab_2)
self.verticalLayout_7.setObjectName("verticalLayout_7") self.verticalLayout_7.setObjectName("verticalLayout_7")
if (webk): if (webk):
self.webView = QtWebKit.QWebView(self.tab_2) 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.webView.setObjectName("webView")
self.verticalLayout_7.addWidget(self.webView) self.verticalLayout_7.addWidget(self.webView)
else: else:
self.webLink = QtGui.QLabel(self.groupBox) self.webLink = QtGui.QLabel(self.groupBox)
self.webLink.setFont(font) self.webLink.setFont(font)
self.webLink.setObjectName("lblLink") self.webLink.setObjectName("lblLink")
self.webLink.setText(QtGui.QApplication.translate("Dialog", "<a href=\"http://galileo.dmi.unict.it/wiki/relational/\">Relational's website</a>", None,)) self.webLink.setText(QtGui.QApplication.translate(
"Dialog", "<a href=\"https://github.com/ltworf/relational\">Relational's website</a>", None,))
self.webLink.setOpenExternalLinks(True) self.webLink.setOpenExternalLinks(True)
self.webLink.setTextFormat(QtCore.Qt.AutoText) self.webLink.setTextFormat(QtCore.Qt.AutoText)
self.webLink.setTextInteractionFlags( self.webLink.setTextInteractionFlags(
@ -116,7 +120,7 @@ class Ui_Dialog(object):
self.verticalLayout_7.addWidget(self.webLink) 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.verticalLayout_2.addWidget(self.tabWidget)
self.buttonBox = QtGui.QDialogButtonBox(Dialog) self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
@ -126,169 +130,185 @@ class Ui_Dialog(object):
self.retranslateUi(Dialog) self.retranslateUi(Dialog)
self.tabWidget.setCurrentIndex(0) self.tabWidget.setCurrentIndex(0)
QtCore.QObject.connect(self.buttonBox,QtCore.SIGNAL("accepted()"),Dialog.accept) QtCore.QObject.connect(
QtCore.QObject.connect(self.buttonBox,QtCore.SIGNAL("rejected()"),Dialog.reject) self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
QtCore.QObject.connect(
self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog) 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 &lt;<a href=\"mailto:tiposchi@tiscali.it\">tiposchi@tiscali.it</a>&gt;<br>Emilio Di Prima &lt;emiliodiprima[at]msn[dot]com&gt; (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", "<a href=\"http://galileo.dmi.unict.it/wiki/relational/\">http://galileo.dmi.unict.it/wiki/relational/</a>", 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", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><title>GNU General Public License - GNU Project - Free Software Foundation (FSF)</title><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'DejaVu Sans\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:14px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><span style=\" font-size:large;\">GNU GENERAL PUBLIC LICENSE</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Version 3, 29 June 2007 </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Copyright © 2007 Free Software Foundation, Inc. &lt;http://fsf.org/&gt;</p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><a name=\"preamble\"></a><span style=\" font-size:large;\">P</span><span style=\" font-size:large;\">reamble</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">The GNU General Public License is a free, copyleft license for software and other kinds of works. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">The precise terms and conditions for copying, distribution and modification follow. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><a name=\"terms\"></a><span style=\" font-size:large;\">T</span><span style=\" font-size:large;\">ERMS AND CONDITIONS</span> </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section0\"></a><span style=\" font-size:medium;\">0</span><span style=\" font-size:medium;\">. Definitions.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“This License” refers to version 3 of the GNU General Public License. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">A “covered work” means either the unmodified Program or a work based on the Program. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section1\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">. Source Code.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">The Corresponding Source for a work in source code form is that same work. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section2\"></a><span style=\" font-size:medium;\">2</span><span style=\" font-size:medium;\">. Basic Permissions.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section3\"></a><span style=\" font-size:medium;\">3</span><span style=\" font-size:medium;\">. Protecting Users\' Legal Rights From Anti-Circumvention Law.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section4\"></a><span style=\" font-size:medium;\">4</span><span style=\" font-size:medium;\">. Conveying Verbatim Copies.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section5\"></a><span style=\" font-size:medium;\">5</span><span style=\" font-size:medium;\">. Conveying Modified Source Versions.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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: </p>\n"
"<ul style=\"-qt-list-indent: 1;\"><li style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">a) The work must carry prominent notices stating that you modified it, and giving a relevant date. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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”. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li></ul>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section6\"></a><span style=\" font-size:medium;\">6</span><span style=\" font-size:medium;\">. Conveying Non-Source Forms.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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: </p>\n"
"<ul style=\"-qt-list-indent: 1;\"><li style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li></ul>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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). </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section7\"></a><span style=\" font-size:medium;\">7</span><span style=\" font-size:medium;\">. Additional Terms.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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: </p>\n"
"<ul style=\"-qt-list-indent: 1;\"><li style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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 </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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 </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">d) Limiting the use for publicity purposes of names of licensors or authors of the material; or </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or </li>\n"
"<li style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li></ul>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section8\"></a><span style=\" font-size:medium;\">8</span><span style=\" font-size:medium;\">. Termination.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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). </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section9\"></a><span style=\" font-size:medium;\">9</span><span style=\" font-size:medium;\">. Acceptance Not Required for Having Copies.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section10\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">0. Automatic Licensing of Downstream Recipients.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section11\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">1. Patents.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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”. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section12\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">2. No Surrender of Others\' Freedom.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section13\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">3. Use with the GNU Affero General Public License.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section14\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">4. Revised Versions of this License.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section15\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">5. Disclaimer of Warranty.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section16\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">6. Limitation of Liability.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section17\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">7. Interpretation of Sections 15 and 16.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">END OF TERMS AND CONDITIONS </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><a name=\"howto\"></a><span style=\" font-size:large;\">H</span><span style=\" font-size:large;\">ow to Apply These Terms to Your New Programs</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<pre style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> &lt;one line to give the program\'s name and a brief idea of what it does.&gt;</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> Copyright (C) &lt;year&gt; &lt;name of author&gt;</pre>\n"
"<pre style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"></pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> This program is free software: you can redistribute it and/or modify</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> it under the terms of the GNU General Public License as published by</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> the Free Software Foundation, either version 3 of the License, or</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> (at your option) any later version.</pre>\n"
"<pre style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"></pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> This program is distributed in the hope that it will be useful,</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> but WITHOUT ANY WARRANTY; without even the implied warranty of</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> GNU General Public License for more details.</pre>\n"
"<pre style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"></pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> You should have received a copy of the GNU General Public License</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> along with this program. If not, see &lt;http://www.gnu.org/licenses/&gt;. </pre>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Also add information on how to contact you by electronic and paper mail. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: </p>\n"
"<pre style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> &lt;program&gt; Copyright (C) &lt;year&gt; &lt;name of author&gt;</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> This is free software, and you are welcome to redistribute it</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> under certain conditions; type `show c\' for details. </pre>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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”. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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 &lt;http://www.gnu.org/licenses/&gt;. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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 &lt;http://www.gnu.org/philosophy/why-not-lgpl.html&gt;. </p></body></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 &lt;<a href=\"mailto:tiposchi@tiscali.it\">tiposchi@tiscali.it</a>&gt;<br>Emilio Di Prima &lt;emiliodiprima[at]msn[dot]com&gt; (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", "<a href=\"https://github.com/ltworf/relational/\">https://github.com/ltworf/relational/</a>", 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", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><title>GNU General Public License - GNU Project - Free Software Foundation (FSF)</title><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'DejaVu Sans\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:14px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><span style=\" font-size:large;\">GNU GENERAL PUBLIC LICENSE</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Version 3, 29 June 2007 </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Copyright © 2007 Free Software Foundation, Inc. &lt;http://fsf.org/&gt;</p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><a name=\"preamble\"></a><span style=\" font-size:large;\">P</span><span style=\" font-size:large;\">reamble</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">The GNU General Public License is a free, copyleft license for software and other kinds of works. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">The precise terms and conditions for copying, distribution and modification follow. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><a name=\"terms\"></a><span style=\" font-size:large;\">T</span><span style=\" font-size:large;\">ERMS AND CONDITIONS</span> </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section0\"></a><span style=\" font-size:medium;\">0</span><span style=\" font-size:medium;\">. Definitions.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“This License” refers to version 3 of the GNU General Public License. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">A “covered work” means either the unmodified Program or a work based on the Program. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section1\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">. Source Code.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">The Corresponding Source for a work in source code form is that same work. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section2\"></a><span style=\" font-size:medium;\">2</span><span style=\" font-size:medium;\">. Basic Permissions.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section3\"></a><span style=\" font-size:medium;\">3</span><span style=\" font-size:medium;\">. Protecting Users\' Legal Rights From Anti-Circumvention Law.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section4\"></a><span style=\" font-size:medium;\">4</span><span style=\" font-size:medium;\">. Conveying Verbatim Copies.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section5\"></a><span style=\" font-size:medium;\">5</span><span style=\" font-size:medium;\">. Conveying Modified Source Versions.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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: </p>\n"
"<ul style=\"-qt-list-indent: 1;\"><li style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">a) The work must carry prominent notices stating that you modified it, and giving a relevant date. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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”. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li></ul>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section6\"></a><span style=\" font-size:medium;\">6</span><span style=\" font-size:medium;\">. Conveying Non-Source Forms.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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: </p>\n"
"<ul style=\"-qt-list-indent: 1;\"><li style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li>\n"
"<li style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li></ul>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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). </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section7\"></a><span style=\" font-size:medium;\">7</span><span style=\" font-size:medium;\">. Additional Terms.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">“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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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: </p>\n"
"<ul style=\"-qt-list-indent: 1;\"><li style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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 </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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 </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">d) Limiting the use for publicity purposes of names of licensors or authors of the material; or </li>\n"
"<li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or </li>\n"
"<li style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </li></ul>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section8\"></a><span style=\" font-size:medium;\">8</span><span style=\" font-size:medium;\">. Termination.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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). </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section9\"></a><span style=\" font-size:medium;\">9</span><span style=\" font-size:medium;\">. Acceptance Not Required for Having Copies.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section10\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">0. Automatic Licensing of Downstream Recipients.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section11\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">1. Patents.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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”. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section12\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">2. No Surrender of Others\' Freedom.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section13\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">3. Use with the GNU Affero General Public License.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section14\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">4. Revised Versions of this License.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section15\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">5. Disclaimer of Warranty.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section16\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">6. Limitation of Liability.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><a name=\"section17\"></a><span style=\" font-size:medium;\">1</span><span style=\" font-size:medium;\">7. Interpretation of Sections 15 and 16.</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">END OF TERMS AND CONDITIONS </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><a name=\"howto\"></a><span style=\" font-size:large;\">H</span><span style=\" font-size:large;\">ow to Apply These Terms to Your New Programs</span> </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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. </p>\n"
"<pre style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> &lt;one line to give the program\'s name and a brief idea of what it does.&gt;</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> Copyright (C) &lt;year&gt; &lt;name of author&gt;</pre>\n"
"<pre style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"></pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> This program is free software: you can redistribute it and/or modify</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> it under the terms of the GNU General Public License as published by</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> the Free Software Foundation, either version 3 of the License, or</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> (at your option) any later version.</pre>\n"
"<pre style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"></pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> This program is distributed in the hope that it will be useful,</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> but WITHOUT ANY WARRANTY; without even the implied warranty of</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> GNU General Public License for more details.</pre>\n"
"<pre style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"></pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> You should have received a copy of the GNU General Public License</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> along with this program. If not, see &lt;http://www.gnu.org/licenses/&gt;. </pre>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Also add information on how to contact you by electronic and paper mail. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: </p>\n"
"<pre style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> &lt;program&gt; Copyright (C) &lt;year&gt; &lt;name of author&gt;</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> This is free software, and you are welcome to redistribute it</pre>\n"
"<pre style=\" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Courier New,courier\';\"> under certain conditions; type `show c\' for details. </pre>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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”. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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 &lt;http://www.gnu.org/licenses/&gt;. </p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">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 &lt;http://www.gnu.org/philosophy/why-not-lgpl.html&gt;. </p></body></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__": if __name__ == "__main__":
@ -299,4 +319,3 @@ if __name__ == "__main__":
ui.setupUi(Dialog) ui.setupUi(Dialog)
Dialog.show() Dialog.show()
sys.exit(app.exec_()) sys.exit(app.exec_())

@ -22,37 +22,42 @@
try: try:
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
pyqt=True pyqt = True
except: except:
from PySide import QtCore, QtGui from PySide import QtCore, QtGui
pyqt=False pyqt = False
def get_py_str(a): def get_py_str(a):
'''Returns a python string out of a QString''' '''Returns a python string out of a QString'''
if pyqt: if pyqt:
return unicode(a.toUtf8(),'utf-8') return unicode(a.toUtf8(), 'utf-8')
return a #Already a python string in PySide return a # Already a python string in PySide
def set_utf8_text(component,text):
def set_utf8_text(component, text):
if not pyqt: if not pyqt:
component.setText(text) component.setText(text)
else: else:
component.setText(QtCore.QString.fromUtf8(text)) component.setText(QtCore.QString.fromUtf8(text))
def get_filename(filename): def get_filename(filename):
if pyqt: if pyqt:
return str(filename.toUtf8()) return str(filename.toUtf8())
return filename[0] return filename[0]
def add_list_item(l,item):
def add_list_item(l, item):
if pyqt: if pyqt:
history_item=QtCore.QString() history_item = QtCore.QString()
history_item.append(item) history_item.append(item)
hitem=QtGui.QListWidgetItem(None,0) hitem = QtGui.QListWidgetItem(None, 0)
hitem.setText(history_item) hitem.setText(history_item)
l.addItem (hitem) l.addItem(hitem)
l.setCurrentItem(hitem) l.setCurrentItem(hitem)
else: else:
hitem=QtGui.QListWidgetItem(None,0) hitem = QtGui.QListWidgetItem(None, 0)
hitem.setText(item) hitem.setText(item)
l.addItem (hitem) l.addItem(hitem)
l.setCurrentItem(hitem) l.setCurrentItem(hitem)

@ -28,105 +28,119 @@ import rel_edit
class creatorForm(QtGui.QDialog): class creatorForm(QtGui.QDialog):
def __init__(self,rel=None):
def __init__(self, rel=None):
QtGui.QDialog.__init__(self) QtGui.QDialog.__init__(self)
self.setSizeGripEnabled(True) self.setSizeGripEnabled(True)
self.result_relation=None self.result_relation = None
self.rel=rel self.rel = rel
def setUi(self,ui):
self.ui=ui
self.table=self.ui.table
if self.rel==None: def setUi(self, ui):
self.ui = ui
self.table = self.ui.table
if self.rel == None:
self.setup_empty() self.setup_empty()
else: else:
self.setup_relation(self.rel) self.setup_relation(self.rel)
def setup_relation(self,rel):
def setup_relation(self, rel):
self.table.insertRow(0) self.table.insertRow(0)
for i in rel.header.attributes: for i in rel.header.attributes:
item=QtGui.QTableWidgetItem() item = QtGui.QTableWidgetItem()
item.setText(i) item.setText(i)
self.table.insertColumn(self.table.columnCount()) 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: for i in rel.content:
self.table.insertRow(self.table.rowCount()) self.table.insertRow(self.table.rowCount())
for j in range(len(i)): for j in range(len(i)):
item=QtGui.QTableWidgetItem() item = QtGui.QTableWidgetItem()
item.setText(i[j]) item.setText(i[j])
self.table.setItem(self.table.rowCount()-1,j,item) self.table.setItem(self.table.rowCount() - 1, j, item)
pass pass
def setup_empty(self): def setup_empty(self):
self.table.insertColumn(0) self.table.insertColumn(0)
self.table.insertColumn(0) self.table.insertColumn(0)
self.table.insertRow(0) self.table.insertRow(0)
self.table.insertRow(0) self.table.insertRow(0)
i00=QtGui.QTableWidgetItem() i00 = QtGui.QTableWidgetItem()
i01=QtGui.QTableWidgetItem() i01 = QtGui.QTableWidgetItem()
i10=QtGui.QTableWidgetItem() i10 = QtGui.QTableWidgetItem()
i11=QtGui.QTableWidgetItem() i11 = QtGui.QTableWidgetItem()
i00.setText('Field name 1') i00.setText('Field name 1')
i01.setText('Field name 2') i01.setText('Field name 2')
i10.setText('Value 1') i10.setText('Value 1')
i11.setText('Value 2') i11.setText('Value 2')
self.table.setItem (0,0,i00) self.table.setItem(0, 0, i00)
self.table.setItem (0,1,i01) self.table.setItem(0, 1, i01)
self.table.setItem (1,0,i10) self.table.setItem(1, 0, i10)
self.table.setItem (1,1,i11) self.table.setItem(1, 1, i11)
def create_relation(self): def create_relation(self):
hlist=[] hlist = []
for i in range(self.table.columnCount()): 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: try:
header=relation.header(hlist) header = relation.header(hlist)
except Exception, e: 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 return None
r=relation.relation() r = relation.relation()
r.header=header r.header = header
for i in range(1,self.table.rowCount()): for i in range(1, self.table.rowCount()):
hlist=[] hlist = []
for j in range(self.table.columnCount()): for j in range(self.table.columnCount()):
try: 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: 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 return None
r.content.add(tuple(hlist)) r.content.add(tuple(hlist))
return r return r
def accept(self): def accept(self):
self.result_relation=self.create_relation() self.result_relation = self.create_relation()
#Doesn't close the window in case of errors # Doesn't close the window in case of errors
if self.result_relation!=None: if self.result_relation != None:
QtGui.QDialog.accept(self) QtGui.QDialog.accept(self)
pass pass
def reject(self): def reject(self):
self.result_relation=None self.result_relation = None
QtGui.QDialog.reject(self) QtGui.QDialog.reject(self)
pass pass
def addColumn(self): def addColumn(self):
self.table.insertColumn(self.table.columnCount()) self.table.insertColumn(self.table.columnCount())
pass pass
def addRow(self): def addRow(self):
self.table.insertRow(1) self.table.insertRow(1)
pass pass
def deleteColumn(self): def deleteColumn(self):
if self.table.columnCount()>1: if self.table.columnCount() > 1:
self.table.removeColumn(self.table.currentColumn()) self.table.removeColumn(self.table.currentColumn())
pass pass
def deleteRow(self): def deleteRow(self):
if self.table.rowCount()>2: if self.table.rowCount() > 2:
self.table.removeRow(self.table.currentRow()) self.table.removeRow(self.table.currentRow())
pass pass
@ -149,5 +163,6 @@ def edit_relation(rel=None):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
app = QtGui.QApplication(sys.argv) 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) print edit_relation(r)

@ -26,8 +26,7 @@ except:
from PySide import QtCore, QtGui from PySide import QtCore, QtGui
from relational import relation, parser, optimizer, rtypes
from relational import relation, parser, optimizer,rtypes
import about import about
import survey import survey
@ -38,277 +37,315 @@ import compatibility
class relForm(QtGui.QMainWindow): class relForm(QtGui.QMainWindow):
def __init__(self,ui): def __init__(self, ui):
QtGui.QMainWindow.__init__(self) QtGui.QMainWindow.__init__(self)
self.About=None self.About = None
self.Survey=None self.Survey = None
self.relations={} #Dictionary for relations self.relations = {} # Dictionary for relations
self.undo=None #UndoQueue for queries self.undo = None # UndoQueue for queries
self.selectedRelation=None self.selectedRelation = None
self.ui=ui self.ui = ui
self.qcounter=1 #Query counter self.qcounter = 1 # Query counter
self.settings = QtCore.QSettings() self.settings = QtCore.QSettings()
def checkVersion(self): def checkVersion(self):
from relational import maintenance from relational import maintenance
online=maintenance.check_latest_version() online = maintenance.check_latest_version()
if online>version: if online > version:
r=QtGui.QApplication.translate("Form", "New version available online: %s." % online) r = QtGui.QApplication.translate(
elif online==version: "Form", "New version available online: %s." % online)
r=QtGui.QApplication.translate("Form", "Latest version installed.") elif online == version:
r = QtGui.QApplication.translate(
"Form", "Latest version installed.")
else: 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()) self.ui.txtQuery.setText(self.savedQ.itemData(index[0]).toString())
def undoOptimize(self): def undoOptimize(self):
'''Undoes the optimization on the query, popping one item from the undo list''' '''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) self.ui.txtQuery.setText(self.undo)
def optimize(self): def optimize(self):
'''Performs all the possible optimizations on the query''' '''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: try:
result=optimizer.optimize_all(query,self.relations) result = optimizer.optimize_all(query, self.relations)
compatibility.set_utf8_text(self.ui.txtQuery,result) compatibility.set_utf8_text(self.ui.txtQuery, result)
except Exception, e: 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)
def resumeHistory(self,item): compatibility.set_utf8_text(self.ui.txtResult, itm[0])
itm=compatibility.get_py_str(item.text()).split(' = ',1) compatibility.set_utf8_text(self.ui.txtQuery, itm[1])
compatibility.set_utf8_text(self.ui.txtResult,itm[0])
compatibility.set_utf8_text(self.ui.txtQuery,itm[1])
def execute(self): def execute(self):
'''Executes the query''' '''Executes the query'''
query=compatibility.get_py_str(self.ui.txtQuery.text()) query = compatibility.get_py_str(self.ui.txtQuery.text())
res_rel=compatibility.get_py_str(self.ui.txtResult.text())#result relation's name res_rel = compatibility.get_py_str(
self.ui.txtResult.text()) # result relation's name
if not rtypes.is_valid_relation_name(res_rel): 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 return
try: try:
#Converting string to utf8 and then from qstring to normal string # Converting string to utf8 and then from qstring to normal string
expr=parser.parse(query)#Converting expression to python code expr = parser.parse(query) # Converting expression to python code
print query,"-->" , expr #Printing debug print query, "-->", expr # Printing debug
result=eval(expr,self.relations) #Evaluating the expression result = eval(expr, self.relations) # Evaluating the expression
self.relations[res_rel]=result #Add the relation to the dictionary self.relations[
self.updateRelations() #update the list res_rel] = result # Add the relation to the dictionary
self.selectedRelation=result self.updateRelations() # update the list
self.showRelation(self.selectedRelation) #Show the result in the table self.selectedRelation = result
self.showRelation(self.selectedRelation)
# Show the result in the table
except Exception, e: except Exception, e:
print e.__unicode__() 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 return
#Adds to history # Adds to history
item=u'%s = %s' % (compatibility.get_py_str(self.ui.txtResult.text()),compatibility.get_py_str(self.ui.txtQuery.text())) item = u'%s = %s' % (compatibility.get_py_str(
#item=item.decode('utf-8')) self.ui.txtResult.text()), compatibility.get_py_str(self.ui.txtQuery.text()))
compatibility.add_list_item(self.ui.lstHistory,item) # item=item.decode('utf-8'))
compatibility.add_list_item(self.ui.lstHistory, item)
self.qcounter+=1 self.qcounter += 1
compatibility.set_utf8_text(self.ui.txtResult,u"_last%d"% self.qcounter) #Sets the result relation name to none 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''' '''Shows the selected relation into the table'''
self.ui.table.clear() 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.setColumnCount(1)
self.ui.table.headerItem().setText(0,"Empty relation") self.ui.table.headerItem().setText(0, "Empty relation")
return return
self.ui.table.setColumnCount(len(rel.header.attributes)) self.ui.table.setColumnCount(len(rel.header.attributes))
#Set content # Set content
for i in rel.content: for i in rel.content:
item = QtGui.QTreeWidgetItem() item = QtGui.QTreeWidgetItem()
for j in range(len(i)): for j in range(len(i)):
item.setText(j, i[j]) item.setText(j, i[j])
self.ui.table.addTopLevelItem(item) self.ui.table.addTopLevelItem(item)
#Sets columns # Sets columns
for i in range(len(rel.header.attributes)): for i in range(len(rel.header.attributes)):
self.ui.table.headerItem().setText(i,rel.header.attributes[i]) 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.resizeColumnToContents(
i) # Must be done in order to avoid too small columns
def printRelation(self, item):
def printRelation(self,item): self.selectedRelation = self.relations[
self.selectedRelation=self.relations[compatibility.get_py_str(item.text())] compatibility.get_py_str(item.text())]
self.showRelation(self.selectedRelation) self.showRelation(self.selectedRelation)
def showAttributes(self,item): def showAttributes(self, item):
'''Shows the attributes of the selected relation''' '''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() self.ui.lstAttributes.clear()
for j in self.relations[rel].header.attributes: for j in self.relations[rel].header.attributes:
self.ui.lstAttributes.addItem (j) self.ui.lstAttributes.addItem(j)
def updateRelations(self): def updateRelations(self):
self.ui.lstRelations.clear() self.ui.lstRelations.clear()
for i in self.relations: for i in self.relations:
if i != "__builtins__": if i != "__builtins__":
self.ui.lstRelations.addItem(i) 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) def saveRelation(self):
if (len(filename)==0):#Returns if no file was selected 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 return
self.selectedRelation.save(filename) self.selectedRelation.save(filename)
return return
def unloadRelation(self): def unloadRelation(self):
for i in self.ui.lstRelations.selectedItems(): for i in self.ui.lstRelations.selectedItems():
del self.relations[compatibility.get_py_str(i.text())] del self.relations[compatibility.get_py_str(i.text())]
self.updateRelations() self.updateRelations()
def editRelation(self): def editRelation(self):
import creator import creator
for i in self.ui.lstRelations.selectedItems(): for i in self.ui.lstRelations.selectedItems():
result=creator.edit_relation(self.relations[compatibility.get_py_str(i.text())]) result = creator.edit_relation(
if result!=None: self.relations[compatibility.get_py_str(i.text())])
self.relations[compatibility.get_py_str(i.text())]=result if result != None:
self.relations[compatibility.get_py_str(i.text())] = result
self.updateRelations() self.updateRelations()
def newRelation(self): def newRelation(self):
import creator import creator
result=creator.edit_relation() result = creator.edit_relation()
if result==None: if result == None:
return return
res=QtGui.QInputDialog.getText( res = QtGui.QInputDialog.getText(
self, self,
QtGui.QApplication.translate("Form", "New relation"), QtGui.QApplication.translate("Form", "New relation"),
QtGui.QApplication.translate("Form", "Insert the name for the new relation"), QtGui.QApplication.translate(
QtGui.QLineEdit.Normal,'') "Form", "Insert the name for the new relation"),
if res[1]==False or len(res[0])==0: QtGui.QLineEdit.Normal, '')
if res[1] == False or len(res[0]) == 0:
return return
#Patch provided by Angelo 'Havoc' Puglisi # Patch provided by Angelo 'Havoc' Puglisi
name=compatibility.get_py_str(res[0]) name = compatibility.get_py_str(res[0])
if not rtypes.is_valid_relation_name(name): if not rtypes.is_valid_relation_name(name):
r=QtGui.QApplication.translate("Form", str("Wrong name for destination relation: %s." % name)) r = QtGui.QApplication.translate(
QtGui.QMessageBox.information(self,QtGui.QApplication.translate("Form", "Error"),r) "Form", str("Wrong name for destination relation: %s." % name))
QtGui.QMessageBox.information(
self, QtGui.QApplication.translate("Form", "Error"), r)
return return
try: try:
self.relations[name]=result self.relations[name] = result
except Exception, e: except Exception, e:
print 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 return
self.updateRelations() self.updateRelations()
def closeEvent(self, event): def closeEvent(self, event):
self.save_settings() self.save_settings()
event.accept() event.accept()
def save_settings(self): def save_settings(self):
#self.settings.setValue("width",) # self.settings.setValue("width",)
pass pass
def restore_settings(self): def restore_settings(self):
#self.settings.value('session_name','default').toString() # self.settings.value('session_name','default').toString()
pass pass
def showSurvey(self): def showSurvey(self):
if self.Survey==None: if self.Survey == None:
self.Survey=surveyForm.surveyForm() self.Survey = surveyForm.surveyForm()
ui = survey.Ui_Form() ui = survey.Ui_Form()
self.Survey.setUi(ui) self.Survey.setUi(ui)
ui.setupUi(self.Survey) ui.setupUi(self.Survey)
self.Survey.setDefaultValues() self.Survey.setDefaultValues()
self.Survey.show() self.Survey.show()
def showAbout(self): def showAbout(self):
if self.About==None: if self.About == None:
self.About = QtGui.QDialog() self.About = QtGui.QDialog()
ui = about.Ui_Dialog() ui = about.Ui_Dialog()
ui.setupUi(self.About) ui.setupUi(self.About)
self.About.show() 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, '''Loads a relation. Without parameters it will ask the user which relation to load,
otherwise it will load filename, giving it name. otherwise it will load filename, giving it name.
It shouldn't be called giving filename but not giving name.''' It shouldn't be called giving filename but not giving name.'''
#Asking for file to load # Asking for file to load
if filename==None: 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 = QtGui.QFileDialog.getOpenFileName(self, QtGui.QApplication.translate(
filename=compatibility.get_filename(filename) "Form", "Load Relation"), "", QtGui.QApplication.translate("Form", "Relations (*.csv);;Text Files (*.txt);;All Files (*)"))
filename = compatibility.get_filename(filename)
#Default relation's name # Default relation's name
f=filename.split('/') #Split the full path f = filename.split('/') # Split the full path
defname=f[len(f)-1].lower() #Takes only the lowercase filename defname = f[len(f) - 1].lower() # Takes only the lowercase filename
if len(defname)==0: if len(defname) == 0:
return return
if (defname.endswith(".csv")): #removes the extension if (defname.endswith(".csv")): # removes the extension
defname=defname[:-4] defname = defname[:-4]
if name==None: #Prompt dialog to insert name for the relation 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"), res = QtGui.QInputDialog.getText(
QtGui.QLineEdit.Normal,defname) self, QtGui.QApplication.translate("Form", "New relation"), QtGui.QApplication.translate(
if res[1]==False or len(res[0])==0: "Form", "Insert the name for the new relation"),
QtGui.QLineEdit.Normal, defname)
if res[1] == False or len(res[0]) == 0:
return return
#Patch provided by Angelo 'Havoc' Puglisi # Patch provided by Angelo 'Havoc' Puglisi
name=compatibility.get_py_str(res[0]) name = compatibility.get_py_str(res[0])
if not rtypes.is_valid_relation_name(name): if not rtypes.is_valid_relation_name(name):
r=QtGui.QApplication.translate("Form", str("Wrong name for destination relation: %s." % name)) r = QtGui.QApplication.translate(
QtGui.QMessageBox.information(self,QtGui.QApplication.translate("Form", "Error"),r) "Form", str("Wrong name for destination relation: %s." % name))
QtGui.QMessageBox.information(
self, QtGui.QApplication.translate("Form", "Error"), r)
return return
try: try:
self.relations[name]=relation.relation(filename) self.relations[name] = relation.relation(filename)
except Exception, e: except Exception, e:
print 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 return
self.updateRelations() self.updateRelations()
def addProduct(self): def addProduct(self):
self.addSymbolInQuery(u"*") self.addSymbolInQuery(u"*")
def addDifference(self): def addDifference(self):
self.addSymbolInQuery(u"-") self.addSymbolInQuery(u"-")
def addUnion(self): def addUnion(self):
self.addSymbolInQuery(u"") self.addSymbolInQuery(u"")
def addIntersection(self): def addIntersection(self):
self.addSymbolInQuery(u"") self.addSymbolInQuery(u"")
def addDivision(self): def addDivision(self):
self.addSymbolInQuery(u"÷") self.addSymbolInQuery(u"÷")
def addOLeft(self): def addOLeft(self):
self.addSymbolInQuery(u"ᐅLEFTᐊ") self.addSymbolInQuery(u"ᐅLEFTᐊ")
def addJoin(self): def addJoin(self):
self.addSymbolInQuery(u"ᐅᐊ") self.addSymbolInQuery(u"ᐅᐊ")
def addORight(self): def addORight(self):
self.addSymbolInQuery(u"ᐅRIGHTᐊ") self.addSymbolInQuery(u"ᐅRIGHTᐊ")
def addOuter(self): def addOuter(self):
self.addSymbolInQuery(u"ᐅFULLᐊ") self.addSymbolInQuery(u"ᐅFULLᐊ")
def addProjection(self): def addProjection(self):
self.addSymbolInQuery(u"π") self.addSymbolInQuery(u"π")
def addSelection(self): def addSelection(self):
self.addSymbolInQuery(u"σ") self.addSymbolInQuery(u"σ")
def addRename(self): def addRename(self):
self.addSymbolInQuery(u"ρ") self.addSymbolInQuery(u"ρ")
def addArrow(self): def addArrow(self):
self.addSymbolInQuery(u"") self.addSymbolInQuery(u"")
def addSymbolInQuery(self,symbol): def addSymbolInQuery(self, symbol):
self.ui.txtQuery.insert(symbol) self.ui.txtQuery.insert(symbol)
self.ui.txtQuery.setFocus() self.ui.txtQuery.setFocus()

@ -2,7 +2,7 @@
# Form implementation generated from reading ui file 'relational_gui/maingui.ui' # 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 # by: PyQt4 UI code generator 4.10.3
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!

@ -2,7 +2,7 @@
# Form implementation generated from reading ui file 'relational_gui/rel_edit.ui' # 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 # by: PyQt4 UI code generator 4.10.3
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!

@ -2,7 +2,7 @@
# Form implementation generated from reading ui file 'relational_gui/survey.ui' # 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 # by: PyQt4 UI code generator 4.10.3
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!

File diff suppressed because one or more lines are too long

@ -2,7 +2,7 @@
# Form implementation generated from reading ui file 'relational_pyside/maingui.ui' # 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 # by: pyside-uic 0.2.15 running on PySide 1.2.1
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!

@ -2,7 +2,7 @@
# Form implementation generated from reading ui file 'relational_pyside/rel_edit.ui' # 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 # by: pyside-uic 0.2.15 running on PySide 1.2.1
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!

@ -2,7 +2,7 @@
# Form implementation generated from reading ui file 'relational_pyside/survey.ui' # 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 # by: pyside-uic 0.2.15 running on PySide 1.2.1
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!

@ -17,7 +17,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it> # author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
# 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 readline
import logging import logging
@ -31,7 +32,9 @@ from xtermcolor import colorize
PROMPT_COLOR = 0xffff00 PROMPT_COLOR = 0xffff00
ERROR_COLOR = 0xff0000 ERROR_COLOR = 0xff0000
class SimpleCompleter(object): class SimpleCompleter(object):
'''Handles completion''' '''Handles completion'''
def __init__(self, options): def __init__(self, options):
@ -39,13 +42,13 @@ class SimpleCompleter(object):
self.options = sorted(options) self.options = sorted(options)
return return
def add_completion(self,option): def add_completion(self, option):
'''Adds one string to the list of the valid completion options''' '''Adds one string to the list of the valid completion options'''
if option not in self.options: if option not in self.options:
self.options.append(option) self.options.append(option)
self.options.sort() self.options.sort()
def remove_completion(self,option): def remove_completion(self, option):
'''Removes one completion from the list of the valid completion options''' '''Removes one completion from the list of the valid completion options'''
if option in self.options: if option in self.options:
self.options.remove(option) self.options.remove(option)
@ -57,25 +60,25 @@ class SimpleCompleter(object):
# This is the first time for this text, so build a match list. # This is the first time for this text, so build a match list.
if text: if text:
self.matches =[s self.matches = [s
for s in self.options for s in self.options
if s and s.startswith(text)] if s and s.startswith(text)]
#Add the completion for files here # Add the completion for files here
try: try:
d=os.path.dirname(text) d = os.path.dirname(text)
listf=os.listdir(d) listf = os.listdir(d)
d+="/" d += "/"
except: except:
d="" d = ""
listf=os.listdir('.') listf = os.listdir('.')
for i in listf: for i in listf:
i=(d+i).replace('//','/') i = (d + i).replace('//', '/')
if i.startswith(text): if i.startswith(text):
if os.path.isdir(i): if os.path.isdir(i):
i=i+"/" i = i + "/"
self.matches.append(i) self.matches.append(i)
logging.debug('%s matches: %s', repr(text), self.matches) logging.debug('%s matches: %s', repr(text), self.matches)
@ -94,203 +97,211 @@ class SimpleCompleter(object):
return response return response
relations={} relations = {}
completer=SimpleCompleter(['SURVEY','LIST','LOAD ','UNLOAD ','HELP ','QUIT','SAVE ','_PRODUCT ','_UNION ','_INTERSECTION ','_DIFFERENCE ','_JOIN ','_LJOIN ','_RJOIN ','_FJOIN ','_PROJECTION ','_RENAME_TO ','_SELECTION ','_RENAME ','_DIVISION ']) 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): 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 return None
f=filename.split('/') f = filename.split('/')
if defname==None: if defname == None:
defname=f[len(f)-1].lower() defname = f[len(f) - 1].lower()
if defname.endswith(".csv"): #removes the extension if defname.endswith(".csv"): # removes the extension
defname=defname[:-4] defname = defname[:-4]
if not rtypes.is_valid_relation_name(defname): 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 return
try: try:
relations[defname]=relation.relation(filename) relations[defname] = relation.relation(filename)
completer.add_completion(defname) completer.add_completion(defname)
print colorize("Loaded relation %s"% defname,0x00ff00) print colorize("Loaded relation %s" % defname, 0x00ff00)
return defname return defname
except Exception, e: except Exception, e:
print >>sys.stderr,colorize(e,ERROR_COLOR) print >>sys.stderr, colorize(e, ERROR_COLOR)
return None return None
def survey(): def survey():
'''performs a survey''' '''performs a survey'''
from relational import maintenance from relational import maintenance
post= {'software':'Relational algebra (cli)','version':version} post = {'software': 'Relational algebra (cli)', 'version': version}
fields=('System','Country','School','Age','How did you find','email (only if you want a reply)','Comments') fields = ('System', 'Country', 'School', 'Age', 'How did you find',
'email (only if you want a reply)', 'Comments')
for i in fields: for i in fields:
a=raw_input('%s: '%i) a = raw_input('%s: ' % i)
post[i]=a post[i] = a
maintenance.send_survey(post) maintenance.send_survey(post)
def help(command): def help(command):
'''Prints help on the various functions''' '''Prints help on the various functions'''
p=command.split(' ',1) p = command.split(' ', 1)
if len(p)==1: if len(p) == 1:
print 'HELP command' 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 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 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 '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.' print 'Rember: the tab key is enabled and can be very helpful if you can\'t remember something.'
return return
cmd=p[1] cmd = p[1]
if cmd=='QUIT': if cmd == 'QUIT':
print 'Quits the program' print 'Quits the program'
elif cmd=='LIST': elif cmd == 'LIST':
print "Lists the relations loaded" print "Lists the relations loaded"
elif cmd=='LOAD': elif cmd == 'LOAD':
print "LOAD filename [relationame]" print "LOAD filename [relationame]"
print "Loads a relation into memory" print "Loads a relation into memory"
elif cmd=='UNLOAD': elif cmd == 'UNLOAD':
print "UNLOAD relationame" print "UNLOAD relationame"
print "Unloads a relation from memory" print "Unloads a relation from memory"
elif cmd=='SAVE': elif cmd == 'SAVE':
print "SAVE filename relationame" print "SAVE filename relationame"
print "Saves a relation in a file" print "Saves a relation in a file"
elif cmd=='HELP': elif cmd == 'HELP':
print "Prints the help on a command" print "Prints the help on a command"
elif cmd=='SURVEY': elif cmd == 'SURVEY':
print "Fill and send a survey" print "Fill and send a survey"
else: else:
print "Unknown command: %s" %cmd print "Unknown command: %s" % cmd
def exec_line(command): def exec_line(command):
command=command.strip() command = command.strip()
if command.startswith(';'): if command.startswith(';'):
return return
elif command=='QUIT': elif command == 'QUIT':
sys.exit(0) sys.exit(0)
elif command.startswith('HELP'): elif command.startswith('HELP'):
help(command) help(command)
elif command=='LIST': #Lists all the loaded relations elif command == 'LIST': # Lists all the loaded relations
for i in relations: for i in relations:
if not i.startswith('_'): if not i.startswith('_'):
print i print i
elif command=='SURVEY': elif command == 'SURVEY':
survey() survey()
elif command.startswith('LOAD '): #Loads a relation elif command.startswith('LOAD '): # Loads a relation
pars=command.split(' ') pars = command.split(' ')
if len(pars)==1: if len(pars) == 1:
print colorize("Missing parameter",ERROR_COLOR) print colorize("Missing parameter", ERROR_COLOR)
return return
filename=pars[1] filename = pars[1]
if len(pars)>2: if len(pars) > 2:
defname=pars[2] defname = pars[2]
else: else:
defname=None defname = None
load_relation(filename,defname) load_relation(filename, defname)
elif command.startswith('UNLOAD '): elif command.startswith('UNLOAD '):
pars=command.split(' ') pars = command.split(' ')
if len(pars)<2: if len(pars) < 2:
print colorize("Missing parameter",ERROR_COLOR) print colorize("Missing parameter", ERROR_COLOR)
return return
if pars[1] in relations: if pars[1] in relations:
del relations[pars[1]] del relations[pars[1]]
completer.remove_completion(pars[1]) completer.remove_completion(pars[1])
else: else:
print colorize("No such relation %s" % pars[1],ERROR_COLOR) print colorize("No such relation %s" % pars[1], ERROR_COLOR)
pass pass
elif command.startswith('SAVE '): elif command.startswith('SAVE '):
pars=command.split(' ') pars = command.split(' ')
if len(pars)!=3: if len(pars) != 3:
print colorize("Missing parameter",ERROR_COLOR) print colorize("Missing parameter", ERROR_COLOR)
return return
filename=pars[1] filename = pars[1]
defname=pars[2] defname = pars[2]
if defname not in relations: if defname not in relations:
print colorize("No such relation %s" % defname,ERROR_COLOR) print colorize("No such relation %s" % defname, ERROR_COLOR)
return return
try: try:
relations[defname].save(filename) relations[defname].save(filename)
except Exception,e: except Exception, e:
print colorize(e,ERROR_COLOR) print colorize(e, ERROR_COLOR)
else: else:
exec_query(command) exec_query(command)
def replacements(query): def replacements(query):
'''This funcion replaces ascii easy operators with the correct ones''' '''This funcion replaces ascii easy operators with the correct ones'''
query=query.replace(u'_PRODUCT' , u'*') query = query.replace(u'_PRODUCT', u'*')
query=query.replace(u'_UNION' , u'') query = query.replace(u'_UNION', u'')
query=query.replace(u'_INTERSECTION' , u'') query = query.replace(u'_INTERSECTION', u'')
query=query.replace(u'_DIFFERENCE' , u'-') query = query.replace(u'_DIFFERENCE', u'-')
query=query.replace(u'_JOIN' , u'ᐅᐊ') query = query.replace(u'_JOIN', u'ᐅᐊ')
query=query.replace(u'_LJOIN' , u'ᐅLEFTᐊ') query = query.replace(u'_LJOIN', u'ᐅLEFTᐊ')
query=query.replace(u'_RJOIN' , u'ᐅRIGHTᐊ') query = query.replace(u'_RJOIN', u'ᐅRIGHTᐊ')
query=query.replace(u'_FJOIN' , u'ᐅFULLᐊ') query = query.replace(u'_FJOIN', u'ᐅFULLᐊ')
query=query.replace(u'_PROJECTION' , u'π') query = query.replace(u'_PROJECTION', u'π')
query=query.replace(u'_RENAME_TO' , u'') query = query.replace(u'_RENAME_TO', u'')
query=query.replace(u'_SELECTION' , u'σ') query = query.replace(u'_SELECTION', u'σ')
query=query.replace(u'_RENAME' , u'ρ') query = query.replace(u'_RENAME', u'ρ')
query=query.replace(u'_DIVISION' , u'÷') query = query.replace(u'_DIVISION', u'÷')
return query return query
def exec_query(command): def exec_query(command):
'''This function executes a query and prints the result on the screen '''This function executes a query and prints the result on the screen
if the command terminates with ";" the result will not be printed if the command terminates with ";" the result will not be printed
''' '''
command=unicode(command,'utf-8') command = unicode(command, 'utf-8')
#If it terminates with ; doesn't print the result # If it terminates with ; doesn't print the result
if command.endswith(';'): if command.endswith(';'):
command=command[:-1] command = command[:-1]
printrel=False printrel = False
else: else:
printrel=True printrel = True
# Performs replacements for weird operators
command = replacements(command)
# Finds the name in where to save the query
parts = command.split('=', 1)
#Performs replacements for weird operators if len(parts) > 1 and rtypes.is_valid_relation_name(parts[0]):
command=replacements(command) relname = parts[0]
query = parts[1]
#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: else:
relname='last_' relname = 'last_'
query=command query = command
# Execute query
#Execute query
try: try:
pyquery=parser.parse(query) pyquery = parser.parse(query)
result=eval(pyquery,relations) result = eval(pyquery, relations)
print colorize("-> query: %s" % pyquery.encode('utf-8'),0x00ff00) print colorize("-> query: %s" % pyquery.encode('utf-8'), 0x00ff00)
if printrel: if printrel:
print print
print result print result
relations[relname]=result relations[relname] = result
completer.add_completion(relname) completer.add_completion(relname)
except Exception, e: except Exception, e:
print colorize(e,ERROR_COLOR) print colorize(e, ERROR_COLOR)
def main(files=[]): def main(files=[]):
print colorize('> ',PROMPT_COLOR) + "; Type HELP to get the HELP" 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) + "; Completion is activated using the tab (if supported by the terminal)"
for i in files: for i in files:
load_relation(i) load_relation(i)
@ -301,11 +312,10 @@ def main(files=[]):
readline.parse_and_bind('set editing-mode emacs') readline.parse_and_bind('set editing-mode emacs')
readline.set_completer_delims(" ") readline.set_completer_delims(" ")
while True: while True:
try: try:
line = raw_input(colorize('> ',PROMPT_COLOR)) line = raw_input(colorize('> ', PROMPT_COLOR))
if isinstance(line,str) and len(line)>0: if isinstance(line, str) and len(line) > 0:
exec_line(line) exec_line(line)
except KeyboardInterrupt: except KeyboardInterrupt:
print print
@ -317,4 +327,3 @@ def main(files=[]):
if __name__ == "__main__": if __name__ == "__main__":
main() main()