Ejemplo n.º 1
0
 def printMovieTimes(self, day_id):
     dbConn = DBConnection()
     cur = dbConn.connection()
     query = "SELECT id,time FROM movie_timings where day_id = ?"
     for row in cur.execute(query, day_id):
         print("[" + str(row[0]) + "]", "\t", row[1])
     cur.close()
Ejemplo n.º 2
0
 def __init__(self):
     self.db = DBConnection(
         'postgresql://*****:*****@192.168.1.102/controllerdb')
     self.topology_manager = TopologyManager(self.db)
     self.ryu = RyuManager(self.db)
     self._current_mpls_label = 0
     self._flows_added = 0
Ejemplo n.º 3
0
 def printMovieDays(self, movie_id):
     dbConn = DBConnection()
     cur = dbConn.connection()
     query = "SELECT id,day FROM movie_days where movie_id = ?"
     for row in cur.execute(query, movie_id):
         print("[" + str(row[0]) + "]", "\t", row[1])
     cur.close()
Ejemplo n.º 4
0
 def __init__(self, args):
     self.con = DBConnection(args.uri, args.user, args.password)
     self.write_prepare()
     self.write_dict(args.dict)
     self.write_docs(args.docs)
     a = time.time()
     self.write_terms(args.terms)
     print(time.time() - a)
Ejemplo n.º 5
0
	def get_game_level_info(cls):
		dbconn = DBConnection(conf.DB_GAME_INFO)
		cursor = dbconn.get_cursor()

		if not cursor or 'level_info' not in cursor.keys():
			return None

		return cursor['level_info']
Ejemplo n.º 6
0
 def getBookedSeatNos(self, time_id):
     dbConn = DBConnection()
     conn = dbConn.connection()
     cur = conn.cursor()
     seat_no = list()
     query = "SELECT row,col from movie_booking where time_id = ?"
     for row in cur.execute(query, time_id):
         seat_no.append(row)
     return seat_no
Ejemplo n.º 7
0
 def printMovieList(self):
     dbConn = DBConnection()
     cur = dbConn.connection()
     print(
         "#########################\n#\tMovies \t\t#\n#########################"
     )
     query = "SELECT * FROM movies"
     for row in cur.execute(query):
         print("[" + str(row[0]) + "]", "\t", row[1])
     cur.close()
Ejemplo n.º 8
0
	def get_game_user_info(cls, username, password):
		game_user = user.User(username, password)
		dbconn = DBConnection(conf.DB_USER)
		cursor = dbconn.get_cursor()

		uid = game_user.get_uid()
		if not cursor or uid not in cursor.keys():
			return None

		return cursor[uid]
Ejemplo n.º 9
0
 def getMovieTitle(self, id):
     dbConn = DBConnection()
     conn = dbConn.connection()
     cur = conn.cursor()
     query = "SELECT title from movies where id = ?"
     cur.execute(query, id)
     row = cur.fetchone()
     if row:
         return row[0]
     else:
         return False
Ejemplo n.º 10
0
 def getMovieTime(self, id, dayID):
     dbConn = DBConnection()
     conn = dbConn.connection()
     cur = conn.cursor()
     query = "SELECT time from movie_timings where id = {0} and day_id = {1}".format(
         id, dayID)
     cur.execute(query)
     row = cur.fetchone()
     if row:
         return row[0]
     else:
         return False
Ejemplo n.º 11
0
 def getMovieDay(self, id, movieID):
     dbConn = DBConnection()
     conn = dbConn.connection()
     cur = conn.cursor()
     query = "SELECT day from movie_days where id = {0} AND movie_id = {1}".format(
         id, movieID)
     cur.execute(query)
     row = cur.fetchone()
     if row:
         return row[0]
     else:
         return False
Ejemplo n.º 12
0
 def bookTicket(self, time_id, seatnos, name):
     dbConn = DBConnection()
     conn = dbConn.connection()
     cur = conn.cursor()
     for seat in seatnos:
         (row, col) = seat
         query = "INSERT INTO movie_booking(time_id,row,col,username) values({0},{1},{2},'{3}')".format(
             time_id, row, col, str(name))
         if cur.execute(query):
             conn.commit()
         else:
             return False
     return True
Ejemplo n.º 13
0
class DBOperation(object):
	def __init__(self):
		self.dbc = DBConnection()
		self.getDate = GetDate()

	def updateOEMToFacility(self):
		SQL = """
				UPDATE T3 SET T3.ZRMK_0 = T1.ZRMK_0
				FROM SORDERQ T1
					LEFT JOIN PORDERQ T2 ON T1.SOHNUM_0 = T2.SOHNUM_0 AND T1.SOPLIN_0 = T2.SOPLIN_0
					LEFT JOIN SORDERQ T3 ON T2.POHNUM_0 = T3.POHNUM_0 AND T2.POPLIN_0 = T3.POPLIN_0
				WHERE T1.ZRMK_0 <> N'' 
					AND T1.SALFCY_0 = N'0101'
					AND T3.ZRMK_0 = N''
			"""
		self.dbc.execute(SQL)
Ejemplo n.º 14
0
	def init_game_level(cls, max_level=69):
		dbconn = DBConnection(conf.DB_GAME_INFO)
		cursor = dbconn.get_cursor()

		if not cursor:
			cursor = {}

		if 'level_info' not in cursor.keys():
			cursor['level_info'] = {}

		level_info = cursor['level_info']
		level_info['max_level'] = max_level
		level_info['levels'] = []

		for level in xrange(max_level):
			level_info['levels'].append(Util.__calc_level_exp(level+1))

		dbconn.write_back(cursor)
Ejemplo n.º 15
0
class CreateCollectionGraph:
    def __init__(self, args):
        self.con = DBConnection(args.uri, args.user, args.password)
        self.write_prepare()
        self.write_dict(args.dict)
        self.write_docs(args.docs)
        a = time.time()
        self.write_terms(args.terms)
        print(time.time() - a)

    def write_prepare(self):
        qs = []
        qs.append("CREATE CONSTRAINT ON (t:Term) ASSERT t.termid IS UNIQUE")
        qs.append("CREATE CONSTRAINT ON (t:Term) ASSERT t.term IS UNIQUE")
        qs.append("CREATE CONSTRAINT ON (d:Doc) ASSERT d.docid IS UNIQUE")
        qs.append(
            "CREATE CONSTRAINT ON (d:Doc) ASSERT d.collectionid IS UNIQUE")
        for q in qs:
            self.con.write(q)

    def write_dict(self, dict_filename):
        query = """ 
           USING PERIODIC COMMIT 10000
           LOAD CSV FROM 'file:///{}' AS line FIELDTERMINATOR '|' 
           CREATE (:Term {{ termid: toInteger(line[0]), term: line[1], df: toInteger(line[2]) }})
        """.format(dict_filename)
        self.con.write(query)

    def write_docs(self, docs_filename):
        query = """ 
           USING PERIODIC COMMIT 10000
           LOAD CSV FROM 'file:///{}' AS line FIELDTERMINATOR '|' 
           CREATE (:Doc {{ docid: toInteger(line[1]), collectionid: line[0], len: toInteger(line[2]) }})
        """.format(docs_filename)
        self.con.write(query)

    def write_terms(self, terms_filename):
        query = """ 
           USING PERIODIC COMMIT 10000
           LOAD CSV FROM 'file:///{}' AS line FIELDTERMINATOR '|' 
           MATCH (d:Doc),(t:Term)
           WHERE d.docid = toInteger(line[1]) AND t.termid = toInteger(line[0])
           CREATE (t)-[a:appearsIn {{count: toInteger(line[2])}}]->(d)
        """.format(terms_filename)
        self.con.write(query)
