Ejemplo n.º 1
0
def ExportNotes(DBcursor, currentPath):
    #create a table with notes
    # "_id","lon","lat","altim","ts","description","text","form","style","isdirty"
    notes = DBcursor.execute("SELECT * FROM notes")
    notesTable = Table([
        "_id", "lon", "lat", "altim", "ts", "description", "text", "form",
        "style", "isdirty"
    ])
    notesTableFields = [QgsField("_id", QVariant.Int), QgsField("lon", QVariant.Double), QgsField("lat", QVariant.Double),QgsField("altim", QVariant.Double), \
                                        QgsField("ts", QVariant.String),QgsField("description", QVariant.String), \
                                        QgsField("text", QVariant.String), \
                                        QgsField("form", QVariant.String),QgsField("style", QVariant.String), \
                                        QgsField("isdirty", QVariant.Int)]

    for note in notes:
        note = convertToStringList(note)
        notesTable.addRecordList(note)

    vl = exportPointToTempVector(notesTable,
                                 layName='notes',
                                 fields=notesTableFields)
    vl.setDisplayField('[% "text" %]')
    vl.loadNamedStyle(os.path.join(currentPath, 'styles', 'note_symb.qml'))
    # add to the TOC
    QgsMapLayerRegistry.instance().addMapLayer(vl)
Ejemplo n.º 2
0
class Game:

    # strat1 --> Strategy for Player1
    # strat2 --> Strategy for Player 2
    # strat must be a dictionary with the key string and value another dictionary
    #        with key int that determines the action (OR, 3Bet ...)
    #        and value array with the weights needed
    def __init__(self, strat1, strat2):
        self.bigBlind = 10
        self.starting_chips = 1500
        self.handsUpgradeTheBlinds = 10
        self.table = Table()
        self.table.bigBlind = self.bigBlind
        self.table.setChips(self.starting_chips)
        self.preflop = PreflopController(strat1["PF"], strat2["PF"])

    # This function will simulate one game and return who is the winner
    def simulateGame(self):
        while self.gameEnd() == 0:
            self.table.newHand()

    # this function will determine if the program needs to update the blinds,
    # if it needed auto increase the blinds
    def increaseBlinds(self):
        if self.table.hand_number % self.handsUpgradeTheBlinds == 0:
            self.table.bigBlind *= 2

    # This function will determine if the game had ended and return the winner   (1 or 2)
    # or will retunr 0 if the game had not end yet
    def gameEnd(self):
        if self.table.player1.chips == 0:
            return 2
        if self.table.player2.chips == 0:
            return 1
        return 0
Ejemplo n.º 3
0
    def __init__(self, argv):    

        FILE = open("RunInfoAll.txt","w")

        for siteIdx in range(1,4):
            # 1,2,3  -> 1,2,4
            site = siteIdx
            if siteIdx==3:
                site = 4
            
            print siteIdx,argv[siteIdx]
            table = Table()
            table.read( argv[siteIdx] )

            if siteIdx==1:
                FILE.writelines( table.headerLine )

            for row in range(0, table.nRows):
                # print table.columns["Site"][row]
                if int( table.columns["Site"][row] ) == site:
                    for col in range(0, len(table.fieldNames)):
                        FILE.writelines( table.columns[ table.fieldNames[col] ][row] )
                        FILE.writelines("\t")
                    FILE.writelines("\n")
                                                 
        FILE.close()
Ejemplo n.º 4
0
    def join(self, table1, table2, where_list_and, where_list_or, name):
        output_table = Table(name)
        output_table.data_array = np.zeros(
            (0, len(table1.data_array[0]) + len(table2.data_array[0])),
            dtype=object)

        table1 = copy.deepcopy(table1)
        table2 = copy.deepcopy(table2)

        if len(where_list_and) == 0 and len(where_list_or) == 0:
            pass
        else:
            # rename the dictionary keys by adding prefix of table name
            temp1 = {}
            temp2 = {}
            temp3 = {}
            for key in table1.column_dict:
                temp1[table1.name + '.' + key] = table1.column_dict[key]
                temp3[table1.name + '_' + key] = table1.column_dict[key]
            for key in table2.column_dict:
                temp2[table2.name + '.' + key] = table2.column_dict[key]
                temp3[table2.name + '_' +
                      key] = table2.column_dict[key] + len(temp1)
            table1.column_dict = temp1
            table2.column_dict = temp2

            output_table.column_dict = temp3

            for i in range(len(table1.data_array)):
                for j in range(len(table2.data_array)):
                    to_add_or = False  # set OR condition
                    for [column1, operator, column2] in where_list_or:
                        condition = self.__join_condition(
                            column1, operator, column2, table1, table2, i, j)
                        if condition is True:
                            to_add_or = True

                    if len(where_list_and) == 0:
                        to_add_and = False  # set AND condition
                    else:
                        to_add_and = True

                    for [column1, operator, column2] in where_list_and:
                        condition = self.__join_condition(
                            column1, operator, column2, table1, table2, i, j)
                        to_add_and = condition and to_add_and

                    if (to_add_and or to_add_or) is True:
                        vector = np.zeros((1, 0), dtype=object)
                        vector = np.append(vector,
                                           np.expand_dims(table1.data_array[i],
                                                          axis=0),
                                           axis=1)
                        vector = np.append(vector,
                                           np.expand_dims(table2.data_array[j],
                                                          axis=0),
                                           axis=1)
                        output_table.data_array = np.append(
                            output_table.data_array, vector, axis=0)
        return output_table
 def __init__(self, servers=None, tables=None):
     if servers is None:
         server1 = Server("Lisa", False)
         server2 = Server("Bob", False)
         server3 = Server("Joe", False)
         server4 = Server("Kate", False)
         server5 = Server("John", False)
         servers = [server1, server2, server3, server4, server5]
         self.servers = servers
     else:
         self.servers = servers
     if tables is None:
         table1 = Table(4, "W", True)
         table2 = Table(10, "B", True)
         table3 = Table(4, "N", True)
         table4 = Table(4, "N", True)
         table5 = Table(2, "W", True)
         table6 = Table(6, "N", True)
         table7 = Table(3, "O", True)
         table8 = Table(2, "N", True)
         table9 = Table(12, "O", True)
         table10 = Table(2, "N", True)
         self.tables = [
             table1, table2, table3, table4, table5, table6, table7, table8,
             table9, table10
         ]
     else:
         self.tables = tables
Ejemplo n.º 6
0
    def testHandSize(self):
        table1 = Table(4)
        table1.deal(5)
        playersCards1 = table1.getHands()

        for hand in playersCards1:
            self.assertEqual(len(hand), 5, "Hand size was incorrectly dealt")
Ejemplo n.º 7
0
def testJoin():
    from Field import VarCharField
    from Table import Table
    from DBObject import DBObject

    class Fruit(DBObject):
        def __init__(self):
            self.fruit = ''
            self.taste = ''
            DBObject.__init__(self)

    class Taste(DBObject):
        def __init__(self):
            self.taste = ''
            self.goodbad = ''
            DBObject.__init__(self)

    FruitFields = [
        VarCharField('fruit', length=16, key=True),
        VarCharField('taste', length=16, index=True)
    ]
    FruitTable = Table('Fruit', Fruit, fields=FruitFields)

    TasteFields = [
        VarCharField('taste', length=16, key=True),
        VarCharField('goodbad', length=16, index=True)
    ]
    TasteTable = Table('Taste', Taste, fields=TasteFields)

    join = Join(FruitTable, TasteTable, 'Fruit.taste=Taste.taste')
    print join.joinStr()
Ejemplo n.º 8
0
def read_files():

    path = os.curdir + "/csv_files/"

    print(os.curdir)
    files = os.listdir(path)
    tables = []

    for file in files:
        if file.endswith(".csv"):

            t = Table("", "", "")

            # set table name from file name
            t.tableName = file.title()[:-4].lower()

            f = open(path + file)

            csv_f = csv.reader(f)
            csv_list = list(csv_f)

            # set headers and rest of data
            t.headers = csv_list[0]
            t.rows = csv_list[1:]

            tables.append(t)

    print_file_names(tables)
    return tables
Ejemplo n.º 9
0
def retrieve_training_set():

    training_pool = Table("training_pool_3_targets.table")

    tmp = []
    for name in [row["name"] for row in training_pool]:
        if name in tmp:
            print name
        else:
            tmp.append(name)

    positive_training_pool = []
    negative_training_pool = []

    training_fraction = 0.7

    print "<---", "cpxR" in [row["name"] for row in training_pool]

    for row in training_pool:
        if int(row["label"]) < 0:
            negative_training_pool.append(row["name"])
        else:
            positive_training_pool.append(row["name"])

    data_pool = Table("table_s6_range_0.csv")

    positive_training_names = \
     random_names_for_training(positive_training_pool,
             training_fraction)

    negative_training_names = \
     random_names_for_training(negative_training_pool,
             training_fraction)

    positive_validation_names = \
     [name for name in positive_training_pool if name not in positive_training_names]
    negative_validation_names = \
     [name for name in negative_training_pool if name not in negative_training_names]

    training_set = retrieve_data(data_pool, positive_training_names)
    training_set.extend(retrieve_data(data_pool, negative_training_names))
    training_labels = [1] * len(positive_training_names)
    training_labels.extend([0] * len(negative_training_names))

    validation_set = retrieve_data(data_pool, positive_validation_names)
    validation_set.extend(retrieve_data(data_pool, negative_validation_names))
    validation_labels = [1] * len(positive_validation_names)
    validation_labels.extend([0] * len(negative_validation_names))

    training_set = np.array(training_set)
    training_labels = np.array(training_labels)
    validation_set = np.array(validation_set)
    validation_labels = np.array(validation_labels)

    training_names = positive_training_names + negative_training_names
    validation_names = positive_validation_names + negative_validation_names

    print len(training_set), len(training_labels)

    return training_set, training_labels, validation_set, validation_labels, training_names, validation_names
Ejemplo n.º 10
0
def read_files():

    path = os.curdir+"/csv_files/"

    print(os.curdir)
    files = os.listdir(path)
    tables = []

    for file in files:
        if file.endswith(".csv"):

            t = Table("", "", "")

            # set table name from file name
            t.tableName = file.title()[:-4].lower()

            f = open(path + file)

            csv_f = csv.reader(f)
            csv_list = list(csv_f)

            # set headers and rest of data
            t.headers = csv_list[0]
            t.rows = csv_list[1:]

            tables.append(t)

    print_file_names(tables)
    return tables
