Beispiel #1
0
 def __init__(self, id, *args, **kwargs):
     super(TableWindow, self).__init__(*args, **kwargs)
     self.setupUi(self)
     self.dishNum = '0'
     self.totalPrice.setText('0')
     self.btnExit.clicked.connect(self.btn_exit_pressed)
     self.dishes = []
     self.idToRemove = 0
     global TABLE
     TABLE = None
     self.order = {}
     for table in TABLES:
         if table.id == id:
             TABLE = table
     if TABLE is None:
         TABLE = database.Table(id)
         TABLES.append(TABLE)
     self.update()
     self.labelTable.setText('Table: ' + str(TABLE.id))
     for i in range(0, 10):
         getattr(self, 'btn%s' %i).clicked.connect(self.btn_num_pressed)
     self.btnQuanti.clicked.connect(self.btn_num_pressed)
     self.btnDel.clicked.connect(self.btn_del_pressed)
     self.btnOk.clicked.connect(self.btn_ok_pressed)
     self.btnOrder.clicked.connect(self.btn_order_pressed)
     self.btnCancel.clicked.connect(self.btn_cancel_pressed)
     self.btnPay.clicked.connect(self.btn_pay_pressed)
     self.listDish.clicked.connect(self.clicked)
     self.btnDelete.clicked.connect(self.btn_delete_pressed)
     self.btnMinus.clicked.connect(self.btn_delete_pressed)
Beispiel #2
0
 def _init_store(self):
     tname = self.config['parser_config']['name']
     if self.test:
         tname = 'test_' + self.name
     self.item_class = self.db.create_table_if_not_exists(
         tname, self.col_map.keys(), self.fmt)
     self.store = database.Table(self.db, self.item_class, ['url'])
Beispiel #3
0
 def permissions(self, permission):
     table = database.Table(tables["user_permissions"])
     if table.exist("telegram_id", self.telegram_id):
         table.update("telegram_id", self.telegram_id, permission, 1)
     else:
         table.insert(["telegram_id", permission], [self.telegram_id, 1])
     table.close()
Beispiel #4
0
 def test_delete_order(self):
     table1 = database.Table(1)
     table1.take_order(1, 2)
     table1.take_order(2, 1)
     self.assertEqual(table1.totalPrice, 9.5)
     table1.delete_order(1)
     self.assertEqual(table1.totalPrice, 3.5)
Beispiel #5
0
def login():
    form = forms.LoginForm(request.form)

    if request.method == 'POST':
        username = form.username.data
        user_password = form.password.data

        users = database.Table("users", "first_name", "last_name", "username",
                               "email", "password")
        user = users.getone('username', username)
        db_password = user.get('password')

        if db_password is None:
            flash('User with this username does not exists!', 'danger')
            return redirect(url_for('login'))
        else:
            if sha256_crypt.verify(user_password, db_password):
                login_get(username)
                flash(
                    'Congratulations! You have been logged in to your account.',
                    'success')
                return redirect(url_for('dashboard'))
            else:
                flash('Incorrect Password!', 'danger')
                return redirect(url_for('login'))

    return render_template('login.html', title="Login")
Beispiel #6
0
 def set_manager_admin(self, manager_tid, admin_tid):
     table = database.Table(tables["managers_admins"])
     if table.exist("manager_tid", manager_tid):
         table.update("manager_tid", manager_tid, "admin_tid", admin_tid)
     else:
         table.insert(["manager_tid", "admin_tid"],
                      [manager_tid, admin_tid])
     table.close()
Beispiel #7
0
 def create(self, name):
     table = database.Table(name)
     fields, types = self.fields[self.names.index(name)], self.types[
         self.names.index(name)]
     table.create(fields, types)
     table.send_query(
         "ALTER TABLE {table_name} CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"
         .format(table_name=name))
     table.close()