Ejemplo n.º 16
0
def main():
    handle = DBConnection()

    queries = [
        "some",
        "sql",
        "queries",
        "here..."
    ]

    for query in queries:
        handle.add(query)

    handle.commit()

    print("\nDone")
Ejemplo n.º 17
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.undoStack = QUndoStack()

        self.db = DBConnection("172.16.6.137", "root", "password", "wahl")

        self.gui = Ui_MainWindow()
        self.gui.setupUi(self)
        self.gui.actionOpen.triggered.connect(self.open_file)
        self.gui.actionSave.triggered.connect(self.save_file)
        self.gui.actionSave_as.triggered.connect(self.save_file_as)
        self.gui.actionNew.triggered.connect(self.new_file)
        self.gui.actionCopy.triggered.connect(self.copy_cs)
        self.gui.actionAdd_Row.triggered.connect(self.add_rows)
        self.gui.actionSave_DB.triggered.connect(self.open_save_db)
        self.gui.actionOpen_DB.triggered.connect(self.open_load_db)
        self.gui.actionPaste.triggered.connect(self.paste)
        self.gui.actionCut.triggered.connect(self.cut)
        self.gui.actionDelete_Row.triggered.connect(self.remove_rows)
        self.gui.actionDuplicate_Row.triggered.connect(self.duplicate)
        self.gui.actionUndo.triggered.connect(self.undo)
        self.gui.actionRedo.triggered.connect(self.redo)
        self.gui.actionCreate_Prediction.triggered.connect(self.open_create_pred)
        self.gui.actionShow_Prediction.triggered.connect(self.open_choose_pred)

        self.gui.tableView.setSortingEnabled(True)
        self.gui.tableView.setItemDelegate(ItemDelegate(self.undoStack, self.set_unrdo_text))

        self.tbm = DictTableModel(data=[], header=[], parent=self)

        self.sdb_dialog = SaveToDBDialog(self)
        self.ldb_dialog = LoadFromDBDialog(self)
        self.create_pred_dialog = CreatePredDialog(self)
        self.choose_pred_dialog = ChoosePredDialog(self)
        self.show_pred_dialog = ShowPredDialog(self)

        self.file = "."
 def predict_accident(self):
     insert_into_DB = 1
     db = DBConnection()
     conn = db.get_connection()
     mycursor = conn.cursor()
     mycursor.execute("SELECT path FROM buffer")
     buffer_items = mycursor.fetchall()
     for path_row in buffer_items:
         path = path_row[0]
         clf = Classify(path)
         class_name, percentage = clf.classify_image()
         if (class_name[0] is 'a'
                 or class_name[0] is 'A') and (insert_into_DB is 1):
             insert_into_DB = 0
             print('accident detected')
             Camera_id = 'CAM001'
             db1 = DBConnection()
             conn1 = db1.get_connection()
             mycursor1 = conn1.cursor()
             mycursor1.execute("SELECT count(path) FROM Accident")
             count_row = mycursor1.fetchone()
             new_path = '../accident/Accident' + str(count_row[0]) + '.jpg'
             copyfile(path, new_path)
             date_time = datetime.datetime.now().strftime(
                 "%Y-%m-%d %H:%M:%S")
             timestamp = time.time()
             sql1 = "insert into Accident(Camera_id,path,date_time,timestampAcc) values(%s,%s,%s,%s);"
             mycursor1.execute(
                 sql1, [Camera_id, new_path, date_time,
                        int(timestamp)])
             conn1.commit()
             mycursor1.execute(
                 "UPDATE flag set flag_var = 1 where flag_key = 1;")
             conn1.commit()
             mycursor1.execute(
                 "UPDATE smbool set continue_buffer = 0 where flag_var = 0")
             conn1.commit()
         if (insert_into_DB is 0):
             print('skipping database entry')
         sql = "DELETE FROM buffer WHERE path = %s"
         mycursor.execute(sql, [path])
         conn.commit()
         os.remove(path)
Ejemplo n.º 19
0
 def add_to_buffer(self):
     count = 0
     db = DBConnection()
     conn = db.get_connection()
     mycursor = conn.cursor()
     mycursor.execute("SELECT path FROM vidbuffer")
     vid_buffer_items = mycursor.fetchall()
     for row in vid_buffer_items:
         should_continue = 1
         path = row[0]
         vidcap = cv2.VideoCapture(path)
         success, image = vidcap.read()
         while success:
             img_path = "../buffer/frame" + str(count) + ".jpg"
             cv2.imwrite(img_path, image)
             db1 = DBConnection()
             conn1 = db1.get_connection()
             mycursor1 = conn1.cursor()
             mycursor1.execute("INSERT INTO `buffer`(`path`) VALUES (%s);",
                               [img_path])
             conn1.commit()
             count = count + 1
             for _ in range(25):
                 success, image = vidcap.read()
             mycursor1.execute(
                 "SELECT continue_buffer FROM smbool where flag_var = 0")
             row1 = mycursor1.fetchone()
             should_continue = row1[0]
             print("should continue", should_continue)
             mycursor1.execute(
                 "UPDATE smbool set continue_buffer = 1 where flag_var = 0")
             conn1.commit()
             if should_continue is 0:
                 break
         mycursor1.execute("DELETE FROM `vidbuffer` WHERE `path` = %s",
                           [path])
         conn1.commit()