Ejemplo n.º 11
0
def Master():
    Sleep()

    move = MoveTo()

    rospy.init_node("node_master", anonymous=True)
    rospy.loginfo("[MASTER] BEGIN")
    #	GetSide()

    Sleep()

    side = GetSide()

    rospy.sleep(5.)
    table = Table(side)
    rospy.loginfo("debranchement possible cote :  :" + str(side))

    Sleep()

    launch = LaunchRobot()

    Sleep()

    table.Parcours()
    #	move.GoTo(2600, 800, 0)
    rospy.loginfo("[MASTER] END")
Ejemplo n.º 12
0
 def __init__(self, inputFile):
     self.inputStack = deque()
     tup = Tuple()
     tup.x = '$'
     tup.y = 0
     self.workingStack = deque([tup])
     self.outputStack = []
     self.inputFile = inputFile
     self.grammar = Grammar()
     #self.grammar.readFromFile("grammar.txt")
     self.grammar.readFromFile("myGrammar.txt")
     self.table = Table(self.grammar)
     self.table.makeCanonicalCollection()
     self.table.makeTable()
     self.operators = [
         "=", "+", "-", "*", "/", ">", "<", "<=", ">=", "==", "<>"
     ]
     self.separators = ["{", "}", "(", ")", ";"]
     self.reservedWords = [
         "main", "char", "integer", "READ", "PRINT", "IF", "THEN", "ELSE",
         "WHILE", "DO"
     ]
     specialSymbols = [
         "identifier", "constant"
     ] + self.reservedWords + self.operators + self.separators
     self.codificTable = dict([(i, specialSymbols[i])
                               for i in range(len(specialSymbols))])
     #self.readInput()
     self.readGrammar()
     self.derivString = ""
Ejemplo n.º 13
0
    def init_ui(self):
        self.table = Table()
        self.subject_names, self.max_lab_count, self.lab_maiking = self.table.Make_table()

        self.labels = [self.subject_names.__len__() * self.max_lab_count]
        self.labels_names = [self.subject_names.__len__()]

        self.ctrl_press = False
        self.prosent_add_maiking = 10
        self.square_id = 0
        self.x = 30
        self.y = 100
        self.margin = 120


        self.qle = QPushButton("X", self)
        self.qle.move(465, 200)
        self.qle.clicked.connect(self.close)
        self.qle.setFont(QFont('Ralleway', 14))
        self.qle.setStyleSheet(
            "color: #a0302d; "
            "max-height: 24px; "
            "max-width: 24px; ")

        self.smap = QSignalMapper(self)
        self.GetSquares()
        self.smap.mapped.connect(self.on_click)
Ejemplo n.º 14
0
def ThreeNFConversion(table):
    MinimalCover(table)
    transitiveDependency = TansistiveDependency(table)
    table.show()
    print("Transistive Dependency: ")
    print(transitiveDependency)
    if (len(transitiveDependency[LEFT]) == 0):
        table.setNormalForm("3NF")
        return [table]
    threeNFtables = list()

    for index in range(len(transitiveDependency[LEFT])):
        tfd = [
            transitiveDependency[LEFT][index],
            transitiveDependency[RIGHT][index]
        ]
        attr = tfd[LEFT].union(tfd[RIGHT])
        table.deleteFdForNormalization(tfd)
        threeNFtables.append(
            Table(attr, [[tfd[LEFT]], [tfd[RIGHT]]], "3NF", table.getId(), 0))

    table.setNormalForm("3NF")
    threeNFtables.append(
        Table(table.getAttr(), table.getFdsSet(), table.getNormalForm(),
              table.getId(), 0))
    return threeNFtables
Ejemplo n.º 15
0
def main(
        start_date: str = typer.Argument(..., help=start_date_help),
        end_date: Optional[str] = typer.Argument(None, help=end_date_help),
):
    month_from, year_from = start_date.split("/")
    month_to, year_to = (end_date.split("/") if end_date else (
        month_from,
        year_from,
    ))

    typer.echo(
        f"Period: between {month_from}-{year_from} and {month_to}-{year_to}")
    typer.echo("Fetching released albums for the period on Metal Archives...")
    albums = get_released_albums(month_from=month_from,
                                 month_to=month_to,
                                 year_from=year_from,
                                 year_to=year_to)
    typer.echo(f"Found [{len(albums)}] albums on Metal Archives")

    typer.echo("Setting up Spotify API...")
    load_dotenv()
    spotify_api = setup_spotify()

    typer.echo("Fetching album data on Spotify...")
    with typer.progressbar(albums) as progress:
        for album in progress:
            spotify_album = search_album(album, spotify_api)
            if spotify_album:
                album["spotify_album"] = spotify_album
                album["date"] = spotify_album.release_date

    markdown_table = Table(albums)
    markdown_table.print_markdown()
Ejemplo n.º 16
0
 def test_calculate_score_of_dealer_for_two_cards(self):
     table = Table(2, 4)
     cards = table.cards.stack[-1:-3:-1]
     table.distribute_card_to_dealer()
     table.distribute_card_to_dealer()
     score = cards[0][1] + cards[1][1]
     self.assertEqual(score, table.calc_score(table.dealer))
Ejemplo n.º 17
0
 def write(self, writePgLinks=True):
     # returns a list with each element as (link to table
     # row, row)
     ret_data = []
     self.mkdir_p(self.outputdir)
     nRows = self.table.countRows()
     pgCounter = 1
     for i in range(0, nRows, self.rowsPerPage):
         rowsSubset = self.table.rows[i : i + self.rowsPerPage]
         t = Table(self.table.headerRows + rowsSubset)
         ret_data.append((pgCounter, rowsSubset))
         f = open(os.path.join(self.outputdir, str(pgCounter) + '.html'), 'w')
         f.write('<head>')
         f.write('<script src="http://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>\n')
         f.write('<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>\n')
         f.write('</head>')
         pgLinks = self.getPageLinks(int(math.ceil(nRows * 1.0 / self.rowsPerPage)),
                 pgCounter, self.pgListBreak)
         if writePgLinks:
             f.write(pgLinks)
         f.write('<p>' + self.desc + '</p>')
         f.write(t.getHTML(makeChart = self.makeChart, transposeTableForChart=self.transposeTableForChart, chartType = self.chartType, chartHeight = self.chartHeight))
         if writePgLinks:
             f.write(pgLinks)
         f.write(self.getCredits())
         f.close()
         pgCounter += 1
     return ret_data
Ejemplo n.º 18
0
    def count_group(self, table, target_col, by_list, name):
        output_table = Table(name)
        dict_list = [str("count(" + target_col + ")")]
        dict_list.extend(by_list)
        output_table.column_dict = {
            col_name: ind
            for ind, col_name in enumerate(dict_list)
        }
        output_table.data_array = np.zeros((0, len(by_list) + 1), dtype=object)

        group_dict = self.group_by(table, target_col,
                                   by_list)  # get dict of groups

        for identifier, group_table in group_dict.items():
            count_table = self.count(group_table, target_col, 'count')
            data_array = np.expand_dims(
                group_table.data_array[0],
                axis=0)  # get the first row of data array
            # data_array = np.column_stack((count_table.data_array[0], data_array))
            data_array[0][0] = count_table.data_array[0][0]
            output_table.data_array = np.append(output_table.data_array,
                                                data_array,
                                                axis=0)

        return output_table
Ejemplo n.º 19
0
    def sum_group(self, table, target_col, by_list, name):
        """
        @params: - target_col : column_name to sum
                 - by_list : ['pricerange', 'time']
        """
        output_table = Table(name)
        dict_list = [str("count(" + target_col + ")")]
        dict_list.extend(by_list)
        output_table.column_dict = {
            col_name: ind
            for ind, col_name in enumerate(dict_list)
        }
        output_table.data_array = np.zeros((0, len(by_list) + 1), dtype=object)
        group_dict = self.group_by(table, target_col, by_list)

        for identifier, group_table in group_dict.items():
            sum_table = self.sum(group_table, target_col, 'count')
            data_array = np.expand_dims(
                group_table.data_array[0],
                axis=0)  # get the first row of data array
            data_array[0][0] = sum_table.data_array[0][0]
            output_table.data_array = np.append(output_table.data_array,
                                                data_array,
                                                axis=0)

        return output_table
Ejemplo n.º 20
0
    def group_by(self, table, target_col, by_list):
        group_dict = {}
        group_index = 0

        lst = [target_col]
        lst.extend(by_list)

        table = self.select(table, lst, [], [],
                            'temp')  # reduce columns by target and by_list

        for i in range(len(table.data_array)):
            vector = table.data_array[i]
            val_group_list = []
            for bys in by_list:
                col_index = table.column_dict[bys]
                val = vector[col_index]
                val_group_list.append(val)  # group identifier
            identifier = str(val_group_list)

            if identifier not in group_dict:  # if new group identified
                temp_table = Table(group_index)
                group_dict[identifier] = temp_table
                group_index += 1
                temp_table.column_dict = copy.deepcopy(table.column_dict)
                temp_table.data_array = copy.deepcopy(
                    np.expand_dims(vector, axis=0))
            else:  # if group identifier exists, append vector to group table data array
                temp_table = group_dict[identifier]
                temp_table.data_array = np.append(temp_table.data_array,
                                                  np.expand_dims(vector,
                                                                 axis=0),
                                                  axis=0)

        return group_dict
Ejemplo n.º 21
0
    def count(self, table, target_col, name):
        count = len(table.data_array)

        output_table = Table(name)
        output_table.column_dict['count(' + target_col + ')'] = 0
        output_table.data_array = np.array([[count]], dtype=object)
        return output_table
Ejemplo n.º 22
0
 def __init__(self, variable, condition_variables=[]):
     if len(condition_variables)>0:
         condition_variables.sort(key = lambda x: x.name)
     self.variable = variable
     self.condition_variables = condition_variables
     self.table = Table([self.variable]+self.condition_variables) 
     
     self.__variable_dict = self.__buildVariableDict(self.variable, self.condition_variables)
Ejemplo n.º 23
0
	def __init__(self, w, h, cb):
		self.width = w
		self.height = h
		self.progress_callback = cb

		self.table = Table(self.width, self.height)
		self.place_items()
		self.new_generation()
Ejemplo n.º 24
0
 def __init__(self, strat1, strat2):
     self.bigBlind = 10
     self.starting_chips = 1500
     self.handsUpgradeTheBlinds = 10
     self.table = Table()
     self.table.bigBlind = self.bigBlind
     self.table.setChips(self.starting_chips)
     self.preflop = PreflopController(strat1["PF"], strat2["PF"])