Beispiel #8
0
    def user_status(self, telegram_id):
        table = database.Table(tables["user_permissions"])
        permissions = table.select(["owner", "admin", "manager", "modeartor"], "telegram_id", telegram_id)[0]
        table.close()

        self.owner = permissions[0]
        self.admin = permissions[1]
        self.manager = permissions[2]
        self.moderator = permissions[3]
Beispiel #9
0
    def set_employee(self, employee_tid, employee):
        table = database.Table(tables["permissions"])
        if table.exist("tid", employee_tid):
            table.update("tid", employee_tid, employee, 1)
        else:
            table.insert(["tid", employee], [employee_tid, 1])
        table.close()

        if employee_tid not in self.privileged_users:
            self.privileged_users.append(employee_tid)
Beispiel #10
0
    def get_managers_admins(self):

        table = database.Table(tables["managers_admins"])
        pairs = table.select_all(["manager_tid", "admin_tid"], to_dict=True)
        table.close()

        self.managers_admins = {}
        for pair in pairs:
            self.managers_admins[pair["manager_tid"]] = pair["admin_tid"]
        print(self.managers_admins)
Beispiel #11
0
def login_get(username):
    users = database.Table("users", "first_name", "last_name", "username",
                           "email", "password")
    user = users.getone('username', username)

    session['logged_in'] = True
    session['username'] = username
    session['first_name'] = user.get('first_name')
    session['last_name'] = user.get('last_name')
    session['email'] = user.get('email')
Beispiel #12
0
    def get_privileged_users(self):

        table = database.Table(tables["permissions"])
        users = table.select_all(
            ["tid", "owner", "admin", "manager", "moderator"], to_dict=True)
        table.close()

        self.privileged_users = [user["tid"] for user in users]
        self.owners = [user["tid"] for user in users if user["owner"]]
        self.admins = [user["tid"] for user in users if user["admin"]]
        self.managers = [user["tid"] for user in users if user["manager"]]
        self.moderators = [user["tid"] for user in users if user["moderator"]]
Beispiel #13
0
    def write_default_data(self):
        table_names = []
        for table_name, fields, values in self.default_data:
            if table_name not in table_names:
                table_names.append(table_name)

        for table_name_now in table_names:
            table = database.Table(table_name_now)
            for table_name, fields, values in self.default_data:
                if table_name_now == table_name:
                    table.insert(fields, values)
            table.close()
Beispiel #14
0
Datei: main.py Projekt: nav/dbviz
async def root(request: Request, table: str = ""):
    if config is None:
        return RedirectResponse(url="/connect")

    columns = []
    if table:
        table = database.Table(name=table)
        table = db.backend.populate_columns_for_table(table)
        table = db.backend.populate_outbound_related_tables(table)
        table = db.backend.populate_inbound_related_tables(table)
        dot = database.generate_dot_diagram(table)
        return templates.TemplateResponse(
            "viewer.html", {"request": request, "table": table, "dot": dot}
        )

    return templates.TemplateResponse("index.html", {"request": request, "db": db})
Beispiel #15
0
    def test_pass_from_db(self):
        LOGIN = "******"
        PASSWORD = "******"

        class MockOpt(object):
            login = ""

        opt = MockOpt()
        password = byfly.pass_from_db(LOGIN, self.DB_FILENAME, opt)
        self.assertIsNone(password)
        table = database.Table(self.DB_FILENAME)
        record = table.add(Record(LOGIN, PASSWORD))
        password = byfly.pass_from_db(LOGIN, self.DB_FILENAME, opt)
        self.assertEqual(password, PASSWORD)

        password = byfly.pass_from_db(LOGIN, self.DB_FILENAME, None)
        self.assertIsNone(password)