Ejemplo n.º 20
0
class WahlAnalyse(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.undoStack = QUndoStack()

        self.db = DBConnection("172.16.6.137", "root", "password", "wahl")

        self.gui = Ui_MainWindow()
        self.gui.setupUi(self)
        self.gui.actionOpen.triggered.connect(self.open_file)
        self.gui.actionSave.triggered.connect(self.save_file)
        self.gui.actionSave_as.triggered.connect(self.save_file_as)
        self.gui.actionNew.triggered.connect(self.new_file)
        self.gui.actionCopy.triggered.connect(self.copy_cs)
        self.gui.actionAdd_Row.triggered.connect(self.add_rows)
        self.gui.actionSave_DB.triggered.connect(self.open_save_db)
        self.gui.actionOpen_DB.triggered.connect(self.open_load_db)
        self.gui.actionPaste.triggered.connect(self.paste)
        self.gui.actionCut.triggered.connect(self.cut)
        self.gui.actionDelete_Row.triggered.connect(self.remove_rows)
        self.gui.actionDuplicate_Row.triggered.connect(self.duplicate)
        self.gui.actionUndo.triggered.connect(self.undo)
        self.gui.actionRedo.triggered.connect(self.redo)
        self.gui.actionCreate_Prediction.triggered.connect(self.open_create_pred)
        self.gui.actionShow_Prediction.triggered.connect(self.open_choose_pred)

        self.gui.tableView.setSortingEnabled(True)
        self.gui.tableView.setItemDelegate(ItemDelegate(self.undoStack, self.set_unrdo_text))

        self.tbm = DictTableModel(data=[], header=[], parent=self)

        self.sdb_dialog = SaveToDBDialog(self)
        self.ldb_dialog = LoadFromDBDialog(self)
        self.create_pred_dialog = CreatePredDialog(self)
        self.choose_pred_dialog = ChoosePredDialog(self)
        self.show_pred_dialog = ShowPredDialog(self)

        self.file = "."

    def open_file(self):
        self.file = QFileDialog.getOpenFileName(self, "Choose File", filter="CSV-File (*.csv)")[0]
        if self.file != '':
            data, header = CSVUtil.read(self.file)
            self.tbm.set_data(data, header)
            self.gui.tableView.reset()
            self.gui.tableView.setModel(self.tbm)

    def save_file(self):
        if self.file != '' and self.file is not None:
            CSVUtil.write(self.file, self.tbm.get_data())

    def save_file_as(self):
        self.file = QFileDialog.getSaveFileName(self, "CSV-Datei speichern", dir=self.file, filter="CSV-Datei (*.csv)")[
            0]
        if self.file != '':
            self.save_file()

    def new_file(self):
        self.file = "."
        self.tbm.set_data([], [])
        self.gui.tableView.reset()
        self.gui.tableView.setModel(self.tbm)
        self.undoStack.clear()
        self.set_unrdo_text()

    def copy_cs(self):
        if len(self.gui.tableView.selectionModel().selectedIndexes()) == 0:
            return

        clipboard = QApplication.clipboard()
        selected_index = self.gui.tableView.selectionModel().selectedIndexes()[0]
        selected_text = str(self.tbm.data(selected_index))
        clipboard.setText(selected_text)

    def save_data_db(self, date):
        self.db.write_data(self.tbm.get_data(), date)

    def load_data_db(self, date):
        data, header = self.db.read_data(date)
        self.tbm.set_data(data, header)
        self.gui.tableView.reset()
        self.gui.tableView.setModel(self.tbm)
        self.undoStack.clear()
        self.set_unrdo_text()

    def create_prediction(self, termin, time):
        self.db.create_prediction(termin, time)

    def open_save_db(self):
        self.setDisabled(True)
        self.sdb_dialog.setEnabled(True)
        self.sdb_dialog.show()

    def open_load_db(self):
        self.ldb_dialog.update_dates(self.db.get_termine())
        self.setDisabled(True)
        self.ldb_dialog.setEnabled(True)
        self.ldb_dialog.show()

    def open_create_pred(self):
        self.create_pred_dialog.update_dates(self.db.get_termine())
        self.setDisabled(True)
        self.create_pred_dialog.setEnabled(True)
        self.create_pred_dialog.show()

    def open_choose_pred(self):
        self.choose_pred_dialog.update_predictions(self.db.get_predictions())
        self.setDisabled(True)
        self.choose_pred_dialog.setEnabled(True)
        self.choose_pred_dialog.show()

    def show_prediction(self, date, time):
        data, header = self.db.get_prediction_data(date, time)
        self.show_pred_dialog.update_prediction(data, header, date, time)
        self.setDisabled(True)
        self.show_pred_dialog.setEnabled(True)
        self.show_pred_dialog.show()

    def set_unrdo_text(self):
        undo = "Undo"
        redo = "Redo"
        undo_txt = self.undoStack.undoText()
        redo_txt = self.undoStack.redoText()
        if undo_txt:
            undo += " \"" + undo_txt + "\""
        if redo_txt:
            redo += " \"" + redo_txt + "\""
        self.gui.actionUndo.setText(undo)
        self.gui.actionRedo.setText(redo)

    def get_sel_indexes(self):
        sel_indexes = self.gui.tableView.selectedIndexes()
        if sel_indexes:
            return [index for index in sel_indexes if not index.column()]

    def get_sel(self):
        sel_indexes = self.get_sel_indexes()
        if not sel_indexes:
            return self.tbm.rowCount(self), 1
        first_sel_index = sel_indexes[0]
        sel_indexes = self.get_sel_indexes()

        if not first_sel_index or not first_sel_index.isValid():
            return False
        startingrow = first_sel_index.row()

        return startingrow, len(sel_indexes)

    def remove_rows(self):
        if len(self.tbm.get_data()) == 0:
            return
        start, amount = self.get_sel()
        if start != len(self.tbm.get_data()):
            self.undoStack.beginMacro("Remove Rows")
            self.undoStack.push(RemoveRowsCommand(self.tbm, start, amount))
            self.undoStack.endMacro()
            self.set_unrdo_text()

    def add_rows(self):
        if len(self.tbm.get_header()) == 0:
            return
        start, amount = self.get_sel()

        self.undoStack.beginMacro("Add Row")
        self.undoStack.push(InsertRowsCommand(self.tbm, start, 1))
        self.undoStack.endMacro()
        self.set_unrdo_text()

    def paste(self):
        if len(self.gui.tableView.selectionModel().selectedIndexes()) == 0:
            return

        clipboard = QApplication.clipboard()
        index = self.gui.tableView.selectionModel().selectedIndexes()[0]
        command = EditCommand(self.tbm, index)
        command.newVal(str(clipboard.text()))

        self.undoStack.beginMacro("Paste")
        self.undoStack.push(command)
        self.undoStack.endMacro()
        self.set_unrdo_text()
        self.gui.tableView.reset()

    def cut(self):
        self.copy()
        index = self.gui.tableView.selectionModel().selectedIndexes()[0]
        command = EditCommand(self.tbm, index)
        command.newVal("")
        self.undoStack.beginMacro("Cut")
        self.undoStack.push(command)
        self.undoStack.endMacro()
        self.set_unrdo_text()
        self.gui.tableView.reset()

    def duplicate(self):
        if len(self.gui.tableView.selectionModel().selectedIndexes()) == 0:
            return

        start, amount = self.get_sel()
        self.undoStack.beginMacro("Duplicate Row")
        self.undoStack.push(DuplicateRowCommand(self.tbm, start))
        self.undoStack.endMacro()
        self.set_unrdo_text()
        self.gui.tableView.reset()

    def undo(self):
        self.undoStack.undo()
        self.set_unrdo_text()
        self.gui.tableView.reset()

    def redo(self):
        self.undoStack.redo()
        self.set_unrdo_text()
        self.gui.tableView.reset()
Ejemplo n.º 21
0
from django.shortcuts import render

# Create your views here.
#views.py
from login.forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from dbconnection import DBConnection
from login.forms import PostForm

connection = DBConnection()
val = connection.select()


@csrf_protect
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email'])
            return HttpResponseRedirect('/register/success/')
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {'form': form})
Ejemplo n.º 22
0
#!/usr/bin/env python3

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import romdb
from config import Configuration
from dbconnection import DBConnection