Ejemplo n.º 25
0
 def __init__(self):
     self.sunkBalls = []
     self.points = 0
     self.table = Table()
     self.ready = False
     self.balls = self.addBalls()
     self.writeState(STATE_FILE)
     self.player = Player(self)
Ejemplo n.º 26
0
 def testNegativePlayers(self):
     try:
         table3 = Table(-3)
         playersCards3 = table3.getHands()
         self.assertEqual(len(playersCards3), 0,
                          "Number of players initialized incorrect")
     except ValueError:
         pass
Ejemplo n.º 27
0
    def test_check_cell_out_table(self):
        table = Table()

        table.height = 3
        table.weight = 2

        is_in_table = table.check_cell_is_in_table(3, 1)

        self.assertFalse(is_in_table)
Ejemplo n.º 28
0
def showTableNames():
    cursor = c.execute('''
        SELECT name 
        FROM sqlite_master
        WHERE type = "table"
    ''')

    table = Table(cursor.fetchall(), "Table Names")
    table.print()
Ejemplo n.º 29
0
    def __init__(self):
        self.game_id = random.randint(1000000, 9000000)
        self.deck = Deck()
        self.table = Table()
        self.user = False
        self.user_player = None
        self.display = None

        random.seed(datetime.datetime.now().strftime('%S'))
Ejemplo n.º 30
0
    def __init__ (self, callback, container, *args, **kwargs):
        Table.__init__ (self, *args, **kwargs)
        self.id  = "sortablelist_%d" %(self.uniq_id)
        self.url = "/sortablelist_%d"%(self.uniq_id)
        self.container = container

        # Register the public URL
        publish (self.url, changed_handler_func, method='POST',
                 callback=callback, key_id='%s_order'%(self.id), **kwargs)
Ejemplo n.º 31
0
 def test_when_score_of_dealer_and_player_is_equal_and_none_have_blackjack(
         self):
     table = Table(2, 1)
     table.dealer.hand = [('10', 10), ('K', 10)]
     table.players[0].hand = [('10', 10), ('K', 10), ('A', None)]
     table.dealer.score = 20
     table.players[0].score = 20
     results = [{'dealer': 'Push', 'player_1': 'Push'}]
     self.assertEqual(results, table.get_the_results_of_game())
Ejemplo n.º 32
0
    def test_check_cell_in_table(self):
        table = Table()

        table.height = 3
        table.weight = 2

        is_in_table = table.check_cell_is_in_table(1, 1)

        self.assertTrue(is_in_table)
Ejemplo n.º 33
0
    def __init__(self):
        self.deck = Deck()
        self.deck.shuffle()

        self.table = Table()

        for i in range(12):
            self.table.addCard(self.deck.draw())
        self.table.print()
Ejemplo n.º 34
0
    def __init__ ( self, handle ):
	self.name   =  'nrdb'
        
	self.fields = (
			('nid', 'INT UNSIGNED NOT NULL'),
		)
	self.indices = (
			'UNIQUE (nid)',
		)
	Table.__init__( self, handle )
Ejemplo n.º 35
0
    def __init__ (self, callback, container, *args, **kwargs):
        Table.__init__ (self, *args, **kwargs)
        self.id  = "sortablelist_%d" %(self.uniq_id)
        self.url = "/sortablelist_%d"%(self.uniq_id)
        self.container = container

        # Secure submit
        srv = get_server()
        if srv.use_sec_submit:
            self.url += '?key=%s' %(srv.sec_submit)

        # Register the public URL
        publish (r"^/sortablelist_%d"%(self.uniq_id), changed_handler_func,
                 method='POST', callback=callback, key_id='%s_order'%(self.id), **kwargs)
Ejemplo n.º 36
0
    def __init__ ( self, handle, root = "domains"):

	self.fields = (
            ('nid', 'INT UNSIGNED NOT NULL'),
            ('start', 'SMALLINT UNSIGNED NOT NULL DEFAULT 0'),
            ('end', 'SMALLINT UNSIGNED NOT NULL DEFAULT 0'),
            ('rep_ali', 'BLOB NOT NULL'),
            ('domain_id', self.mTypeDomainId),
            ('domain_from', 'SMALLINT UNSIGNED NOT NULL DEFAULT 0'),
            ('domain_to', 'SMALLINT UNSIGNED NOT NULL DEFAULT 0'),
            ('domain_ali', 'BLOB NOT NULL'),
            ('family', self.mTypeDomainClass ),
            ) + self.mExtraFields
        
	self.indices = (
            'INDEX (nid)',
            'INDEX (domain_id)',
            'INDEX (family)'
            ) + self.mExtraIndices
        
        self.mFieldsNr = (
            ('nid INT UNSIGNED NOT NULL'),
            ('start SMALLINT UNSIGNED NOT NULL DEFAULT 0'),
            ('end SMALLINT UNSIGNED NOT NULL DEFAULT 0'),
            ('family %s' % self.mTypeDomainClass),
            )
        self.mIndicesNr = ( 'INDEX (nid)',
                            'INDEX (family)',
                            )

        self.mRootName = root
        
	Table.__init__( self, handle )

        # minimum length of an assignment
        self.mMinAssignmentLength = 10

        # whether or not to shorten domains
        self.mShortenDomains = 0

        # minimum overlap between domains of the same did in order
        # for them to be joined for making non-redundant set
        # (had problems with scop and hemoglobins, there was one residue overlap)
        self.mMinRedundancyOverlap = 0

        ## field to use as class identifier, this is the default
        self.mClassNr = "family"

        ## additional info in each row, used for propagation
        self.mAdditionalInfo = []
Ejemplo n.º 37
0
    def __init__(self, handle, root):

        self.mRootName = root

        Table.__init__(self, handle)

        self.fields = (
            ("family", self.mTypeDomainClass),
            ("nunits", "INT UNSIGNED NOT NULL DEFAULT 0"),
            ("nsequences", "INT UNSIGNED NOT NULL DEFAULT 0"),
            ("nresidues", "INT UNSIGNED NOT NULL DEFAULT 0"),
            ("length", "SMALLINT UNSIGNED NOT NULL DEFAULT 0"),
        ) + self.mExtraFields

        self.indices = ("UNIQUE (family)",) + self.mExtraIndices
Ejemplo n.º 38
0
    def __init__(self, connectionPool, name):
        self.tabName = name
        self.connectionPool = connectionPool
        self.serverVersion = connectionPool.ServerVersion()
        for part in self.connectionPool.dsn.split():
            if part.startswith("dbname="):
                self.dbName = part[7:]

        cursor = connectionPool.GetCursor()
        row = cursor.ExecuteRow(
            """
      SELECT c.oid, relhasoids
        FROM pg_class c
       WHERE oid=oid(regclass('%s'))
    """
            % self.tabName
        )
        if not row:
            raise Exception(xlt("No such table: %s") % self.tabName)
        self.oid = row["oid"]
        self.hasoids = row["relhasoids"]

        self.constraints = cursor.ExecuteDictList(Table.getConstraintQuery(self.oid))

        self.colSpecs = {}
        self.colNames = []
        set = cursor.ExecuteSet(
            """
        SELECT attname, attnotnull, atttypid, atttypmod, t.typcategory, CASE WHEN typbasetype >0 THEN format_type(typbasetype,typtypmod) ELSE format_type(atttypid, atttypmod) END as formatted
         FROM pg_attribute a
         JOIN pg_type t ON t.oid=atttypid
        WHERE attrelid=%d
          AND (attnum>0 OR attnum = -2) AND NOT attisdropped
        ORDER BY attnum
    """
            % self.oid
        )
        for row in set:
            attname = row["attname"]
            self.colNames.append(attname)
            self.colSpecs[attname] = ColSpec(row)

        self.primaryConstraint = None
        if self.hasoids:
            self.keyCols = ["oid"]
        else:
            for c in self.constraints:
                if c.get("indisprimary"):
                    self.primaryConstraint = c
                    break
            if not self.primaryConstraint:
                for c in self.constraints:
                    if c.get("isunique"):
                        self.primaryConstraint = c
                        break
            if self.primaryConstraint:
                self.keyCols = self.primaryConstraint.get("colnames")
            else:
                self.keyCols = []
Ejemplo n.º 39
0
 def init(self):
     self.recordList = []
     self.tables = {}
     self.table = Table(self.path, self.pageSize)
     self.table.setTableFDP(4)
     self.table.setTableNumber(2)
     self.setMsysObjectColumns()
     self.makeTables()
Ejemplo n.º 40
0
 def __init__(self, lines):
   # Turn padding into preceding number
   lines = [ str(calculate_padding(line)) + ' ' + line.strip() for line in lines ]
   self.table = Table()
   self.lines = Lines(lines)
   self.terminate = False
   self.result = ""
   return
Ejemplo n.º 41
0
    def __init__ ( self, handle, root ):
        
        self.mRootName = root
        
	Table.__init__( self, handle)

    	self.fields = (
            ('family', self.mTypeDomainClass),
            ('nunits', 'INT UNSIGNED NOT NULL DEFAULT 0'),
            ('nsequences', 'INT UNSIGNED NOT NULL DEFAULT 0'),
            ('nresidues', 'INT UNSIGNED NOT NULL DEFAULT 0'),            
            ('length', 'SMALLINT UNSIGNED NOT NULL DEFAULT 0'),
            ) + self.mExtraFields
        
	self.indices = (
            'UNIQUE (family)',
            ) + self.mExtraIndices
Ejemplo n.º 42
0
def parseTable(handle):
    inTable = handle.Offset

    # Get table title
    title = inTable(1,2).Value
    if title is None:
        title = ""

    # Build table object
    outTable = Table(title)

    # Get axis titles
    outTable.yTitle = inTable(2, 1).Value
    outTable.xTitle = inTable(2, 3).Value

    # Get axis units
    outTable.yUnits = inTable(3, 1).Value
    if outTable.yUnits is None:
        outTable.yUnits = ""
    outTable.xUnits = inTable(3, 3).Value
    if outTable.xUnits is None:
        outTable.xUnits = ""

    # Iterate over the table
    i = 4
    while (not inTable(i, 1).Value is None):
        outTable.yValues.append(str(inTable(i, 1).Value))
        outTable.yErrors.append(str(inTable(i, 2).Value))
        outTable.xValues.append(str(inTable(i, 3).Value))
        outTable.xErrors.append(str(inTable(i, 4).Value))
        i += 1
        print inTable(i, 2).Value

    return outTable