Beispiel #16
0
def saveToDatabase(rawData):
    userid = rawData.get('player')['userid']
    logg(f' [{userid}] saving data to database...')

    # save to table users
    user = database.User.query.get(userid)
    if user == None:
        database.db.session.add(
            database.User(userid=userid,
                          username=rawData.get('player')['username'],
                          cost=rawData.get('cost'),
                          old_cost=rawData.get('old_cost'),
                          player=rawData.get('player'),
                          pp=rawData.get('pp'),
                          time=rawData.get('time')))
    else:
        user.name = rawData.get('player')['username'],
        user.cost = rawData.get('cost'),
        user.player = rawData.get('player'),
        user.pp = rawData.get('pp'),
        user.time = rawData.get('time')

    # save to table tables
    table = database.Table.query.get(userid)
    if table == None:
        database.db.session.add(
            database.Table(userid=userid,
                           table=rawData.get('table'),
                           time=rawData.get('time')))
    else:
        table.userid = userid
        table.table = rawData.get('table'),
        table.time = rawData.get('time')

    # add the record
    database.db.session.add(
        database.Record(userid=userid,
                        username=rawData.get('player')['username'],
                        cost=rawData.get('cost'),
                        old_cost=rawData.get('old_cost'),
                        player=rawData.get('player'),
                        pp=rawData.get('pp'),
                        time=rawData.get('time')))

    database.db.session.commit()
    logg(f' [{userid}] complete!')
Beispiel #17
0
def privileged():
    fields = ["telegram_id", "owner", "admin"]
    users = []

    table = database.Table(tables["user_permissions"])
    users_data = table.select_all(fields)
    table.close()

    for user_data in users_data:
        user = {}
        for i, field in enumerate(fields):
            user[field] = user_data[i]
        users.append(user)

    all = [user["telegram_id"] for user in users]
    owner_and_admins = [user["telegram_id"] for user in users if user["owner"] or user["admin"]]
    return all, owner_and_admins
Beispiel #18
0
def register():
    form = forms.RegisterForm(request.form)
    users = database.Table("users", "first_name", "last_name", "username",
                           "email", "password")

    if request.method == 'POST' and form.validate():
        first_name = form.first_name.data
        last_name = form.last_name.data
        username = form.username.data
        email = form.email.data

        if database.isnewuser(username):
            password = sha256_crypt.encrypt(form.password.data)
            users.insert(first_name, last_name, username, email, password)
            login_get(username)
            return redirect(url_for('login'))
        else:
            flash(
                'User with this username already exists. Please try again with different username!',
                'danger')
            return redirect(url_for('register'))

    return render_template('signup.html', title="Sign Up", form=form)
Beispiel #19
0
 def test_enter_element_list(self):
     tb = database.Table()
     self.assertEqual(tb.enter_element_list(), ["a", "bc", 5])
Beispiel #20
0
 def delete(self, name):
     table = database.Table(name)
     table.delete_table("yes")
     table.close()
Beispiel #21
0
 def test_take_order(self):
     table1 = database.Table(1)
     table1.take_order(1, 2)
     self.assertEqual(table1.orders, {1: 2})
     self.assertEqual(table1.totalPrice, 6)
Beispiel #22
0
 def test_table_push_element(self):
     tb = database.Table()
     tb.push([1, 2, 3])
     tb.push([1])
     self.assertEqual(tb, [[1], [1, 2, 3]])
Beispiel #23
0
        fields['macaddress'] = 'NA'
except:
    ip = "1.2.3.4"
    ip = "108.56.138.39"
    localip = "192.168.1.1"
    macaddress = 'junk:mac:address'
    dev_type = "ClockIOT"
    fields = {'localip':localip, 'macaddress':macaddress, 'dev_type':dev_type}

DB_FN = 'timezone.db'
db = sqlite3.connect(DB_FN)

Timezone = database.Table('Timezone', db,
                          Column('first_update', Integer()),
                          Column('last_update', Integer()),
                          Column('tz_count', Integer()),
                          Column('timezone', String()),
                          Column('utc_offset', String()),
)