dbxmlfname = Configuration.xml_dir() + "/db_suitobject.xml"
filedbfname = Configuration.data_dir() + "/suitobject.db"

conn = DBConnection()
cur = conn.cursor()

fields = romdb.load_field_xml(dbxmlfname)

db_fields = romdb.DBFields(cur, 'suit', fields, [ 'basetype', 'suitlist' ])
db_fields.recreate_table([ ('guid', 'sys_name', 'id') ])

cur.execute('DROP TABLE IF EXISTS suit_bonus')
cur.execute("""CREATE TABLE suit_bonus (
	guid INTEGER NOT NULL,
	itemcount INTEGER NOT NULL,
	ordernum INTEGER NOT NULL,
	typeid INTEGER NOT NULL,
	value INTEGER NOT NULL,
	CONSTRAINT suitbouns_itemcount_range CHECK (itemcount >= 2 AND itemcount <= 9),
	CONSTRAINT suitbonus_ordernum_range CHECK (ordernum >= 1 AND ordernum <= 3),
	PRIMARY KEY (guid, itemcount, ordernum),
	FOREIGN KEY (typeid) REFERENCES sys_weareqtype (id),
	FOREIGN KEY (guid) REFERENCES suit 
Ejemplo n.º 23
0
class QoSTracker:
    def __init__(self):
        self.db = DBConnection(
            'postgresql://*****:*****@192.168.1.102/controllerdb')
        self.topology_manager = TopologyManager(self.db)
        self.ryu = RyuManager(self.db)
        self._current_mpls_label = 0
        self._flows_added = 0

    def start(self):
        self.db.delete_reservations()
        self.db.delete_queues()
        # self.topology_manager.init_db()
        switches = self.db.get_all_switches()
        for switch in switches:
            ryu_response = self.ryu.put_ovsdb_addr(switch.dpid)
            print "++ Adding ovsdb_addr for dpid:" + str(
                switch.dpid) + " returned: " + str(ryu_response.text)

    def generate_mpls_label(self):
        self._current_mpls_label += 1
        return self._current_mpls_label

    def get_bw_for_src_dst(self, src, dst):
        src_map = SWITCH_MAP[str(src)]
        for port in src_map:
            if str(SWITCH_MAP[str(src)][port]["dpid"]) == str(dst):
                return SWITCH_MAP[str(src)][port]["bw"]

    def add_links(self, link_data):
        # TODO: Not great way to do this
        for link in link_data:
            bw = self.get_bw_for_src_dst(link.src.dpid, link.dst.dpid)
            self.db.add_link({
                "src_port": link.src.dpid,
                "dst_port": link.dst.dpid,
                "bw": bw
            })

    def add_switches(self, switch_data):
        for switch in switch_data:
            s = self.db.add_switch(switch, HOST_MAP[str(switch.dp.id)])

    def add_single_switch_rules(self, switch, out_port, reservation):
        queues = [{"max_rate": "500000"}, {"min_rate": str(reservation.bw)}]
        response = self.ryu.add_egress_port_queue(switch, out_port.port_no,
                                                  queues, 1000000)
        print response.text
        respone = self.ryu.add_single_switch_packet_checking_flow(
            switch, reservation.dst)
        print response.text
        print "Added single switch_rules"

    def add_reservation(self, rsv):
        print "Adding reservation"
        reservation = self.db.add_reservation(rsv, self.generate_mpls_label())
        print "Added"
        in_port = self.db.get_port_for_id(reservation.in_port)
        in_switch = self.db.get_switch_for_port(in_port)

        last_port = self.db.get_port_for_id(reservation.out_port)
        last_switch = self.db.get_switch_for_port(last_port)

        path = self.topology_manager.get_route_to_host(rsv["dst"], in_switch)
        total_bw = self.topology_manager.get_max_bandwidth_for_path(path)
        print "Total Bandwidth: " + str(total_bw)

        available_bw = self.topology_manager.get_available_bandwidth_for_path(
            path)
        print "Available Bandwidth: " + str(available_bw)
        if not path:
            return
        if len(path) == 1:
            print "Correct path length"
            switch = path[0]
            print "Correct switch"
            self.add_single_switch_rules(switch, last_port, reservation)

        else:
            in_port_reservation = self.db.add_port_reservation(
                reservation.id, in_port.id)
            # TODO: this is stupid
            last_port_reservation = self.db.add_port_reservation(
                reservation.id, last_port.id)

            # Get the out port of the first switch and add the ingress rule
            first_switch_out_port_no = self.db.get_out_port_no_between_switches(
                in_switch, path[1], SWITCH_MAP)
            self.add_ingress_rules(in_switch, first_switch_out_port_no,
                                   reservation.src, reservation.dst,
                                   reservation.bw, total_bw)

            for i in range(1, len(path) - 1):
                in_port_no = self.db.get_in_port_no_between_switches_1(
                    path[i - 1], path[i], SWITCH_MAP)
                in_port = self.db.get_port_for_port_no(in_port_no,
                                                       path[i].dpid)

                out_port_no = self.db.get_out_port_no_between_switches(
                    path[i], path[i + 1], SWITCH_MAP)
                self.add_switch_rules(path[i], out_port_no, reservation.src,
                                      reservation.dst, reservation.bw,
                                      total_bw)

            in_port_no = self.db.get_in_port_no_between_switches_1(
                path[-1], path[-2], SWITCH_MAP)
            in_port = self.db.get_port_for_port_no(in_port_no, path[i].dpid)
            out_port = self.db.get_port_for_id(reservation.out_port)
            self.add_switch_rules(path[-1], out_port.port_no, reservation.src,
                                  reservation.dst, reservation.bw, total_bw)

    def add_ingress_rules(self, switch, out_port_no, src_ip, dst_ip, bw,
                          max_bw):
        # Add queues
        queues = [{"max_rate": str(max_bw)}, {"min_rate": str(bw)}]
        ryu_response = self.ryu.add_egress_port_queue(switch, out_port_no,
                                                      queues, max_bw)
        print "++ Adding port queue for dpid:" + str(
            switch.dpid) + " returned: " + str(ryu_response.text)

        # Mark the packets on their way in
        ryu_response = self.ryu.add_packet_marking_flow(switch, src_ip, dst_ip)
        print "++ Adding packet marking flow for dpid:" + str(
            switch.dpid) + " returned: " + str(ryu_response.text)

    def add_switch_rules(self, switch, out_port_no, src_ip, dst_ip, bw,
                         max_bw):
        # Add queues
        queues = [{"max_rate": str(max_bw)}, {"min_rate": str(bw)}]
        ryu_response = self.ryu.add_egress_port_queue(switch, out_port_no,
                                                      queues, max_bw)
        print "++ Adding port queue for dpid:" + str(
            switch.dpid) + " returned: " + str(ryu_response.text)

        ryu_response = self.ryu.add_packet_checking_flow(switch)
        print "++ Adding packet checking flow for dpid:" + str(
            switch.dpid) + " returned: " + str(ryu_response.text)
Ejemplo n.º 24
0
        bot.loading_failure["cache"] = e


# -----------------------   START UP   -----------------------------------

# load all Discord, MySQL, and API credentials
tokenFile = open(AUTH_FILE_PATH, "r", encoding="utf-8")
tokenLines = tokenFile.read().splitlines()
tokens = {}
for line in tokenLines:
    key_value = line.split(":")
    tokens[key_value[0]] = key_value[1]
credentials.set_tokens(tokens)

# Create MySQL connection
bot.dbconn = DBConnection(credentials.tokens["MYSQL_USER"],
                          credentials.tokens["MYSQL_PASSWORD"], "suitsBot")
bot.loading_failure = {}

# Load opus library
if not discord.opus.is_loaded():
    discord.opus.load_opus('opus')

print("\n\n------------")
print('Loading Data...')

# Load data from database
load()

print("Loading cogs...")

# Load cogs
Ejemplo n.º 25
0
def loadcache():
    """ Load Cache values from database """
    global currently_playing, scribble_bank
    try:
        currently_playing = utils.load_from_cache(bot.dbconn, "currPlaying",
                                                  "")
        scribble_bank = utils.load_from_cache(bot.dbconn, "scribble",
                                              "").split(',')
    except Exception as e:
        bot.loading_failure["cache"] = e


# -----------------------   START UP   -----------------------------------

# Create MySQL connection
bot.dbconn = DBConnection(tokens["MYSQL_USER"], tokens["MYSQL_PASSWORD"],
                          "suitsBot")
bot.loading_failure = {}

# Load opus library
if not discord.opus.is_loaded():
    discord.opus.load_opus('opus')

print("\n\n------------")
print('Loading Data...')

# Load data from database
load()

print("Loading cogs...")

# Load cogs
Ejemplo n.º 26
0
	def __init__(self):
		self.dbc = DBConnection()
		self.getDate = GetDate()
Ejemplo n.º 27
0
Archivo: mysql.py Proyecto: blaa/pybot
                return "%d rows modified." % count
            else:
                ret = "Results:\n"
                for entry in rows:
                    for key, val in entry.iteritems():
                        ret += "%s: %s\n" % (key, val)
                    ret += "\n"
                return ret

        except db.IntegrityError:
            # Nothing changed
            return "Integrity error - nothing changed."
        except db.OperationalError, e:
            code, desc = e
            return "Database operational error - try again: " + desc
        except:
            return "Database operation error. Please try again"
        finally:
            if connection:
                self.disconnect()


if __name__ == "__main__":
    m = MySQL()
    connection = DBConnection(username='******',
                              password='******',
                              db='otpasswd')
    print m.execute("insert into test values('a', 4)", connection)

# vim:tabstop=4:expandtab
Ejemplo n.º 28
0
class DBOperation(object):
	def __init__(self):
		self.dbc = DBConnection()
		self.getDate = GetDate()

	def insertAccessToken(self,accessToken):
		SQL = """INSERT INTO WECHATACTO(ACCESSTOKEN_0,CREDATTIM_0,UPDDATTIM_0,AUUID_0,CREUSR_0,UPDUSR_0) 
			VALUES(N'{0}',GETDATE(),GETDATE(),NEWID(),N'ADMIN',N'ADMIN')""".format(accessToken)
		self.dbc.execute(SQL)

	def getAccessToken(self):
		SQL = u"SELECT TOP 1 ACCESSTOKEN_0,DATEDIFF(SECOND,CREDATTIM_0,GETDATE()) EXPIRE FROM WECHATACTO ORDER BY CREDATTIM_0 DESC"
		return self.dbc.Query(SQL)

	def getUserID(self):
		SQL = u"SELECT USERID_0 FROM WECHATUSER"
		return self.dbc.Query(SQL)

	def getUserName(self, OPENID):
		SQL = u"""SELECT USERNAME_0 FROM WECHATUSER WHERE USERID_0 = N'{0}'""".format(OPENID)
		return self.dbc.Query(SQL)

	def insertUserID(self,ID, userName):
		SQL = u"""INSERT INTO WECHATUSER(USERID_0,USERNAME_0,CREDATTIM_0,UPDDATTIM_0,AUUID_0,CREUSR_0,UPDUSR_0)
			VALUES(N'{0}',N'{1}',GETDATE(),GETDATE(),NEWID(),N'ADMIN',N'ADMIN')""".format(str(ID),str(userName))
		self.dbc.execute(SQL)

	def getX3UserInfo(self,X3UserName):
		SQL = u"SELECT USR_0,NOMUSR_0 FROM AUTILIS WHERE NOMUSR_0 LIKE N'%{0}%'".format(X3UserName)
		return self.dbc.Query(SQL)
		
	def getOEMSaleTodayTotal(self,facility):
		dateRange = self.getDate.Today()
		SQL = u"""
				SELECT T3.TEXTE_0,
						CONVERT(DECIMAL(18,2),SUM(T1.ORDINVATI_0)) ORDINVATI_0,
						CONVERT(DECIMAL(18,2),SUM(ISNULL(T1.ORDINVATI_0 * T2.RATE_0,T1.ORDINVATI_0))) PRORATE_0
				FROM SORDER T1
					LEFT JOIN EXCHANGERATE T2 ON T1.CUR_0 = T2.CURRENCYFROM_0 AND T2.CREDAT_0 BETWEEN N'{1}' AND N'{2}'
					LEFT JOIN ATEXTRA T3 ON T1.CUR_0 = T3.IDENT1_0 AND T3.LANGUE_0 = N'CHI' AND T3.ZONE_0 = N'INTDES'
				WHERE T1.SALFCY_0 = N'{0}'
					AND T1.CREDAT_0 BETWEEN N'{1}' AND N'{2}'
				GROUP BY T3.TEXTE_0
			""".format(facility,dateRange["start"],dateRange["end"])
		return self.dbc.Query(SQL)
	def insertExchangeRate(self,erFrom,erTo,rate):
		dateRange = self.getDate.Today()
		SQL = u'''
				INSERT INTO EXCHANGERATE(CURRENCYFROM_0,CURRENCYTO_0,CREDAT_0,RATE_0,CREDATTIM_0,UPDDATTIM_0,AUUID_0,CREUSR_0,UPDUSR_0)
						VALUES(N'{0}',N'{1}',N'{2}',N'{3}',GETDATE(),GETDATE(),NEWID(),N'ADMIN',N'ADMIN')
				'''.format(erFrom,erTo,dateRange["start"],rate)
		self.dbc.execute(SQL)

	def getTodayQuantity(self,facility,cur):
		dateRange = self.getDate.Today()
		SQL = u"""
				SELECT T2.ZISPART_0,CONVERT(DECIMAL(18,0),SUM(T1.QTY_0)) QTY_0
				FROM SORDERQ T1
					LEFT JOIN ITMMASTER T2 ON T1.ITMREF_0 = T2.ITMREF_0
					LEFT JOIN SORDER T3 ON T1.SOHNUM_0 = T3.SOHNUM_0
					LEFT JOIN ATEXTRA T4 ON T3.CUR_0 = T4.IDENT1_0 AND T4.LANGUE_0 = N'CHI' AND T4.ZONE_0 = N'INTDES'
				WHERE T1.SALFCY_0 = N'{0}'
					AND T1.CREDAT_0 BETWEEN N'{1}' AND N'{2}'
					AND T4.TEXTE_0 = N'{3}'
				GROUP BY T4.TEXTE_0,T2.ZISPART_0
				ORDER BY T4.TEXTE_0
			""".format(facility,dateRange["start"],dateRange["end"],cur)
		return self.dbc.Query(SQL)

	def selectExchangeRate(self):
		dateRange = self.getDate.Today()
		SQL = u"""
				SELECT CURRENCYFROM_0 FROM EXCHANGERATE WHERE CREDAT_0 BETWEEN N'{0}' AND N'{1}'
			""".format(dateRange["start"],dateRange["end"])
		return self.dbc.Query(SQL)

	def getTodaySaleOrderDetails(self, facility, dateRange):
		SQL = """		
					SELECT
						T3.BPCNAM_0,
						T4.BPCNAM_0,
						T1.ITMREF_0,
						T2.ITMDES1_0,
						CONVERT(DECIMAL(18,2),T1.QTY_0),
						CONVERT(DECIMAL(18,2),T2.GROPRI_0),
						CONVERT(DECIMAL(18,2),T1.QTY_0 * T2.GROPRI_0),
						CONVERT(DECIMAL(18,2),ISNULL(T1.QTY_0 * T2.GROPRI_0 * T5.RATE_0,T1.QTY_0 * T2.GROPRI_0)),
						T3.BPCORD_0,
						T3.YBPCSHO_0,
						T1.ZRMK_0,
						T1.ZCUSNUM_0,
						T1.ZCUSNUMLIN_0,
						CONVERT(INT,T1.SOPLIN_0),
						T1.SOHNUM_0
					FROM SORDERQ T1
					LEFT JOIN SORDERP T2 ON T1.SOHNUM_0 = T2.SOHNUM_0 AND T1.SOPLIN_0 = T2.SOPLIN_0
					LEFT JOIN SORDER T3 ON T1.SOHNUM_0 = T3.SOHNUM_0
					LEFT JOIN BPCUSTOMER T4 ON T3.YBPCSHO_0 = T4.BPCNUM_0
					LEFT JOIN EXCHANGERATE T5 ON T3.CUR_0 = T5.CURRENCYFROM_0 AND T5.CREDAT_0 = N'{1}'
					WHERE T1.CREDAT_0 BETWEEN N'{1}' AND N'{1}'
					AND T1.SALFCY_0 = N'{0}'
					ORDER BY T1.SOHNUM_0,T1.SOPLIN_0
					""".format(facility,dateRange)
		return self.dbc.Query(SQL)

	def authorize(self, OPENID, facility):
		SQL = """
			INSERT INTO WECHATAUTH(USERID_0,DIMENSION_0,FCY_0,CREDATTIM_0,UPDDATTIM_0,AUUID_0,CREUSR_0,UPDUSR_0)
					VALUES(N'{0}',N'SOP',N'{1}',GETDATE(),GETDATE(),NEWID(),N'ADMIN',N'ADMIN')
		""".format(OPENID, facility)
		self.dbc.execute(SQL)

	def deauthorize(self, *args):
		argsCount = len(args)
		if argsCount == 0:
			SQL = "DELETE FROM WECHATAUTH"
		elif argsCount == 2:
			OPENID = args[0]
			facility = args[1]
			SQL = """
				DELETE FROM WECHATAUTH WHERE USERID_0 = N'{0}' AND DEMENSION_0 = N'SOP' AND FCY_0 = N'{1}'
			""".format(OPENID, facility)
		self.dbc.execute(SQL)

	def getAuthList(self,*args):
		argsCount = len(args)
		if argsCount == 0:
			SQL = """
				SELECT T1.USERID_0,T2.USERNAME_0,T1.DIMENSION_0,T1.FCY_0 
				FROM WECHATAUTH T1
					LEFT JOIN WECHATUSER T2 ON T1.USERID_0 = T2.USERID_0
			"""
                elif argsCount == 1:
                        SQL = """
				SELECT T1.USERID_0,T2.USERNAME_0,T1.DIMENSION_0,T1.FCY_0 
				FROM WECHATAUTH T1
					LEFT JOIN WECHATUSER T2 ON T1.USERID_0 = T2.USERID_0
                                WHERE T1.USERID_0 = N'{0}'
			""".format(args[0])
		elif argsCount == 2:
			SQL = """
				SELECT T1.USERID_0,T2.USERNAME_0,T1.DIMENSION_0,T1.FCY_0 
				FROM WECHATAUTH T1
					LEFT JOIN WECHATUSER T2 ON T1.USERID_0 = T2.USERID_0
				WHERE {}
			""".format(args[0], args[1])
		return self.dbc.Query(SQL)
Ejemplo n.º 29
0
 def __init__(self):
     self.db = DBConnection('sqlite:///my_db.db')
     self.topology_manager = TopologyManager(self.db)
     self.ryu = RyuManager(self.db)
     self._current_mpls_label = 0
     self._flows_added = 0
Ejemplo n.º 30
0
class CCManagerRoot(Tk):

    dbifc = DBConnection()
    user = User.current(dbifc)

    def __init__(self, **kw):
        super().__init__(**kw)

        self.title("CQC - Kontroll diagram modul")

        self.active_panel = None
        self.active_toplevel = None
        self.ccobject = ControlChart()

        self.menubar = RootMenu(self)
        self.config(menu=self.menubar)
        self.menubar.lock()

        self.chartholder = ChartHolder(self)
        self.chartholder.update_image(None)
        self.chartholder.pack(**pkw)
        self.propspanel = None
        self.properties_button = Button(
            self,
            text="Tulajdonságok megjelenítése",
            state="disabled",
            command=lambda: self.launch_propspanel(stage=None))
        self.properties_button.pack(**pkw)
        self.protocol("WM_DELETE_WINDOWS", self.teardown)

    def launch_propspanel(self, stage=None):
        if self.propspanel is not None:
            self.propspanel.destroy()
        self.propspanel = PropertiesPanel(self, self.ccobject, self.dbifc,
                                          stage)

    def savecc_cmd(self):
        if self.ccobject.unsaved is None:
            print("UNSAVED IS NONE! NOT SAVING!")
            return
        if self.ccobject.ccrec["id"] is None:
            self.dbifc.push_object(self.ccobject)
        else:
            self.dbifc.update_cc(self.ccobject)

    def newcc_cmd(self):
        if self.ccobject.unsaved:
            msg = ("A jelenlegi állapot nincs elmentve.", "Szeretnéd menteni?")
            if tkmb.askyesno("Mentetlen adat!", "\n".join(msg)):
                self.savecc_cmd()
        wiz = self._build_stage()
        if wiz is None:
            return
        self.launch_propspanel(wiz.stage)
        self.wait_window(self.propspanel)
        if self.propspanel.canceled:
            return
        self.ccobject.set_upstream_ids()
        self.propspanel = None
        IDs = self.dbifc.push_object(self.ccobject)
        rex = self.ccobject.rec
        for rectype, ID in IDs.items():
            if rex[rectype]["id"] is None:
                rex[rectype]["id"] = ID
            else:
                assert rex[rectype]["id"] == ID
        self.chartholder.update_image(self.ccobject)
        self.menubar.unlock()
        self.properties_button.configure(state="active")

    def opencc_cmd(self):
        wiz = SelectionWizard(self,
                              creation_mode=False,
                              skipempties=True,
                              dbifc=self.dbifc)
        self.wait_window(wiz)
        if wiz.stage is None:
            return
        cc = ControlChart.from_database(
            dbifc=self.dbifc,
            ccID=wiz.selection["cc"],
        )
        self.ccobject = cc
        self.chartholder.update_image(self.ccobject)
        self.menubar.unlock()
        self.properties_button.configure(state="active")

    def deletecc_cmd(self):
        msg = "Valóban törölni szeretnéd a kontroll diagramot?"
        if not tkmb.askyesno("Törlés megerősítése", msg):
            return
        if self.ccobject.ID is not None:
            self.dbifc.delete_cc(self.ccobject.ID)
            path = self.ccobject.pkldump()
            print("Backed up ControlChart object to", path)
        self.ccobject = ControlChart()
        self.chartholder.update_image(None)
        self.menubar.lock()

    def newpoints_cmd(self):
        mtl = NewMeasurements(self, rown=3, title="Pontok bevitele")
        self.wait_window(mtl)
        print("VALUES : ", ", ".join(map(str, mtl.measure["value"])))
        print("DATES  : ", ", ".join(map(str, mtl.measure["date"])))
        print("COMMENT: ", ", ".join(map(str, mtl.measure["comment"])))
        mtl.measure.setall(cc_id=self.ccobject.ID,
                           staff_id=self.user["id"],
                           reference=False)
        self.ccobject.meas.incorporate(mtl.measure.data)
        self.dbifc.push_measurements(mtl.measure)
        self.chartholder.update_image(self.ccobject)

    def editpoints_cmd(self):
        mtl = EditMeasurements(self,
                               self.ccobject.meas,
                               rown=10,
                               title="Pontok szerkesztése")
        self.wait_window(mtl)

    def _build_stage(self):
        wiz = SelectionWizard(self,
                              creation_mode=True,
                              skipempties=False,
                              dbifc=self.dbifc)
        self.wait_window(wiz)
        if wiz.stage is None:
            return
        self.ccobject = ControlChart.build_stage(wiz.selection, wiz.stage,
                                                 self.dbifc)
        return wiz

    def teardown(self):
        print("UI nice shutdown")
        self.destroy()
Ejemplo n.º 31
0
#!/usr/bin/env python3

import os, sys

sys.path.append(os.path.join(os.path.dirname(__file__), "..", "lib"))
import romdb
from config import Configuration
from dbconnection import DBConnection

dbxmlfname = Configuration.xml_dir() + "/db_weaponobject.xml"
filedbfname = Configuration.data_dir() + "/weaponobject.db"

conn = DBConnection()
cur = conn.cursor()

fields = romdb.load_field_xml(dbxmlfname)

# construct db table
db_fields = romdb.DBFields(cur, "weapon", fields, ["eqtype", "dropability"])
db_fields.recreate_table([("guid", "sys_name", "id")])

cur.execute("DROP TABLE IF EXISTS weapon_ability")
cur.execute(
    """CREATE TABLE weapon_ability (
	guid INTEGER NOT NULL,
	ordernum INTEGER NOT NULL,
	abilityid INTEGER NOT NULL,
	CONSTRAINT weapon_ability_ordernum_range CHECK (ordernum >= 1 AND ordernum <= 6),
	CONSTRAINT weapon_ability_ability_range CHECK (abilityid / 10000 IN (51, 72)),
	PRIMARY KEY (guid, ordernum),
	FOREIGN KEY (guid) REFERENCES weapon
Ejemplo n.º 32
0
def install():

    dbConn = DBConnection()
    conn = dbConn.connection()
    cur = conn.cursor()

    #creating movie table

    cur.execute(
        '''CREATE TABLE IF NOT EXISTS movies(ID INTEGER PRIMARY KEY AUTOINCREMENT, TITLE TEXT NOT NULL)'''
    )

    cur.execute("INSERT INTO movies(TITLE) \
            VALUES ('Die Hard 4.0')")

    cur.execute("INSERT INTO movies(TITLE) \
            VALUES ('John Wick')")

    cur.execute("INSERT INTO movies(TITLE) \
            VALUES ('John Wick 2')")

    cur.execute(
        '''CREATE TABLE IF NOT EXISTS movie_days(ID INTEGER PRIMARY KEY AUTOINCREMENT, movie_id INTEGER NOT NULL, day TEXT)'''
    )

    cur.execute("INSERT INTO movie_days(movie_id,day) \
            VALUES (1,'TUE')")
    cur.execute("INSERT INTO movie_days(movie_id,day) \
            VALUES (1,'WED')")
    cur.execute("INSERT INTO movie_days(movie_id,day) \
            VALUES (1,'FRI')")
    cur.execute("INSERT INTO movie_days(movie_id,day) \
            VALUES (2,'MON')")
    cur.execute("INSERT INTO movie_days(movie_id,day) \
            VALUES (2,'WED')")
    cur.execute("INSERT INTO movie_days(movie_id,day) \
            VALUES (2,'THUR')")
    cur.execute("INSERT INTO movie_days(movie_id,day) \
            VALUES (2,'FRI')")
    cur.execute("INSERT INTO movie_days(movie_id,day) \
            VALUES (3,'FRI')")

    cur.execute(
        '''CREATE TABLE IF NOT EXISTS movie_timings(ID INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL, time TEXT)'''
    )
    cur.execute(
        '''CREATE TABLE IF NOT EXISTS movie_booking ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `time_id` INTEGER NOT NULL, `row` INTEGER NOT NULL, `col` INTEGER NOT NULL, `username` TEXT NOT NULL )'''
    )
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (1,'09:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (1,'11:30')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (2,'14:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (2,'20:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (3,'22:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (3,'22:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (4,'22:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (4,'22:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (5,'22:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (6,'22:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (7,'22:00')")
    cur.execute("INSERT INTO movie_timings(day_id,time) \
            VALUES (8,'22:00')")
    conn.commit()
    conn.close()
Ejemplo n.º 33
0
class QoSTracker:

    def __init__(self):
        self.db = DBConnection('sqlite:///my_db.db')
        self.topology_manager = TopologyManager(self.db)
        self.ryu = RyuManager(self.db)
        self._current_mpls_label = 0
        self._flows_added = 0

    def start(self):
        self.db.delete_reservations()
        self.db.delete_queues()
        # self.topology_manager.init_db()
        switches = self.db.get_all_switches()
        for switch in switches:
            ryu_response = self.ryu.put_ovsdb_addr(switch.dpid)
            print "++ Adding ovsdb_addr for dpid:" + str(switch.dpid) + " returned: " + str(ryu_response.text)

    def generate_mpls_label(self):
        self._current_mpls_label += 1
        return self._current_mpls_label

    def get_bw_for_src_dst(self, src, dst):
        src_map = SWITCH_MAP[str(src)]
        for port in src_map:
            if str(SWITCH_MAP[str(src)][port]["dpid"]) == str(dst):
                return SWITCH_MAP[str(src)][port]["bw"]

    def add_links(self, link_data):
        # TODO: Not great way to do this
        for link in link_data:
            bw = self.get_bw_for_src_dst(link.src.dpid, link.dst.dpid)
            self.db.add_link({
                "src_port": link.src.dpid,
                "dst_port": link.dst.dpid,
                "bw": bw
            })

    def add_switches(self, switch_data):
        for switch in switch_data:
            s = self.db.add_switch(switch, HOST_MAP[str(switch.dp.id)])

    def add_single_switch_rules(self, switch, out_port, reservation):
        queues = [{"max_rate": "500000"}, {"min_rate": str(reservation.bw)}]
        response = self.ryu.add_egress_port_queue(switch, out_port.port_no, queues, 1000000)
        print response.text
        respone = self.ryu.add_single_switch_packet_checking_flow(switch, reservation.dst)
        print response.text
        print "Added single switch_rules"

    def add_reservation(self, rsv):
        print "Adding reservation"
        reservation = self.db.add_reservation(rsv, self.generate_mpls_label())
        print "Added"
        in_port = self.db.get_port_for_id(reservation.in_port)
        in_switch = self.db.get_switch_for_port(in_port)

        last_port = self.db.get_port_for_id(reservation.out_port)
        last_switch = self.db.get_switch_for_port(last_port)

        path = self.topology_manager.get_route_to_host(rsv["dst"], in_switch)
        total_bw = self.topology_manager.get_max_bandwidth_for_path(path)
        print "Total Bandwidth: " + str(total_bw)

        available_bw = self.topology_manager.get_available_bandwidth_for_path(path)
        print "Available Bandwidth: " + str(available_bw)
        if not path:
            return
        if len(path) == 1:
            print "Correct path length"
            switch = path[0]
            print "Correct switch"
            self.add_single_switch_rules(switch, last_port, reservation)

        else:
            in_port_reservation = self.db.add_port_reservation(reservation.id, in_port.id)
            # TODO: this is stupid
            last_port_reservation = self.db.add_port_reservation(reservation.id, last_port.id)
            
            # Get the out port of the first switch and add the ingress rule
            first_switch_out_port_no = self.db.get_out_port_no_between_switches(in_switch, path[1], SWITCH_MAP)
            self.add_ingress_rules(in_switch, first_switch_out_port_no, reservation.src, reservation.dst, reservation.bw, total_bw)

            for i in range(1, len(path) - 1):
                in_port_no = self.db.get_in_port_no_between_switches_1(path[i-1], path[i], SWITCH_MAP)
                in_port = self.db.get_port_for_port_no(in_port_no, path[i].dpid)

                out_port_no = self.db.get_out_port_no_between_switches(path[i], path[i+1], SWITCH_MAP)
                self.add_switch_rules(path[i], out_port_no, reservation.src, reservation.dst, reservation.bw, total_bw)

            in_port_no = self.db.get_in_port_no_between_switches_1(path[-1], path[-2], SWITCH_MAP)
            in_port = self.db.get_port_for_port_no(in_port_no, path[i].dpid)
            out_port = self.db.get_port_for_id(reservation.out_port)
            self.add_switch_rules(path[-1], out_port.port_no, reservation.src, reservation.dst, reservation.bw, total_bw)

    def add_ingress_rules(self, switch, out_port_no, src_ip, dst_ip, bw, max_bw):
        # Add queues
        queues = [{"max_rate": str(max_bw)}, {"min_rate": str(bw)}]
        ryu_response = self.ryu.add_egress_port_queue(switch, out_port_no, queues, max_bw)
        print "++ Adding port queue for dpid:" + str(switch.dpid) + " returned: " + str(ryu_response.text)

        # Mark the packets on their way in
        ryu_response = self.ryu.add_packet_marking_flow(switch, src_ip, dst_ip)
        print "++ Adding packet marking flow for dpid:" + str(switch.dpid) + " returned: " + str(ryu_response.text)

    def add_switch_rules(self, switch, out_port_no, src_ip, dst_ip, bw, max_bw):
        # Add queues
        queues = [{"max_rate": str(max_bw)}, {"min_rate": str(bw)}]
        ryu_response = self.ryu.add_egress_port_queue(switch, out_port_no, queues, max_bw)
        print "++ Adding port queue for dpid:" + str(switch.dpid) + " returned: " + str(ryu_response.text)

        ryu_response = self.ryu.add_packet_checking_flow(switch)
        print "++ Adding packet checking flow for dpid:" + str(switch.dpid) + " returned: " + str(ryu_response.text)