Ejemplo n.º 43
0
def main ():
  
  prog = sys.argv[1]
  ## open program to parse (read whole program into memory, it's small enough)
  with open(prog,'r') as f:
    towerProgram = Program.removeCommentedText(f.read())
    
  ### parse instrumentlibrary for additional metadata
  insLib = parse('instrumentlibrary.xml')  
    
  ## parse program to get aliases, constants, and units
  aliases = Program.getAliases(towerProgram)  
  constants = Program.getConstants(towerProgram)
  units = Program.getUnits(towerProgram)

  ## start and initialize new xml for this program
  doc = xmlutils.createNewProgramXML()
  xmlutils.addTextNodeToRoot(doc,"progName",prog)
  tablesNode = xmlutils.addNode(doc,'root','tables')
 
  ### put datatable info in the progxml
  tables = Program.getTables(towerProgram)
  for text in tables:
    ### use text and program info to construct Table object
    table = Table(text,aliases,constants,units)

    ### add table info (name and interval) to xml
    tableNode = doc.createElement("table")
    table.addTableInfo(doc,tableNode)

    ### process output instructions and store variable info
    ### to the progxml
    variablesNode = xmlutils.addNode(doc,tableNode,'variables')
    table.processOutputInstructions(doc,variablesNode,insLib)
   
    tablesNode.appendChild(tableNode)


  #do some cleaning up of xml (so it's easy for humans to view in texteditor)
  progxml = xmlutils.cleanupXML(doc)
  ### save progxml
  xmlout = open(prog + '.xml','w')
  print >>xmlout, progxml
Ejemplo n.º 44
0
    def toTable(self, colName, fmt=None, type_=None, title="", meta=None):
        """
        Generates a one column :py:class:`~libms.DataStructures.Table`
        from an expression.

        Example: ``tab = substances.name.toTable()``
        """
        from Table import Table

        return Table.toTable(colName, self.values, fmt, type_, title, meta)
Ejemplo n.º 45
0
    def __init__ ( self, handle ):
	self.name   =  'nrdb'
	self.fields = (
			('updated', 'TIMESTAMP'),
			('nid', 'INTEGER UNSIGNED NOT NULL AUTO_INCREMENT'),
			('hid', 'CHAR(22) NOT NULL'),
			('sequence', 'TEXT NOT NULL'),
			('sequencedbs_id', 'TINYINT UNSIGNED NOT NULL'),
			('accessionnumber', 'VARCHAR(20) BINARY NOT NULL'),
			('identifier', "VARCHAR(20) BINARY  NOT NULL DEFAULT ''"),
			('description', "VARCHAR(255) NOT NULL DEFAULT ''"),
			('created', 'DATE NOT NULL'),
			('length', 'MEDIUMINT UNSIGNED NOT NULL DEFAULT 0'),
			('filter', 'TINYINT   UNSIGNED NOT NULL DEFAULT 100'),
		)
	self.indices = (
			'PRIMARY KEY (nid)',
			'INDEX  hid (hid(4))',
			'INDEX  updated (updated)',
			'INDEX  filter (filter)',
		)
        Table.__init__( self, handle )
Ejemplo n.º 46
0
 def init(self):
     self.tables = {}
     self.deletedTables = {}
     self.table = Table(self.path, self.pageSize)
     self.table.setTableFDP(4)
     self.table.setTableNumber(2)
     self.setMsysObjectColumns()
     self.table.findNormalPageList()
     recordList = self.table.getNormalData()
     self.makeTables(recordList, "")
     if self.swich == True :
         recordList = self.table.getAbnormalData()
         self.makeTables(recordList, "Deleted_")
Ejemplo n.º 47
0
	def __init__(self):
		self.stateDict = {}
	
		print "starting Table init"
		self.tableObj = Table()
		p1 = Player("p1", 1000)
		p2 = Player("p2", 1000)
		p3 = Player("p3", 1000)
		self.tableObj.addPlayer(p1)
		self.tableObj.addPlayer(p2)
		self.tableObj.addPlayer(p3)
		self.tableObj.beginRound()
		print "starting UI"
		self.UIObj = UI(self)
		self.UIObj.loop()
Ejemplo n.º 48
0
    def _init_data(self, file_path):
        """
            Initializes the CSV data. Uses the read_file method to read the data from the file and uses the
            parse_file_content and extract_header methods to process the data.

            :param file_path: File path to the CSV file.
        """
        # TODO Use standard csv python module to read the csv file instead of using own parser.
        try:
            file_content = self._read_file(file_path)
            table_with_header = self._parse_file_content(file_content)
            table_header, table_body = self._extract_header(table_with_header)
            self._table = Table(table_header, table_body)
        except ValueError as error:
            raise ValueError("Failed to parse the CSV file at '" + file_path + "'. " + error.message)
        except IOError:
            raise ValueError("Could not read the proxy file. Check if the file path is correct and if the file is "
                             "readable")
Ejemplo n.º 49
0
    def load(self):
        timestamp = 0
        db = Database()
        
        for file_name in DATA_FILE_NAMES:
            # generate the name of the table from the filename
            table_name = re.match('[^\.]+', file_name).group()
            new_table = Table(table_name)
            
            full_path = os.path.join(self.data_dir, file_name)
            with open(full_path, 'r') as data_file:
                first_line = True

                for line in data_file:
                    elems = line.split()
                    
                    if (first_line): 
                        # generate col names from the filename plus col num
                        # starting with timestamp
                        new_table.add_column_name(TIMESTAMP_COL_NAME)
                        num_columns = len(elems) + 1
                        for col_num in range(1, num_columns):
                            new_table.add_column_name(table_name + str(col_num))

                        first_line = False
 
                    # add vals for each new row, starting with timestamp
                    new_table.add_value(timestamp, TIMESTAMP_COL_NAME, timestamp)
                    for elem_num in range(len(elems)):
                        col_name = table_name + str(elem_num+1)
                        new_table.add_value(timestamp, col_name, elems[elem_num])

                    timestamp += 1
            # finally, add the table we just built to the db
            db.add_table(new_table)

        return db
Ejemplo n.º 50
0
def classify(C,lnc,AM,discard):
    result=Table()
    result.key=1
    result.col_names=['gid','class']
    for i in C:
        result.data.append([i,'novel_coding'])
        result.row_names[i]=len(result.row_names)
    for i in lnc:
        result.data.append([i,'novel_lincRNA'])
        result.row_names[i]=len(result.row_names)
    for i in AM:
        result.data.append([i,'ambiguous_genes'])
        result.row_names[i]=len(result.row_names)
    for i in discard:
        result.data.append([i,'filter_out_noncoding'])
        result.row_names[i]=len(result.row_names)
    return result
Ejemplo n.º 51
0
def classify(KC,overlap_KC,KN,overlap_KN,discard_cnc_tmap_gids,unannotated):
    result=Table()
    result.key=1
    result.col_names=['gid','class']
    for i in KC:
        result.data.append([i,'known_coding'])
        result.row_names[i]=len(result.row_names)
    for i in overlap_KC:
        result.data.append([i,'undefinable'])
        result.row_names[i]=len(result.row_names)
    for i in KN:
        result.data.append([i,'known_lincRNA'])
        result.row_names[i]=len(result.row_names)
    for i in overlap_KN:
        result.data.append([i,'undefinable'])
        result.row_names[i]=len(result.row_names)
#    for i in discard_cnc_tmap_gids:
#        result.data.append([i,'discarded'])
#        result.row_names[i]=len(result.row_names)
    for i in unannotated:
        result.data.append([i,'potentially_novel'])
        result.row_names[i]=len(result.row_names)
    return result
Ejemplo n.º 52
0
class Bridget:
    def __init__(self,screen):
        self.screen=screen
        self.table=Table(self.screen)
        while True:
            self.table.playRubber(self.screen)
            UTILITIES.pressAnyKey(screen)
    def loop(self):
        self.ctrlDown=False
#        self.mouseDown=(0,0,0)
        while 1:
#            for event in pygame.event.get():
            #event=pygame.event.wait()
            #if not self.processEvent(event):
            #    return
            self.processEvent(pygame.event.wait())
            pygame.display.flip()
    def processEvent(self,event):
        if UTILITIES.globalShortcuts(event,self.ctrlDown):
            return
        elif event.type == KEYUP:
            if event.key == K_LCTRL or event.key == K_RCTRL:
                self.ctrlDown=False
        elif event.type == KEYDOWN:
            if event.key == K_LCTRL or event.key == K_RCTRL:
                self.ctrlDown=True
            #elif event.key==K_F1 or event.key==K_PAUSE or (self.ctrlDown and event.key==K_h):
            #    self.ctrlDown=False
            #    self.table.info.help.transient(self.screen)
            elif event.key==K_i:
                self.table.showHandsInfo(self.screen)
            elif event.key==K_b:
                self.table.bidding.historybox.transient(self.screen)
            #elif event.key==K_F5 or (event.key==K_n and self.ctrlDown):
            #    self.ctrlDown=False
            #    self.table.newHand(self.screen)
            elif event.key==K_F9:
                self.table.toggleShowAllHands(self.screen)
        return True
Ejemplo n.º 53
0
    def __init__(self, uid, machine_id):
        self.uid_ = uid
        self.mid_ = machine_id

        Table.__init__(self, "%s:%s" % (uid, machine_id))
Ejemplo n.º 54
0
import sys
sys.path.append('/home/rohit/Software/vis/PyHTMLWriter/src');
from Element import Element
from TableRow import TableRow
from Table import Table
from TableWriter import TableWriter
import numpy as np

t = Table()
for r in range(100):
    if r == 0:
        r = TableRow(isHeader = True)
    else:
        r = TableRow()
    for e in range(10):
        e = Element()
        pose = np.array([[587, 569, 490, 535, 621, 630, 512, 490, 488, 483, 576, 479, 457, 522, 550, 571, 491],[561, 447, 411, 393, 430, 537, 402, 298, 275, 201, 394, 377, 305, 289, 348, 367, 376]]).transpose().tolist()
        e.addImg("http://sun.pc.cs.cmu.edu/~rohit/Public/Images/himym_chairs.jpg", poses=[pose], width=500, imsize=[1280,768])
        
        r.addElement(e)
    t.addRow(r)
tw = TableWriter(t, 'out')
tw.write()

Ejemplo n.º 55
0
 def __init__(self, Cursor):
     Table.__init__(self, Cursor)
     self.Table = 'File'
Ejemplo n.º 56
0
 def __init__(self, Cursor):
     Table.__init__(self, Cursor)
     self.Table = 'DataModel'