Device = database.Table('Device', db,
                        Column('timezone_rowid', Integer()),
                        Column('first_update', Integer()),
                        Column('last_update', Integer()),
                        Column('count', Integer()),
                        Column('ip',String()),
                        Column('latitude',Float()),
                        Column('longitude',Float()),
                        Column('city', String()),
                        Column('region', String()),
                        Column('country_name', String()),
Beispiel #24
0
 def test_table_pop_element(self):
     tb = database.Table()
     tb.push([1, 2, 3])
     tb.push([1])
     self.assertEqual(tb.pop_(), [1])
Beispiel #25
0
 def test_table_print(self):
     tb = database.Table([1, 2, 3])
     tb.print()
Beispiel #26
0
def parse_table(data):
    ''' Takes a DataTable as input and returns a Table instance. '''

    table = database.Table()
    n_cols = data.n_cols

    # Identify column names: first occurrence of unique (i.e. colspan=1) label.
      # Also track multi-column labels for gurroup names.
    labels = [None] * n_cols
    multicol_labels = {}

    for i in range(data.n_rows()):
        r = data[i]
        for j, val in enumerate(r):
            # If a value is provided and the cell isn't an overflow cell (i.e., '@@'), and
            # there is no current label assigned to this column...
            if val != '' and not val.startswith('@@') and labels[j] is None:
                # Handle the first column separately, because first value in table
                # is often mistaken for label if label is left blank.
                # If all other labels have been found, or if there are lots of numbers
                # in the row, we must already be in contents, so assume the first row
                # denotes regions. Otherwise assume this is a regular column name.
                # Note: this heuristic is known to fail in the presence of multiple
                # unlabeled region columns. See e.g., CerCor bhl081, table 2.
                if j == 0 and (None not in labels[1::] or regex.search('\d+.*\d+.*\d+', '/'.join(r))):
                    labels[j] = 'region'
                else:
                    labels[j] = val
            else:
                # Store any multi-column labels. Key is the starting index and
                # colspan.
                m = regex.search('^@@(.*)@(\d+)$', val)
                if m:
                    multicol_labels["%d/%s" % (j, m.group(2))] = m.group(1)

    # Compact the list, although there shouldn't be any missing values at this point...
    # labels = [x.lower() for x in labels if x is not None]

    # Convert all labels to lowercase
    labels = [x.lower() if x is not None else x for x in labels]
    n_cols = len(labels)

    # Sometimes tables have a single "Coordinates" column name
    # despite breaking X/Y/Z up into 3 columns, so we account for this here.
    for k, v in multicol_labels.items():
        if regex.search('(ordinate|x.*y.*z)', v):
            st, span = k.split('/')
            start, end = int(st), (int(st) + int(span))
            if not regex.search('[a-zA-Z]', ''.join(labels[start:end])):
                logger.info(
                    "Possible multi-column coordinates found: %s, %s" % (k, v))
                labels[start:end] = ['x', 'y', 'z']

    # There shouldn't be any unfilled column labels at this point, but if there are,
    # log that information and skip table if flag is set.
    if None in labels:
        labels = [unicode(l) for l in labels]
        msg = 'Failed to identify at least one column label: [%s]. Skipping table!' % ', '.join(labels)
        if config.EXCLUDE_TABLES_WITH_MISSING_LABELS:
            logger.error(msg)
            return None
        else:
            logger.warning(msg)


    # Detect any standard column labels and any repeating column groups
    standard_cols = identify_standard_columns(labels)
    group_cols = identify_repeating_groups(labels)
    logger.debug("Labels: " + ', '.join(labels))
    logger.debug("Standard columns:" + ', '.join([unicode(x) for x in standard_cols if x is not None]))

    # Store a boolean list indicating which columns belong to a group
    cols_in_group = [False] * n_cols
    for g in group_cols:
        onset, length = [int(i) for i in g.split('/')]
        for i in range(onset, onset+length):
            cols_in_group[i] = True

    # Also store non-group labels for easy lookup later
    nongroup_labels = [l for (i,l) in enumerate(labels) if not cols_in_group[i]]

    # Loop over rows in table
    group_row = None
    activation_num = 0
    
    for r in data:

        logger.debug(r)

        n_cells = len(r)

        # Skip row if any value matches the column label--assume we're in header
        match_lab = False
        for i in range(n_cells):
            if r[i] == labels[i]: match_lab = True
        if match_lab: continue

        # If row is empty except for value in first column, assume the next few 
        # rows of coordinates are grouped together under this heading.
        # Note that this won't extract a hierarchical structure;
        # e.g., if there are two consecutive group-denoting rows,
        # the value in the second row will overwrite the one in the first row.
        if r[0] and not ''.join(r[1::]).strip():
            group_row = r[0].strip()
            continue

        # If first cell spans ALL columns, it probably also denotes a group, as we 
        # should already be past all header rows.
        if r[0].startswith('@@'):
            m = regex.search('@(\d+)', r[0])
            if int(m.group(1)) == n_cols:
                group_row = r[0].split('@')[2].strip()
                continue

        # Skip any additional header rows
        if n_cells != n_cols or regex.search('@@', ' '.join(r)): continue




      
        # If we don't have to worry about groups, the entire row is a single activation
        if not len(group_cols):
            activation = create_activation(r, labels, standard_cols, group_row)
            if activation.validate():
                table.activations.append(activation)

        # ...otherwise we need to iterate over groups and select appropriate columns for each.
        else:

            # Loop over groups and select appropriate columns
            for g in group_cols:
                onset, length = [int(i) for i in g.split('/')]
                # Get current grouping labels. Occasionally there are tables that have multiple 
                # groups of columns but don't attach separate high-order labels to them, so check
                # for the key first.
                groups = [multicol_labels[g]] if g in multicol_labels else []
                if group_row is not None: groups.append(group_row)
                group_specific_cols = range(onset, onset+length)

                # Select columns that belong to this activation: all columns that do not 
                # belong to any group, plus any columns that belong only to this group.
                activation_labels = []
                activation_columns = []
                activation_scs = [] # standard columns
                for (i,x) in enumerate(r):
                    if not cols_in_group[i] or i in group_specific_cols:
                        activation_labels.append(labels[i])
                        activation_columns.append(r[i])
                        activation_scs.append(standard_cols[i])
          
                # Create activation and add to table if it passes validation
                activation = create_activation(activation_columns, activation_labels, activation_scs, groups)
                if activation.validate():
                    table.activations.append(activation)
    table.finalize()
    return table if len(table.activations) else None
Beispiel #27
0
import database

table = database.Table(database.tables["user_permissions"], logging=True)
print (table.exist("telegram_id", 385778185))
table.close()


Beispiel #28
0
 def test_enter_element_dict(self):
     tb = database.Table()
     self.assertEqual(tb.enter_element_dict(), {'10': '10', '20': '20'})
Beispiel #29
0
                (columns_i, columns_j) = (row, col)
                for i in range(columns_i, worksheet.nrows):
                    if type(worksheet.cell_value(i, col)) != str:
                        (idata, jdata) = (i, col)
                        break
                break
        if (columns_i, columns_j) != (0, 0):
            break
    for col in range(jdata, worksheet.ncols - 1):
        data[worksheet.cell_value(columns_i, col)] = []
        for row in range(idata, worksheet.nrows - 2):
            data[worksheet.cell_value(columns_i, col)].append(
                worksheet.cell_value(row, col))
    return data


pat = 'communal_2019.xlsx'
dpath = '../assets/db.sqlite3'
""" download(pat) """
dt = dic_from(pat)
dt = database.DatasetUtils.preprocess(dt)
db = database.Database(dpath)
tb = database.Table(db.db, 'commune',
                    database.DatasetUtils.generate_attributes(dt))
for i in range(len(dt[list(dt.keys())[0]]['values'])):
    values = []
    for key in dt.keys():
        values.append(dt[key]['values'][i])
    tb.insert(values)
db.close()
Beispiel #30
0
 def test_table_replace_element(self):
     tb = database.Table()
     tb.push([1, 2, 3])
     tb.push([1])
     tb.replace([2])
     self.assertEqual(tb, [[2], [1, 2, 3]])