Ejemplo n.º 57
0
class SemantickiAnalizator:
  """INIT"""
  def __init__(self, lines):
    # Turn padding into preceding number
    lines = [ str(calculate_padding(line)) + ' ' + line.strip() for line in lines ]
    self.table = Table()
    self.lines = Lines(lines)
    self.terminate = False
    self.result = ""
    return

  """CHECK EXPRESSIONS"""
  def check_expressions(self, expressions):
    if self.terminate: return False
    else: return self.lines.check_expressions(expressions)

  """ASSERT LEAF"""
  def assert_leaf(self, fst_exp, snd_exp = ""):
    global counter
    counter += 1
    if self.terminate: return False
    else: return self.lines.assert_leaf(fst_exp, snd_exp)

  """PARSE ERROR"""
  def parse_error(self, curr_line):
    self.terminate = True
    return self.lines.parse_error(curr_line)

  """CHECK BOTH FOR INT AND RETURN INT"""
  def check_both_for_int_and_return_int(self, curr_line, fst_fun, expr, snd_fun):
    if not fst_fun() == Expr("INT"):
      return self.parse_error(curr_line)
    self.assert_leaf(expr)
    if not snd_fun() == Expr("INT"):
      return self.parse_error(curr_line)
    return Expr("INT")

  """CAN CAST"""
  def can_cast(self, fst_exp, snd_exp):
    return fst_exp == snd_exp \
        or fst_exp == Expr("INT") and snd_exp == Expr("CHAR")

  """POST TRAVERSAL CHECKS"""
  def post_traversal_checks(self):
    if not self.table.is_declared("main", [Expr("VOID")], [Expr("INT")]) \
        or not "main" in self.table._scopes[0]['_functions'] \
        or not self.table.get_function("main")._function_to_types[0]._type == "INT":
      self.result = "main"
      return True

    for scope in self.table._scopes:
      for function in scope['_functions']:
        if not function in self.table._defined_functions:
          self.result = "funkcija"
          return True
    return False

  """PARSE"""
  def parse(self):
    #pprint("# Starting and checking for <prijevodna_jedinica>")
    self.check_expressions(["<prijevodna_jedinica>"])
    #pprint("Calling self.prijevodna_jedinica()")
    self.prijevodna_jedinica()

    self.result = self.lines.result

    if not self.terminate:
      if not self.post_traversal_checks():
        pprint("Succesful semantic analysis. No errors!")
      else:
        pprint("Post traversal errors found!")

    return(self.result)

######################################
############### IZRAZI ###############
######################################
  """PRIMARNI IZRAZ"""
  def primarni_izraz(self):
    curr_line = self.lines._iter
    pprint("# primarni_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["IDN"]):
      idn = self.assert_leaf("IDN")
      if self.table.contains(idn):
        return self.table.get_var(idn)
      elif self.table.is_JUST_declared(idn):
        return self.table.get_function(idn)
      else:
        return self.parse_error(curr_line)
    elif self.check_expressions(["BROJ"]):
      expr = self.assert_leaf("BROJ")
      if int(expr) < -2**31 or int(expr) >= 2**31:
        return self.parse_error(curr_line)
      return Expr("INT")
    elif self.check_expressions(["ZNAK"]):
      expr = self.assert_leaf("ZNAK")
      if not len(expr) == 3 or ord(expr[1]) < 0 or ord(expr[1]) > 255:
        return self.parse_error(curr_line)
      return Expr("CHAR")
    elif self.check_expressions(["NIZ_ZNAKOVA"]):
      expr = self.assert_leaf("NIZ_ZNAKOVA")
      if not is_valid_char_array(expr):
        return self.parse_error(curr_line)
      return Expr("CHAR", is_array = True)
    elif self.check_expressions(["L_ZAGRADA", "<izraz>", "D_ZAGRADA"]):
      self.assert_leaf("L_ZAGRADA")
      expr = self.izraz()
      self.assert_leaf("D_ZAGRADA")
      return expr
    else:
      return self.parse_error(curr_line)

  """POSTFIX IZRAZ"""
  def postfiks_izraz(self):
    curr_line = self.lines._iter
    pprint("# postfiks_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<postfiks_izraz>", "L_UGL_ZAGRADA", "<izraz>", "D_UGL_ZAGRADA"]):
      expr = self.postfiks_izraz()
      _expr = Expr(expr)
      if not _expr.is_array:
        return self.parse_error(curr_line)
      ## We are accessing an element of this array so the return type is not array
      _expr.is_array = False
      self.assert_leaf("L_UGL_ZAGRADA")
      if not self.izraz() == Expr("INT"):
        return self.parse_error(curr_line)
      self.assert_leaf("D_UGL_ZAGRADA")
      if _expr.is_const:
        return _expr
      else:
        return _expr.set_to_lexpr()
    elif self.check_expressions(["<postfiks_izraz>", "L_ZAGRADA", "D_ZAGRADA"]):
      expr = self.postfiks_izraz()
      self.assert_leaf("L_ZAGRADA")
      self.assert_leaf("D_ZAGRADA")
      if not expr.is_function or not expr.is_function_from([Expr("VOID")]):
        return self.parse_error(curr_line)
      ret = expr.get_return_type()
      if len(ret) != 1:
        raise Exception("This should not happen")
      else:
        return ret[0]
    elif self.check_expressions(["<postfiks_izraz>", "L_ZAGRADA", "<lista_argumenata>", "D_ZAGRADA"]):
      expr = self.postfiks_izraz()
      self.assert_leaf("L_ZAGRADA")
      expr2 = self.lista_argumenata()
      self.assert_leaf("D_ZAGRADA")
      if not expr.is_function or not expr.is_function_from(expr2):
        return self.parse_error(curr_line)
      ret = expr.get_return_type()
      if len(ret) != 1:
        raise Exception("This should not happen")
      else:
        return ret[0]
    elif self.check_expressions(["<postfiks_izraz>", "OP_INC"]):
      expr = self.postfiks_izraz()
      self.assert_leaf("OP_INC")
      if not expr.is_lexpr or not expr == Expr("INT"):
        return self.parse_error(curr_line)
      else:
        return Expr("INT")
    elif self.check_expressions(["<postfiks_izraz>", "OP_DEC"]):
      expr = self.postfiks_izraz()
      self.assert_leaf("OP_DEC")
      if not expr.is_lexpr or not expr == Expr("INT"):
        return self.parse_error(curr_line)
      else:
        return Expr("INT")
    elif self.check_expressions(["<primarni_izraz>"]):
      return self.primarni_izraz()
    else:
      return self.parse_error(curr_line)

  """LISTA ARGUMENATA"""
  def lista_argumenata(self):
    curr_line = self.lines._iter
    pprint("# lista_argumenata")
    pprint(self.lines.get_line())

    if self.check_expressions(["<izraz_pridruzivanja>"]):
      expr = self.izraz_pridruzivanja()
      return [expr]
    elif self.check_expressions(["<lista_argumenata>", "ZAREZ", "<izraz_pridruzivanja>"]):
      expr = self.lista_argumenata()
      self.assert_leaf("ZAREZ")
      expr2 = self.izraz_pridruzivanja()
      return expr + [expr2]
    else:
      return self.parse_error(curr_line)

  """UNARNI IZRAZ"""
  def unarni_izraz(self):
    curr_line = self.lines._iter
    pprint("# unarni_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<postfiks_izraz>"]):
      return self.postfiks_izraz()
    elif self.check_expressions(["OP_DEC", "<unarni_izraz>"]):
      self.assert_leaf("OP_DEC")
      expr = self.unarni_izraz()
      if not expr.is_lexpr or not expr == Expr("INT"):
        return self.parse_error(curr_line)
      else:
        return Expr("INT")
    elif self.check_expressions(["OP_INC", "<unarni_izraz>"]):
      self.assert_leaf("OP_INC")
      expr = self.unarni_izraz()
      if not expr.is_lexpr or not expr == Expr("INT"):
        return self.parse_error(curr_line)
      else:
        return Expr("INT")
    elif self.check_expressions(["<unarni_operator>", "<cast_izraz>"]):
      self.unarni_operator()
      expr = self.cast_izraz()
      if not expr == Expr("INT"):
        return self.parse_error(curr_line)
      else:
        return Expr("INT")
    else:
      return self.parse_error(curr_line)

  """UNARNI OPERATOR"""
  def unarni_operator(self):
    curr_line = self.lines._iter
    pprint("# unarni_operator")
    pprint(self.lines.get_line())

    if self.check_expressions(["PLUS"]):
      self.assert_leaf("PLUS")
      return
    elif self.check_expressions(["MINUS"]):
      self.assert_leaf("MINUS")
      return
    elif self.check_expressions(["OP_TILDA"]):
      self.assert_leaf("OP_TILDA")
      return
    elif self.check_expressions(["OP_NEG"]):
      self.assert_leaf("OP_NEG")
      return
    else:
      return self.parse_error(curr_line)

  """CAST IZRAZ"""
  def cast_izraz(self):
    curr_line = self.lines._iter
    pprint("# cast_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<unarni_izraz>"]):
      return self.unarni_izraz()
    elif self.check_expressions(["L_ZAGRADA", "<ime_tipa>", "D_ZAGRADA", "<cast_izraz>"]):
      self.assert_leaf("L_ZAGRADA")
      expr = self.ime_tipa()
      self.assert_leaf("D_ZAGRADA")
      expr2 = self.cast_izraz()
      if not self.can_cast(expr, expr2):
        return self.parse_error(curr_line)
      else:
        return expr

  """IME TIPA"""
  def ime_tipa(self):
    curr_line = self.lines._iter
    pprint("# ime_tipa")
    pprint(self.lines.get_line())

    if self.check_expressions(["<specifikator_tipa>"]):
      return self.specifikator_tipa()
    elif self.check_expressions(["KR_CONST", "<specifikator_tipa>"]):
      self.assert_leaf("KR_CONST")
      expr = self.specifikator_tipa()
      if expr == Expr("VOID"):
        return self.parse_error(curr_line)
      else:
        return expr.set_to_const()
    else:
      return self.parse_error(curr_line)

  """SPECIFIKATOR TIPA"""
  def specifikator_tipa(self):
    curr_line = self.lines._iter
    pprint("# specifikator_tipa")
    pprint(self.lines.get_line())

    if self.check_expressions(["KR_VOID"]):
      self.assert_leaf("KR_VOID", "void")
      return Expr("VOID")
    elif self.check_expressions(["KR_CHAR"]):
      self.assert_leaf("KR_CHAR", "char")
      return Expr("CHAR")
    elif self.check_expressions(["KR_INT"]):
      self.assert_leaf("KR_INT", "int")
      return Expr("INT")
    else:
      return self.parse_error(curr_line)

  """MULTIPLIKATIVNI IZRAZ"""
  def multiplikativni_izraz(self):
    curr_line = self.lines._iter
    pprint("# multiplikativni_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<cast_izraz>"]):
      return self.cast_izraz()
    elif self.check_expressions(["<multiplikativni_izraz>", "OP_PUTA", "<cast_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.multiplikativni_izraz, "OP_PUTA", self.cast_izraz)
    elif self.check_expressions(["<multiplikativni_izraz>", "OP_DIJELI", "<cast_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.multiplikativni_izraz, "OP_DIJELI", self.cast_izraz)
    elif self.check_expressions(["<multiplikativni_izraz>", "OP_MOD", "<cast_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.multiplikativni_izraz, "OP_MOD", self.cast_izraz)
    else:
      return self.parse_error(curr_line)

  """ADITIVNI IZRAZ"""
  def aditivni_izraz(self):
    curr_line = self.lines._iter
    pprint("# aditivni_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<multiplikativni_izraz>"]):
      return self.multiplikativni_izraz()
    elif self.check_expressions(["<aditivni_izraz>", "PLUS", "<multiplikativni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.aditivni_izraz, "PLUS", self.multiplikativni_izraz)
    elif self.check_expressions(["<aditivni_izraz>", "MINUS", "<multiplikativni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.aditivni_izraz, "MINUS", self.multiplikativni_izraz)
    else:
      return self.parse_error(curr_line)

  """ODNOSNI IZRAZ"""
  def odnosni_izraz(self):
    curr_line = self.lines._iter
    pprint("# odnosni_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<aditivni_izraz>"]):
      return self.aditivni_izraz()
    elif self.check_expressions(["<odnosni_izraz>", "OP_LT", "<aditivni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.odnosni_izraz, "OP_LT" , self.aditivni_izraz)
    elif self.check_expressions(["<odnosni_izraz>", "OP_GT", "<aditivni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.odnosni_izraz, "OP_GT" , self.aditivni_izraz)
    elif self.check_expressions(["<odnosni_izraz>", "OP_LTE", "<aditivni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.odnosni_izraz, "OP_LTE" , self.aditivni_izraz)
    elif self.check_expressions(["<odnosni_izraz>", "OP_GTE", "<aditivni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.odnosni_izraz, "OP_GTE" , self.aditivni_izraz)
    else:
      return self.parse_error(curr_line)

  """JEDNAKOSNI IZRAZ"""
  def jednakosni_izraz(self):
    curr_line = self.lines._iter
    pprint("# jednakosni_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<odnosni_izraz>"]):
      return self.odnosni_izraz()
    elif self.check_expressions(["<jednakosni_izraz>", "OP_EQ", "<odnosni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.jednakosni_izraz, "OP_EQ", self.odnosni_izraz)
    elif self.check_expressions(["<jednakosni_izraz>", "OP_NEQ", "<odnosni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.jednakosni_izraz, "OP_NEQ", self.odnosni_izraz)
    else:
      return self.parse_error(curr_line)

  """BIN I IZRAZ"""
  def bin_i_izraz(self):
    curr_line = self.lines._iter
    pprint("# bin_i_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<jednakosni_izraz>"]):
      return self.jednakosni_izraz()
    elif self.check_expressions(["<bin_i_izraz>", "OP_BIN_I", "<jednakosni_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.bin_i_izraz, "OP_BIN_I", self.jednakosni_izraz)
    else:
      return self.parse_error(curr_line)

  """BIN XILI IZRAZ"""
  def bin_xili_izraz(self):
    curr_line = self.lines._iter
    pprint("# bin_xili_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<bin_i_izraz>"]):
      return self.bin_i_izraz()
    elif self.check_expressions(["<bin_xili_izraz>", "OP_BIN_XILI", "<bin_i_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.bin_xili_izraz, "OP_BIN_XILI", self.bin_i_izraz)
    else:
      return self.parse_error(curr_line)

  """BIN ILI IZRAZ"""
  def bin_ili_izraz(self):
    curr_line = self.lines._iter
    pprint("# bin_ili_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<bin_xili_izraz>"]):
      return self.bin_xili_izraz()
    elif self.check_expressions(["<bin_ili_izraz>", "OP_BIN_ILI", "<bin_xili_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.bin_ili_izraz, "OP_BIN_ILI", self.bin_xili_izraz)
    else:
      return self.parse_error(curr_line)

  """LOG I IZRAZ"""
  def log_i_izraz(self):
    curr_line = self.lines._iter
    pprint("# log_i_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<bin_ili_izraz>"]):
      return self.bin_ili_izraz()
    elif self.check_expressions(["<log_i_izraz>", "OP_I", "<bin_ili_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.log_i_izraz, "OP_I", self.bin_ili_izraz)
    else:
      return self.parse_error(curr_line)

  """LOG ILI IZRAZ"""
  def log_ili_izraz(self):
    curr_line = self.lines._iter
    pprint("# log_ili_izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<log_i_izraz>"]):
      return self.log_i_izraz()
    elif self.check_expressions(["<log_ili_izraz>", "OP_ILI", "<log_i_izraz>"]):
      return self.check_both_for_int_and_return_int(curr_line, self.log_ili_izraz, "OP_ILI", self.log_i_izraz)
    else:
      return self.parse_error(curr_line)

  """IZRAZ PRIDRUZIVANJA"""
  def izraz_pridruzivanja(self):
    curr_line = self.lines._iter
    pprint("# izraz_pridruzivanja")
    pprint(self.lines.get_line())

    if self.check_expressions(["<log_ili_izraz>"]):
      return self.log_ili_izraz()
    elif self.check_expressions(["<postfiks_izraz>", "OP_PRIDRUZI", "<izraz_pridruzivanja>"]):
      expr = self.postfiks_izraz()
      if not expr.is_lexpr:
        return self.parse_error(curr_line)
      self.assert_leaf("OP_PRIDRUZI")
      expr2 = self.izraz_pridruzivanja()
      if not expr == expr2:
        return self.parse_error(curr_line)
      return expr
    else:
      return self.parse_error(curr_line)

  """IZRAZ"""
  def izraz(self):
    curr_line = self.lines._iter
    pprint("# izraz")
    pprint(self.lines.get_line())

    if self.check_expressions(["<izraz_pridruzivanja>"]):
      return self.izraz_pridruzivanja()
    elif self.check_expressions(["<izraz>", "ZAREZ", "<izraz_pridruzivanja>"]):
      self.izraz()
      self.assert_leaf("ZAREZ")
      return self.izraz_pridruzivanja()


##################################
## NAREDBENA STRUKTURA PROGRAMA ##
##################################

  """SLOZENA NAREDBA"""
  def slozena_naredba(self, in_loop = False, in_function = False, function_to = []):
    curr_line = self.lines._iter
    pprint("# slozena_naredba")
    pprint(self.lines.get_line())

    if self.check_expressions(["L_VIT_ZAGRADA", "<lista_naredbi>", "D_VIT_ZAGRADA"]):
      self.assert_leaf("L_VIT_ZAGRADA")
      self.lista_naredbi(in_loop = in_loop, in_function = in_function, function_to = function_to)
      self.assert_leaf("D_VIT_ZAGRADA")
    elif self.check_expressions(["L_VIT_ZAGRADA", "<lista_deklaracija>", "<lista_naredbi>"
                               , "D_VIT_ZAGRADA"]):
      self.table.create_new_scope() #### SCOPING!!!!!!!!
      self.assert_leaf("L_VIT_ZAGRADA")
      self.lista_deklaracija()
      self.lista_naredbi(in_loop = in_loop, in_function = in_function, function_to = function_to)
      self.assert_leaf("D_VIT_ZAGRADA")
      self.table.destroy_current_scope() #### SCOPING!!!!!!!!
    else:
      return self.parse_error(curr_line)

  """LISTA NAREDBI"""
  def lista_naredbi(self, in_loop = False, in_function = False, function_to = []):
    curr_line = self.lines._iter
    pprint("# lista_naredbi")
    pprint(self.lines.get_line())

    if self.check_expressions(["<naredba>"]):
      self.naredba(in_loop = in_loop, in_function = in_function, function_to = function_to)
    elif self.check_expressions(["<lista_naredbi>", "<naredba>"]):
      self.lista_naredbi(in_loop = in_loop, in_function = in_function, function_to = function_to)
      self.naredba(in_loop = in_loop, in_function = in_function, function_to = function_to)
    else:
      return self.parse_error(curr_line)

  """NAREDBA"""
  def naredba(self, in_loop = False, in_function = False, function_to = []):
    curr_line = self.lines._iter
    pprint("# naredba")
    pprint(self.lines.get_line())

    if self.check_expressions(["<slozena_naredba>"]):
      self.slozena_naredba(in_loop = in_loop, in_function = in_function, function_to = function_to)
    elif self.check_expressions(["<izraz_naredba>"]):
      self.izraz_naredba()
    elif self.check_expressions(["<naredba_grananja>"]):
      self.naredba_grananja(in_loop = in_loop, in_function = in_function, function_to = function_to)
    elif self.check_expressions(["<naredba_petlje>"]):
      self.naredba_petlje(in_loop = in_loop, in_function = in_function, function_to = function_to)
    elif self.check_expressions(["<naredba_skoka>"]):
      self.naredba_skoka(in_loop = in_loop, in_function = in_function, function_to = function_to)
    else:
      return self.parse_error(curr_line)

  """IZRAZ NAREDBA"""
  def izraz_naredba(self):
    curr_line = self.lines._iter
    pprint("# izraz_naredba")
    pprint(self.lines.get_line())

    if self.check_expressions(["TOCKAZAREZ"]):
      self.assert_leaf("TOCKAZAREZ")
      return Expr("INT")
    elif self.check_expressions(["<izraz>", "TOCKAZAREZ"]):
      expr = self.izraz()
      self.assert_leaf("TOCKAZAREZ")
      return expr
    else:
      return self.parse_error(curr_line)

  """NAREDBA GRANANJA"""
  def naredba_grananja(self, in_loop = False, in_function = False, function_to = []):
    curr_line = self.lines._iter
    pprint("# naredba_grananja")
    pprint(self.lines.get_line())

    if self.check_expressions(["KR_IF", "L_ZAGRADA", "<izraz>", "D_ZAGRADA", "<naredba>"]):
      self.assert_leaf("KR_IF")
      self.assert_leaf("L_ZAGRADA")
      expr = self.izraz()
      if not expr == Expr("INT"):
        return self.parse_error(curr_line)
      self.assert_leaf("D_ZAGRADA")
      self.naredba(in_loop = in_loop, in_function = in_function, function_to = function_to)
    elif self.check_expressions(["KR_IF", "L_ZAGRADA", "<izraz>"
                                ,"D_ZAGRADA", "<naredba>", "KR_ELSE", "<naredba>"]):
      self.assert_leaf("KR_IF")
      self.assert_leaf("L_ZAGRADA")
      if not self.izraz() == Expr("INT"):
        return self.parse_error(curr_line)
      self.assert_leaf("D_ZAGRADA")
      self.naredba(in_loop = in_loop, in_function = in_function, function_to = function_to)
      self.assert_leaf("KR_ELSE")
      self.naredba(in_loop = in_loop, in_function = in_function, function_to = function_to)
    else:
      return self.parse_error(curr_line)

  """NAREDBA PETLJE"""
  def naredba_petlje(self, in_loop = False, in_function = False, function_to = []):
    curr_line = self.lines._iter
    pprint("# naredba_petlje")
    pprint(self.lines.get_line())

    if self.check_expressions(["KR_WHILE", "L_ZAGRADA", "<izraz>", "D_ZAGRADA", "<naredba>"]):
      self.assert_leaf("KR_WHILE")
      self.assert_leaf("L_ZAGRADA")
      if not self.izraz() == Expr("INT"):
        return self.parse_error(curr_line)
      self.assert_leaf("D_ZAGRADA")
      self.naredba(in_loop = True, in_function = in_function, function_to = function_to)
    elif self.check_expressions(["KR_FOR", "L_ZAGRADA", "<izraz_naredba>", "<izraz_naredba>"
                                ,"D_ZAGRADA", "<naredba>"]):
      self.assert_leaf("KR_FOR")
      self.assert_leaf("L_ZAGRADA")
      self.izraz_naredba()
      if not self.izraz_naredba() == Expr("INT"):
        return self.parse_error(curr_line)
      self.assert_leaf("D_ZAGRADA")
      self.naredba(in_loop = True, in_function = in_function, function_to = function_to)
    elif self.check_expressions(["KR_FOR", "L_ZAGRADA", "<izraz_naredba>", "<izraz_naredba>"
                                ,"<izraz>", "D_ZAGRADA", "<naredba>"]):
      self.assert_leaf("KR_FOR")
      self.assert_leaf("L_ZAGRADA")
      self.izraz_naredba()
      if not self.izraz_naredba() == Expr("INT"):
        return self.parse_error(curr_line)
      self.izraz()
      self.assert_leaf("D_ZAGRADA")
      self.naredba(in_loop = True, in_function = in_function, function_to = function_to)
    else:
      return self.parse_error(curr_line)

  """NAREDBA SKOKA"""
  def naredba_skoka(self, in_loop = False, in_function = False, function_to = []):
    curr_line = self.lines._iter
    pprint("# naredba_skoka")
    pprint(self.lines.get_line())

    if self.check_expressions(["KR_CONTINUE", "TOCKAZAREZ"]):
      if not in_loop:
        return self.parse_error(curr_line)
      self.assert_leaf("KR_CONTINUE")
      self.assert_leaf("TOCKAZAREZ")
      return
    if self.check_expressions(["KR_BREAK", "TOCKAZAREZ"]):
      if not in_loop:
        return self.parse_error(curr_line)
      self.assert_leaf("KR_BREAK")
      self.assert_leaf("TOCKAZAREZ")
      return
    elif self.check_expressions(["KR_RETURN", "TOCKAZAREZ"]):
      if not in_function or not function_to == [Expr("VOID")]:
        return self.parse_error(curr_line)
      self.assert_leaf("KR_RETURN")
      self.assert_leaf("TOCKAZAREZ")
    elif self.check_expressions(["KR_RETURN", "<izraz>", "TOCKAZAREZ"]):
      self.assert_leaf("KR_RETURN")
      expr = self.izraz()
      print(expr)
      if not in_function:
        return self.parse_error(curr_line)
      if not [expr] == function_to:
        return self.parse_error(curr_line)
      self.assert_leaf("TOCKAZAREZ")

  """PRIJEVODNA JEDINICA"""
  def prijevodna_jedinica(self):
    curr_line = self.lines._iter
    pprint("# prijevodna_jedinica")
    pprint(self.lines.get_line())

    if self.check_expressions(["<vanjska_deklaracija>"]):
      pprint("<vanjska_deklaracija>")
      self.vanjska_deklaracija()
    elif self.check_expressions(["<prijevodna_jedinica>", "<vanjska_deklaracija>"]):
      pprint("<prijevodna_jedinica> <vanjska_deklaracija>")
      self.prijevodna_jedinica()
      self.vanjska_deklaracija()
    else:
      return self.parse_error(curr_line)

  """VANJSKA DEKLARACIJA"""
  def vanjska_deklaracija(self):
    curr_line = self.lines._iter
    pprint("# vanjska_deklaracija")
    pprint(self.lines.get_line())

    if self.check_expressions(["<definicija_funkcije>"]):
      self.definicija_funkcije()
    elif self.check_expressions(["<deklaracija>"]):
      pprint("# vanjska_deklaracija")
      self.deklaracija()
    else:
      return self.parse_error(curr_line)

##############################
## DEKLARACIJE I DEFINICIJE ##
##############################

  """DEFINICIJA FUNKCIJE"""
  def definicija_funkcije(self):
    curr_line = self.lines._iter
    pprint("# definicija_funkcije")
    pprint(self.lines.get_line())

    if self.check_expressions(["<ime_tipa>", "IDN", "L_ZAGRADA", "KR_VOID", "D_ZAGRADA"
                             , "<slozena_naredba>"]):
      ## 1
      expr = self.ime_tipa()
      ## 2
      if expr.is_const:
        return self.parse_error(curr_line)
      idn = self.assert_leaf("IDN")
      ## 3
      if self.table.contains(idn) and self.table.is_defined(idn):
        return self.parse_error(curr_line)
      ## 4
      if self.table.is_declared(idn, [Expr("VOID")], [expr]):
        return self.parse_error(curr_line)
      ## 5
      if not self.table.is_declared(idn, [Expr("VOID")], [expr]):
        self.table.declare_fun(idn, [Expr("VOID")], [expr])
      if not self.table.is_defined(idn, [Expr("VOID")], [expr]):
        self.table.define(idn, [Expr("VOID")], [expr])
      ## X
      self.assert_leaf("L_ZAGRADA")
      self.assert_leaf("KR_VOID")
      self.assert_leaf("D_ZAGRADA")
      ## 6
      self.slozena_naredba(in_function = True, function_to = [expr])
    elif self.check_expressions(["<ime_tipa>", "IDN", "L_ZAGRADA", "<lista_parametara>", "D_ZAGRADA"
                               , "<slozena_naredba>"]):
      ## 1
      expr = self.ime_tipa()
      ## 2
      if expr.is_const:
        return self.parse_error(curr_line)
      idn = self.assert_leaf("IDN")
      ## X
      self.assert_leaf("L_ZAGRADA")
      ## 4
      types, names = self.lista_parametara()
      ## 5
      if self.table.is_declared(idn, types, [expr]):
        return self.parse_error(curr_line)
      ## 3
      if self.table.contains(idn) or self.table.is_defined(idn, types, [expr]):
        return self.parse_error(curr_line)
      ## 6
      if not self.table.is_declared(idn, types, [expr]):
        self.table.declare_fun(idn, types, [expr])
      if not self.table.is_defined(idn, types, [expr]):
        self.table.define(idn, types, [expr])

      #### SCOPING!!!!!!!!
      self.table.create_new_scope() #### SCOPING!!!!!!!!
      ## 4 . continued
      ### Addomg types+names to scope (no scoping implemented yet)
      for i, name in enumerate(names):
        self.table.declare_var(name, types[i])
      ## X
      self.assert_leaf("D_ZAGRADA")
      ## 7 !!! Careful about function parameters. Should be implemented (i think)
      pprint("!!!!!!!!!!!!!!!!!!!!!!!!!!!")
      pprint(expr)
      self.slozena_naredba(in_function = True, function_to = [expr])

      self.table.destroy_current_scope() #### SCOPING!!!!!!!!
    else:
      return self.parse_error(curr_line)

  """LISTA PARAMETARA"""
  def lista_parametara(self):
    curr_line = self.lines._iter
    pprint("# lista_parametara")
    pprint(self.lines.get_line())

    if self.check_expressions(["<deklaracija_parametra>"]):
      tip, ime = self.deklaracija_parametra()
      return [tip], [ime]
    elif self.check_expressions(["<lista_parametara>", "ZAREZ", "<deklaracija_parametra>"]):
      tipovi, imena = self.lista_parametara()
      self.assert_leaf("ZAREZ")
      tip, ime = self.deklaracija_parametra()
      return tipovi + [tip], imena + [ime]
    else:
      return self.parse_error(curr_line)

  """DEKLARACIJA PARAMETRA"""
  def deklaracija_parametra(self):
    curr_line = self.lines._iter
    pprint("# deklaracija_parametra")
    pprint(self.lines.get_line())

    if self.check_expressions(["<ime_tipa>", "IDN", "L_UGL_ZAGRADA", "D_UGL_ZAGRADA"]):
      expr = self.ime_tipa()
      if expr == Expr("VOID"):
        return self.parse_error(curr_line)
      idn =  self.assert_leaf("IDN")
      self.assert_leaf("L_UGL_ZAGRADA")
      self.assert_leaf("D_UGL_ZAGRADA")
      return expr.set_to_array(), idn
    elif self.check_expressions(["<ime_tipa>", "IDN"]):
      expr = self.ime_tipa()
      if expr == Expr("VOID"):
        return self.parse_error(curr_line)
      idn = self.assert_leaf("IDN")
      return expr, idn
    else:
      return self.parse_error(curr_line)

  """LISTA DEKLARACIJA"""
  def lista_deklaracija(self):
    curr_line = self.lines._iter
    pprint("# lista_deklaracija")
    pprint(self.lines.get_line())

    if self.check_expressions(["<deklaracija>"]):
      self.deklaracija()
    elif self.check_expressions(["<lista_deklaracija>", "<deklaracija>"]):
      self.lista_deklaracija()
      self.deklaracija()
    else:
      return self.parse_error(curr_line)

  """DEKLRACIJA"""
  def deklaracija(self):
    curr_line = self.lines._iter
    pprint("# deklaracija")
    pprint(self.lines.get_line())

    if self.check_expressions(["<ime_tipa>", "<lista_init_deklaratora>", "TOCKAZAREZ"]):
      expr = self.ime_tipa()
      self.lista_init_deklaratora(expr)
      self.assert_leaf("TOCKAZAREZ")
      return

  """LISTA INIT DEKLARATORA"""
  def lista_init_deklaratora(self, inherited_type):
    curr_line = self.lines._iter
    pprint("# lista_init_deklaratora")
    pprint(self.lines.get_line())

    if self.check_expressions(["<init_deklarator>"]):
      self.init_deklarator(inherited_type)
    elif self.check_expressions(["<lista_init_deklaratora>", "ZAREZ", "<init_deklarator>"]):
      self.lista_init_deklaratora(inherited_type)
      self.assert_leaf("ZAREZ")
      self.init_deklarator(inherited_type)
    else:
      return self.parse_error(curr_line)

  """INIT DEKLARATOR"""
  def init_deklarator(self, inherited_type):
    curr_line = self.lines._iter
    pprint("# init_deklarator")
    pprint(self.lines.get_line())

    if self.check_expressions(["<izravni_deklarator>"]):
      tmp = self.izravni_deklarator(inherited_type)
      if self.terminate: return tmp
      expr, num = tmp
      if expr.is_const:
        return self.parse_error(curr_line)
    elif self.check_expressions(["<izravni_deklarator>", "OP_PRIDRUZI", "<inicijalizator>"]):
      tmp = self.izravni_deklarator(inherited_type)
      if self.terminate: return tmp
      expr, num = tmp
      self.assert_leaf("OP_PRIDRUZI")
      tmp = self.inicijalizator()
      if self.terminate: return tmp
      expr2, num2 = tmp
      if not expr.is_array and not expr2.is_function:
        if not expr == expr2:
          return self.parse_error(curr_line)
      if not expr.is_array and expr2.is_function:
        if not expr == expr2.get_return_type():
          return self.parse_error(curr_line)
      elif expr.is_array:
        if not num >= num2:
          return self.parse_error(curr_line)
        if type(expr2) is list:
          _expr = Expr(expr)
          _expr.is_array = False
          for e in expr2:
            if not e == _expr:
              return self.parse_error(curr_line)
        else:
          if not expr2 == expr:
            return self.parse_error(curr_line)
    else:
      return self.parse_error(curr_line)

  """IZRAVNI DEKLARATOR"""
  def izravni_deklarator(self, inherited_type):
    curr_line = self.lines._iter
    pprint("# izravni_deklarator")
    pprint(self.lines.get_line())

    if self.check_expressions(["IDN"]):
      idn = self.assert_leaf("IDN")
      if inherited_type == Expr("VOID"):
        return self.parse_error(curr_line)
      if self.table.contains(idn):
        return self.parse_error(curr_line)
      self.table.declare_var(idn, inherited_type)
      ## Returning false to know that it's not a declaration that returns a number as second arg
      return inherited_type, 1
    elif self.check_expressions(["IDN", "L_UGL_ZAGRADA", "BROJ", "D_UGL_ZAGRADA"]):
      _inherited_type = Expr(inherited_type).set_to_array()
      idn = self.assert_leaf("IDN")
      if _inherited_type == Expr("VOID"):
        return self.parse_error(curr_line)
      if self.table.contains(idn):
        return self.parse_error(curr_line)
      self.assert_leaf("L_UGL_ZAGRADA")
      num = self.assert_leaf("BROJ")
      if int(num) < 0 or int(num) > 1024:
        return self.parse_error(curr_line)
      self.table.declare_var(idn, _inherited_type)
      self.assert_leaf("D_UGL_ZAGRADA")
      return _inherited_type, int(num)
    elif self.check_expressions(["IDN", "L_ZAGRADA", "KR_VOID", "D_ZAGRADA"]):
      idn = self.assert_leaf("IDN")
      self.assert_leaf("L_ZAGRADA")
      self.assert_leaf("KR_VOID")
      self.assert_leaf("D_ZAGRADA")
      if self.table.is_JUST_declared(idn) \
          and not self.table.is_declared(idn, [Expr("VOID")], [inherited_type]):
        return self.parse_error(curr_line)
      elif not self.table.is_JUST_declared(idn):
        self.table.declare_fun(idn, [Expr("VOID")], [inherited_type])
      else:
        pass # It means it's already declared and of same type
      ## Returning false to know that it's not a declaration that returns a number as second arg
      return Expr("VOID", is_function = True, fun_from = [Expr("VOID")], fun_to = [inherited_type]), 1
    elif self.check_expressions(["IDN", "L_ZAGRADA", "<lista_parametara>", "D_ZAGRADA"]):
      idn = self.assert_leaf("IDN")
      self.assert_leaf("L_ZAGRADA")
      params, names = self.lista_parametara()
      self.assert_leaf("D_ZAGRADA")
      if self.table.is_JUST_declared(idn) \
          and not self.table.is_declared(idn, params, [inherited_type]):
        return self.parse_error(curr_line)
      elif not self.table.is_JUST_declared(idn):
        self.table.declare_fun(idn, params, [inherited_type])
      else:
        pass # It means it's already declared and of same type
      ## Returning false to know that it's not a declaration that returns a number as second arg
      return Expr("VOID", is_function = True, fun_from = params, fun_to = [inherited_type]), 1
    else:
      return self.parse_error(curr_line)

  """INICIJALIZATOR"""
  def inicijalizator(self):
    curr_line = self.lines._iter
    pprint("# inicijalizator")
    pprint(self.lines.get_line())

    if self.check_expressions(["<izraz_pridruzivanja>"]):
      expr = self.izraz_pridruzivanja()
      if expr == Expr("CHAR", is_array = True):
        return Expr("CHAR", is_array = True), expr.array_length
      else:
        return expr, 1
    elif self.check_expressions(["L_VIT_ZAGRADA", "<lista_izraza_pridruzivanja>", "D_VIT_ZAGRADA"]):
      self.assert_leaf("L_VIT_ZAGRADA")
      expr, num = self.lista_izraza_pridruzivanja()
      self.assert_leaf("D_VIT_ZAGRADA")
      return expr, num
    else:
      return self.parse_error(curr_line)

  """LISTA IZRAZA PRIDRUZIVANJA"""
  def lista_izraza_pridruzivanja(self):
    curr_line = self.lines._iter
    pprint("# lista_izraza_pridruzivanja")
    pprint(self.lines.get_line())

    if self.check_expressions(["<izraz_pridruzivanja>"]):
      expr = self.izraz_pridruzivanja()
      return [expr], 1
    elif self.check_expressions(["<lista_izraza_pridruzivanja>", "ZAREZ", "<izraz_pridruzivanja>"]):
      expr, num = self.lista_izraza_pridruzivanja()
      self.assert_leaf("ZAREZ")
      expr2 = self.izraz_pridruzivanja()
      return (expr + [expr2]), (num + 1)
    else:
      return self.parse_error(curr_line)
Ejemplo n.º 58
0
 def __init__(self, Cursor):
     Table.__init__(self, Cursor)
     self.Table = 'Report'
Ejemplo n.º 59
0
class MsysObject :
    def __init__(self, path, pageSize, swich) :
        self.path = path
        self.pageSize = pageSize
        self.swich = swich
        self.init()
        
    def init(self):
        self.tables = {}
        self.deletedTables = {}
        self.table = Table(self.path, self.pageSize)
        self.table.setTableFDP(4)
        self.table.setTableNumber(2)
        self.setMsysObjectColumns()
        self.table.findNormalPageList()
        recordList = self.table.getNormalData()
        self.makeTables(recordList, "")
        if self.swich == True :
            recordList = self.table.getAbnormalData()
            self.makeTables(recordList, "Deleted_")
        
    def getTables(self) :
        return self.tables
    
    def setMsysObjectColumns(self) :
        self.table.addColumn(Column(1, 4, 4, "ObjidTable"))
        self.table.addColumn(Column(2, 3, 2, "Type"))
        self.table.addColumn(Column(3, 4, 4, "Id"))
        self.table.addColumn(Column(4, 4, 4, "ColtypOrPgnoFDP"))
        self.table.addColumn(Column(5, 4, 4, "SpaceUsage"))
        self.table.addColumn(Column(6, 4, 4, "Flags"))
        self.table.addColumn(Column(7, 4, 4, "PagesOrLocale"))
        self.table.addColumn(Column(8, 1, 1, "RootFlag"))
        self.table.addColumn(Column(9, 3, 2, "RecordOffset"))
        self.table.addColumn(Column(10, 4, 4, "LCMapFlags"))
        self.table.addColumn(Column(11, 17, 2, "KeyMost"))
        self.table.addColumn(Column(128, 10, 255, "Name"))
        self.table.addColumn(Column(129, 9, 255, "Stats"))
        self.table.addColumn(Column(130, 10, 255, "TemplateTable"))
        self.table.addColumn(Column(131, 9, 255, "DefaultValue"))
        self.table.addColumn(Column(132, 9, 255, "KeyFldIDs"))
    
    def makeTables(self, recordList, status) :
        for record in recordList :
            objidTable = record.getDatas(1)
            type = record.getDatas(2)
            id = record.getDatas(3)
            coltypOrPgnoFDP = record.getDatas(4)
            spaceUsage = record.getDatas(5)
            #flags = record.getDatas(6)
            #pagesOrLocale = record.getDatas(7)
            #rootFlag = record.getDatas(8)
            #recordOffset = record.getDatas(9)
            #lCMapFlags = record.getDatas(10)
            #keyMost = record.getDatas(11)
            name = record.getDatas(128)
            #stats = recordv129)
            #templateTable = record.getDatas(130)
            #defaultValue = record.getDatas(131)
            #keyFldIDs = record.getDatas(132)
            
            if status == "Deleted_" and objidTable in self.tables.keys() :
                if not "Deleted_" in self.tables[objidTable].getTableName() :
                    continue
            
            if not objidTable in self.tables.keys() :
                self.tables[objidTable] = Table(self.path, self.pageSize)
                
            if type ==1 :
                self.tables[objidTable].setTableNumber(id)
                self.tables[objidTable].setTableFDP(coltypOrPgnoFDP)
                self.tables[objidTable].setTableName(status+name)
                
            elif type ==2 :
                if objidTable == 2 :
                    self.table.addColumn(Column(id, coltypOrPgnoFDP, spaceUsage, name))
                    
                self.tables[objidTable].addColumn(Column(id, coltypOrPgnoFDP, spaceUsage, name))
                
            elif type ==4 :
                if not id in self.tables.keys() :
                    self.tables[id] = Table(self.path, self.pageSize)
                self.tables[id].setTableNumber(id)
                self.tables[id].setTableFDP(coltypOrPgnoFDP)
                self.tables[id].setTableName(name)
                self.tables[objidTable].setLongValueFDP(id)