Пример #1
0
def compose():
  form = ComposeForm(request.form)
  if request.method == 'GET' or not form.validate():
    return render_template('compose.html', form=form, user=current_user)
  # First, get the topics
  topics = re.compile(r'#([a-zA-Z0-9_-]+)\s*').findall(form.topics.data)
  topic_ids = []
  if topics:
    topic_ids = topic_strings_to_ids(topics)
  if len(topic_ids) != len(topics):
    return render_template(
      'error.html',
      message="Database error :(",
    )
  # Next, create the post
  rows = select(
    'INSERT INTO posts (title, body, "user") VALUES(%s, %s, %s) RETURNING *',
    (form.title.data, form.body.data, current_user.get_id()),
  )
  if not rows:
    return render_template(
      'error.html',
      message="Database error :(",
    )
  post_id = rows[0]["id"]
  # Finally, create the topic associations
  if topic_ids:
    values_clause = ','.join(('(%s, %s)',) * len(topic_ids))
    values = sum([(post_id, topic_id) for topic_id in topic_ids], ())
    select(
      'INSERT INTO tags("from", "to") VALUES %s RETURNING *' % values_clause,
      values,
    )
  return redirect(url_for('post.post', post=post_id))
Пример #2
0
def invoice(username):
    print('View your Invoice\n', ('-' * 30), '\n\n', ('-' * 15),
          ' Shared Power ', ('-' * 15))
    user = database.select("SELECT * FROM users WHERE username = '******'")
    date = datetime.datetime.now()
    print('Full Name: ', user[0][3], ' ' * 10, 'Username: '******'Invoice Date and Time: ', date)
    print('Invoice Period: 1-' + str(date.month) + '-' + str(date.year) +
          ' To ' + str(date.day) + "-" + str(date.month) + "-" +
          str(date.year) + '\n' + ('-' * 50))

    bookings = database.select("SELECT * FROM bookings WHERE username = '******' AND NOT total = 0 AND date BETWEEN '" +
                               str(date.year) + "-" + str(date.month) +
                               "-01' AND '" + str(date.year) + "-" +
                               str(date.month) + "-" + str(date.day) +
                               "' ORDER BY date DESC")
    total = 0
    for booking in bookings:
        item = database.select("SELECT * FROM tools WHERE id = " +
                               str(booking[1]))
        print('\nTool Name: ', item[0][1])
        print('Full Day Rate: $', (item[0][3]), '     Half Day Rate: $',
              (item[0][4]))
        print('Booked On: ', booking[3])
        print('Collection Mode: ', booking[4])
        print('Return Mode: ', booking[5])
        print('Return Condition: ', booking[6])
        print('Total Charge: $', booking[7])
        print('-' * 35)
        total += booking[7]
    print('\nTotal Amount: $' + str(total) + '\nInsurance: $5' +
          '\nAmount Due for Payment: $' + str(total + 5))
Пример #3
0
def topic_strings_to_ids(topics):
  # First, see if they exist
  in_clause = ','.join(('%s',) * len(topics))
  print in_clause
  results = select(
    'SELECT * FROM topics WHERE name IN (%s)' % in_clause,
    topics,
  ) 
  # Figure out which topics already exist
  ids = []
  need_creation = []
  for topic in topics:
    found = False
    for result in results:
      if topic == result["name"]:
        ids.append(result["id"])
        found = True
        break
    if not found:
      need_creation.append(topic)
  if not need_creation:
    return ids
  values_clause = ','.join(('(%s)',) * len(need_creation))
  creation = select(
    'INSERT INTO topics(name) VALUES %s RETURNING *' % values_clause,
    need_creation,
  )
  for row in creation:
    ids.append(row["id"])
  return ids
Пример #4
0
def register():
  """Controller for the register page."""
  # TODO: redirect back to where we came from
  form = RegistrationForm(request.form)
  if request.method == 'GET' or not form.validate():
    return render_template('register.html', form=form)
  users = select("SELECT * FROM users WHERE email = %s", (form.email.data,))
  if users:
    return render_template(
      'error.html',
      message="An account with that email already exists!",
    )
  password = form.password.data.encode('ascii')
  salt = urandom(6)
  pw_hash = sha256(password + salt).hexdigest()
  hexlified = binascii.hexlify(salt)
  rows = select(
    "INSERT INTO users (email, name, hash, salt) VALUES(%s, %s, %s, %s) "
    "RETURNING *",
    (form.email.data, form.name.data, pw_hash, hexlified),
  )
  if not rows:
    return render_template(
      'error.html',
      message="Database error :(",
    )
  login_user(User(rows[0]), remember=True)
  return redirect(url_for('home.home'))
Пример #5
0
def home():
  form = FilterForm(request.form)
  topic_ids = []
  if request.method == 'POST' and form.validate():
    topics = re.compile(r'#([a-zA-Z0-9_-]+)\s*').findall(form.topics.data)
    if topics:
      topic_ids = topic_strings_to_ids(topics)
  if not topic_ids:
    posts = select(
      "SELECT p.*, u.name FROM posts p LEFT JOIN users u ON u.id = p.user"
    )
  else:
    in_clause = ','.join(('%s',) * len(topic_ids))
    posts = select(
      'SELECT p.*, u.name FROM posts p '
      'LEFT JOIN users u ON u.id = p.user '
      'INNER JOIN tags t ON t."from" = p.id AND t."to" IN (%s)' % in_clause,
      topic_ids,
    )
  parsed = [parse_post(post) for post in posts]
  return render_template(
    'home.html',
    posts=parsed,
    user=current_user,
    form=form,
  )
Пример #6
0
def compose():
    form = ComposeForm(request.form)
    if request.method == 'GET' or not form.validate():
        return render_template('compose.html', form=form, user=current_user)
    # First, get the topics
    topics = re.compile(r'#([a-zA-Z0-9_-]+)\s*').findall(form.topics.data)
    topic_ids = []
    if topics:
        topic_ids = topic_strings_to_ids(topics)
    if len(topic_ids) != len(topics):
        return render_template(
            'error.html',
            message="Database error :(",
        )
    # Next, create the post
    rows = select(
        'INSERT INTO posts (title, body, "user") VALUES(%s, %s, %s) RETURNING *',
        (form.title.data, form.body.data, current_user.get_id()),
    )
    if not rows:
        return render_template(
            'error.html',
            message="Database error :(",
        )
    post_id = rows[0]["id"]
    # Finally, create the topic associations
    if topic_ids:
        values_clause = ','.join(('(%s, %s)', ) * len(topic_ids))
        values = sum([(post_id, topic_id) for topic_id in topic_ids], ())
        select(
            'INSERT INTO tags("from", "to") VALUES %s RETURNING *' %
            values_clause,
            values,
        )
    return redirect(url_for('post.post', post=post_id))
Пример #7
0
def post(post):
  posts = select(
    'SELECT p.*, u.name FROM posts p '
    'LEFT JOIN users u ON u.id = p.user '
    'WHERE p.id = %s',
    (post,)
  )
  if not posts:
    return render_template(
      'error.html',
      message="Could not find post!",
      user=current_user,
    )
  topics = select(
    'SELECT "to"."name" FROM tags ta '
    'LEFT JOIN topics "to" ON "to"."id" = ta.to '
    'WHERE ta.from = %s',
    (posts[0]["id"],)
  )
  topics = [topic["name"] for topic in topics]
  post = parse_post(posts[0])
  return render_template(
    'post.html',
    post=post,
    user=current_user,
    topics=topics,
  )
Пример #8
0
def main():

	print(""" 
		WELCOME TO STUDENTS DATABASE
		############################
		Select Operation :
		(1) for create Table
		(2) for Add Record
		(3) for Show Records
		(4) for Delete Records
		(5) for Records Selection
		""")
	operation = input("Enter your Choice : ")
	if operation == "2":
		database.add_record()
	elif operation == "3":
		database.show_all()
	elif operation == "4":
		database.delete_one(id)
	elif operation == "5":
		database.select()
	elif operation == "1":

		print("Please Contact DataBase Admonistrator for this Operation")
	else:
		print("Try again !!")
Пример #9
0
def topic_strings_to_ids(topics):
    # First, see if they exist
    in_clause = ','.join(('%s', ) * len(topics))
    print in_clause
    results = select(
        'SELECT * FROM topics WHERE name IN (%s)' % in_clause,
        topics,
    )
    # Figure out which topics already exist
    ids = []
    need_creation = []
    for topic in topics:
        found = False
        for result in results:
            if topic == result["name"]:
                ids.append(result["id"])
                found = True
                break
        if not found:
            need_creation.append(topic)
    if not need_creation:
        return ids
    values_clause = ','.join(('(%s)', ) * len(need_creation))
    creation = select(
        'INSERT INTO topics(name) VALUES %s RETURNING *' % values_clause,
        need_creation,
    )
    for row in creation:
        ids.append(row["id"])
    return ids
Пример #10
0
 def globals(*tags):
     '''Iterate through all of the specified global `tags` within the database using the cache.'''
     iterable = db.select(Or=tags) if tags else db.select()
     for ea, res in iterable:
         ui.navigation.auto(ea)
         if res: yield ea, res
     return
Пример #11
0
 def globals(*tags):
     '''Iterate through all of the specified global `tags` within the database using the cache.'''
     iterable = db.select(Or=tags) if tags else db.select()
     for ea, res in iterable:
         ui.navigation.auto(ea)
         if res: yield ea, res
     return
Пример #12
0
def home():
    form = FilterForm(request.form)
    topic_ids = []
    if request.method == 'POST' and form.validate():
        topics = re.compile(r'#([a-zA-Z0-9_-]+)\s*').findall(form.topics.data)
        if topics:
            topic_ids = topic_strings_to_ids(topics)
    if not topic_ids:
        posts = select(
            "SELECT p.*, u.name FROM posts p LEFT JOIN users u ON u.id = p.user"
        )
    else:
        in_clause = ','.join(('%s', ) * len(topic_ids))
        posts = select(
            'SELECT p.*, u.name FROM posts p '
            'LEFT JOIN users u ON u.id = p.user '
            'INNER JOIN tags t ON t."from" = p.id AND t."to" IN (%s)' %
            in_clause,
            topic_ids,
        )
    parsed = [parse_post(post) for post in posts]
    return render_template(
        'home.html',
        posts=parsed,
        user=current_user,
        form=form,
    )
Пример #13
0
def upgrade_fec():
    if "submit" in request.form:
        q = "select * from facilities"
        res = db.select(q)
        print(len(res))
        for row in res:
            print(row)
            fecility = request.form['feci' + str(row['fec_id'])]
            fec_id = row['fec_id']
            log_id = session['login_data']['login_id']
            q = "SELECT ins_id FROM `institution` WHERE login_id='%s'" % log_id
            ins_id = db.select(q)[0]['ins_id']
            r = "select * from insti_feci WHERE ins_id='%s' and fec_id='%s'" % (
                ins_id, fec_id)
            res1 = db.select(r)
            if (len(res1) > 0):
                q = "UPDATE insti_feci SET status='%s' WHERE ins_id='%s' and fec_id='%s'" % (
                    fecility, ins_id, fec_id)
                db.update(q)
            else:
                q = "insert into insti_feci(ins_id,fec_id,status) values('%s','%s','%s')" % (
                    ins_id, fec_id, fecility)
                db.insert(q)
        return redirect(url_for('grade'))
    q = "select * from facilities"
    res = db.select(q)

    return render_template('institution/upgrade_fec.html', data=res)
Пример #14
0
def grade():
    log_id = session['login_data']['login_id']
    q = "SELECT ins_id FROM `institution` WHERE login_id = '%s'" % (log_id)
    res = db.select(q)
    print(res)
    q = "SELECT SUM*100/(SELECT COUNT(fec_id)FROM facilities) as rating FROM(SELECT COUNT(fec_id)as sum from insti_feci WHERE ins_id = '%s' AND(STATUS='yes' OR STATUS = 'not applicable'))tbl1" % (
        res[0]['ins_id'])

    res1 = db.select(q)
    print(res1)
    if (res1[0]['rating'] > 80):
        r = "update institution set grade='A' where ins_id='%s'" % (
            res[0]['ins_id'])
        db.insert(r)
    elif (res1[0]['rating'] > 60):
        r = "update institution set grade='B' where ins_id='%s'" % (
            res[0]['ins_id'])
        db.insert(r)
    elif (res1[0]['rating'] > 40):
        r = "update institution set grade='C' where ins_id='%s'" % (
            res[0]['ins_id'])
        db.insert(r)
    elif (res1[0]['rating'] > 20):
        r = "update institution set grade='D' where ins_id='%s'" % (
            res[0]['ins_id'])
        db.insert(r)
    else:
        r = "update institution set grade='E' where ins_id='%s'" % (
            res[0]['ins_id'])
        db.insert(r)

    q = db.select("select * from institution where login_id='%s'" % (log_id))

    return render_template('institution/grade.html', data=q)
Пример #15
0
def view_bookings(username):
    print('View your Bookings\n', ('-' * 30))
    bookings = database.select("SELECT * FROM bookings WHERE username = '******' AND total = 0 ORDER BY date DESC")

    if bookings:
        booking_count = 1
        for x in bookings:
            item_name = database.select("SELECT name FROM tools WHERE id = '" +
                                        str(x[1]) + "'")
            print(
                str(booking_count) + '. ' + item_name[0][0] + '  -----  ' +
                str(x[3]) + '  -----  ' + str(x[4]))
            booking_count += 1
        wrong = 1
        while wrong:
            choice = input('Enter any number to view more details: ')
            if str.isdigit(choice):
                if int(choice) < len(bookings) + 1:
                    wrong = 0
                    view(bookings[int(choice) - 1][0], str(x[1]))
                else:
                    print(
                        'Invalid Response! Try again with any number shown above'
                    )
            else:
                print('Type in a digit! Try again with any number shown above')
    else:
        print('No Bookings Yet!')
Пример #16
0
def view(booking_id, tool_id):
    print('View more details about your Booking\n', ('-' * 30))
    item = database.select("SELECT * FROM tools WHERE id = " + str(tool_id))
    # print(item)
    print((item[0][1]), '\nDescription: ', (item[0][2]), '\n', ('-' * 30))
    print('Full Day Rate: $', (item[0][3]), '\nHalf Day Rate: $', (item[0][4]))
    print('Status: ', (item[0][5]))
    booking = database.select("SELECT * FROM bookings WHERE id = " +
                              str(booking_id))
    date = datetime.datetime.now()
    cdate = datetime.date(int(date.year), int(date.month), int(date.day))
    print('Booked On: ', (booking[0][3]))
    datediff = days_between(booking[0][3], cdate)
    if datediff == 0:
        total_charge = item[0][4]
    elif datediff < 4:
        total_charge = datediff * item[0][3]
    else:
        total_charge = 3 * item[0][3]
        total_charge += (datediff - 3) * item[0][3] * 2
    print('Hire Charges: $', total_charge)
    if str.lower(booking[0][4]) == 'collect':
        print('Collection Charge: $0')
    else:
        total_charge += 5
        print('Drop Off Charge: $5')
    print('Total Charge: ', total_charge)
    decision = input('Do you want to return this item?  (y/n)')
    if str.lower(decision) == 'y':
        decision2 = input('Enter mode of return: (Store/Pick-Up)')
        decision3 = input(
            'What is the current condition of the tool? (Good/Damaged)')
        if decision3 == '' or str.lower(decision3) == 'good':
            if decision2 == '' or str.lower(decision2) == 'store':
                sql = "UPDATE bookings SET total = " + str(total_charge) + ", return_condition = 'good' WHERE id = '" \
                      + str(booking[0][0]) + "'"
            else:
                total_charge += 5
                sql = "UPDATE bookings SET total = '" + str(total_charge) + "', return_mode = '" \
                      + decision2 + "', return_condition = 'good' WHERE id = '" + str(booking[0][0]) + "'"
            sql2 = database.insert(
                "UPDATE tools SET status = 'available', t_condition = 'good' WHERE id = '"
                + str(tool_id) + "'")
        else:
            if decision2 == '' or str.lower(decision2) == 'store':
                sql = "UPDATE bookings SET total = " + str(total_charge) + ", return_condition = '" \
                      + decision3 + "' WHERE id = '" \
                      + str(booking[0][0]) + "'"
            else:
                total_charge += 5
                sql = "UPDATE bookings SET total = '" + str(total_charge) + "', return_mode = '" \
                      + decision2 + "', return_condition = '" + decision3 + "' WHERE id = '" + str(booking[0][0]) + "'"
            sql2 = database.insert(
                "UPDATE tools SET status = 'available', t_condition = '" +
                decision3 + "' WHERE id = '" + str(tool_id) + "'")

        database.insert(sql)
        database.insert(sql2)
        print('Return Registered\n', ('-' * 30))
Пример #17
0
def sentmail():

    login_id = session['login_id']
    q = db.select("select f_name from users where login_id = '%s' " %
                  (login_id))[0]['f_name']
    q1 = db.select("select email from users where login_id = '%s' " %
                   (login_id))[0]['email']
    res = db.select(
        "select * from mail where f_id=(select email from users where login_id='%s')"
        % login_id)

    return render_template('user_app/sentmail.html', emails=res, data=q)
Пример #18
0
async def byoc_stats(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't submit a challenge in public channels..."
    ):
        return

    msg = ''
    with db.db_session:
        user = db.User.get(name=username(ctx))
        team_challs = list(
            db.select(c for c in db.Challenge
                      if c.author in db.getTeammates(user)))

        # num solves per challenge
        stats = []
        for chall in team_challs:
            num_solves = list(
                db.select(s for s in db.Solve if s.challenge == chall))

            chall_rewards = sum(
                db.select(
                    sum(t.value) for t in db.Transaction
                    if t.type == "byoc reward"
                    and t.recipient in db.getTeammates(user)
                    and t.challenge == chall).without_distinct())

            line = [
                chall.id, chall.title,
                len(num_solves), chall.author.name, chall_rewards
            ]

            stats.append(line)
        stats.insert(0, ['Chall ID', 'Title', '# Solves', 'Author', 'Payout'])

        table = GithubFlavoredMarkdownTable(stats)

        # team total byoc rewards sum
        total_byoc_rewards = sum(
            db.select(
                sum(t.value) for t in db.Transaction if t.type == "byoc reward"
                and t.recipient in db.getTeammates(user)))

    await ctx.send(
        f"Your stats ```{table.table}```\n**Team Total BYOC Rewards:** `{total_byoc_rewards}` points"
    )
Пример #19
0
def user_home():

    mid = []

    login_id = session['login_id']
    q = db.select("select f_name from users where login_id = '%s' " %
                  (login_id))[0]['f_name']
    q1 = db.select("select email from users where login_id = '%s' " %
                   (login_id))[0]['email']
    res = db.select(
        "select * from mail where t_id=(select email from users where login_id='%s')"
        % login_id)

    return render_template('user_app/mailbox.html', emails=res, data=q)
Пример #20
0
def group_image_files() -> dict:
    """
    Function group image files to dict with key - path, value - images in this path

    :return: Dict with path's and files
                {
                    <path name>: [
                        (<filename>, <image ID>),
                        (<filename>, <image ID>),
                    ],
                    <path name>: [
                        (<filename>, <image ID>),
                        (<filename>, <image ID>),
                    ]
                }
    """
    result = {}
    try:
        all_images_paths = Image.group_images_paths()
        for path in all_images_paths:
            path_files = select((image.image_name, image.id) for image in Image
                                if image.image_path == path)[:]
            result.update({path: path_files})
    except Exception:
        logger.critical(traceback.format_exc())
    finally:
        return result
Пример #21
0
def get_image_duplicates(image_id: int,
                         similarity_threshold: float) -> [(Image, float)]:
    """
    Return list of Image-objects - duplicates of certain image

    :param image_id: ID of image to search it's duplicates
    :param similarity_threshold: Similarity threshold to images filtering

    :return: List of Images-objects and similarity param
    """
    # find image duplicates pairs which contains `image_id`
    duplicates = select(
        duplicate for duplicate in ImageDuplicates
        if (duplicate.image_src_id == image_id
            or duplicate.image_dup.id == image_id)
        and duplicate.images_similarity > similarity_threshold).sort_by(
            desc(ImageDuplicates.images_similarity))[:]

    # filter duplicates pairs and get only new(image!=src_image) images from pair
    duplicates_images = [(
        duplicate.image_src_id
        if duplicate.image_src_id != image_id else duplicate.image_dup.id,
        duplicate.images_similarity,
    ) for duplicate in duplicates]

    return [(Image[img_id], similarity)
            for img_id, similarity in duplicates_images]
Пример #22
0
def get_user(userid):
  """Given a user ID, this function fetches that user object from the database.
  The caller will handle the authentication by looking at the hash."""
  users = select("SELECT * FROM users WHERE id = %s", (int(userid),))
  if not users:
    return None
  return User(users[0])
Пример #23
0
 def subs(self):
     """dumps time that a flag was submitted. useful to prove who submitted fastest? 
     """
     solves = list(db.select((s.time, s.flag.flag, s.user.name, s.value) for s in db.Solve))
     solves.insert(0, ['Time','Flag','User','Value'])
     table  = mdTable(solves)
     print(table.table)
Пример #24
0
def delete_wallet():
    sql = """SELECT my_list.name, value, volume, my_list.id, virtual_id FROM virtual_wallet
            LEFT JOIN my_list ON my_list.id = virtual_wallet.company_id"""
    results = database.select(sql)
    print()
    i = 1
    if results:
        for result in results:
            print("{i} - {n} : {p}€ {v}".format(i=i, n=result[0], p=result[1], v=result[2]))
            i += 1
        print("0 - Retour\n")
        action = input("Quelle action voulez-vous supprimer ?")
        action = int(action)
        if action == 0:
            wallet.virtual()
        if 0 < action <= len(results):
            action = results[action - 1]
            sql = "DELETE FROM virtual_wallet WHERE virtual_id={i}"\
                .format(i=action[4])
            request = database.delete(sql)
            if request == "delete":
                print("----- {n} ({vo}) -----\nValeur: {va}€ supprimé".format(n=action[0], vo=action[2], va=action[1]))
        else:
            print("Merci de rentrer une valeur valable")
            time.sleep(2)
            delete_wallet()
    else:
        print("Pas d'actions")
    time.sleep(2)
    wallet.submenu_virtual()
Пример #25
0
def view(_id):
    print('View more details\n', ('-' * 30))
    item = database.select("SELECT * FROM tools WHERE id = " + str(_id))
    print((item[0][1]), '\nDescription: ', (item[0][2]), '\n', ('-' * 30))
    print('Full Day Rate: $', (item[0][3]), '\nHalf Day Rate: $', (item[0][4]))
    print('Availability: ', (item[0][5]))
    print('Available Till: ', (item[0][6]))
    user = login.is_logged_in()
    if user:
        for x in user:
            username = x[0]
        decision = input('Do you want to book this tool?(y/n)')
        if str.lower(decision) == 'y':
            decision2 = input('Enter mode of collection: (Collect/Drop off)')

            date = datetime.datetime.now()
            bdate = str(date.year) + '-' + str(date.month) + '-' + str(
                date.day)
            if decision2 == '':
                sql = "INSERT INTO bookings (item_id, username, date) VALUES ('" \
                      + str(_id) + "', '" + username + "', '" + bdate + "')"
            else:
                sql = "INSERT INTO bookings (item_id, username, date, mode) VALUES ('" \
                      + str(_id) + "', '" + username + "', '" + bdate + "', '" + decision2 + "')"
            sql2 = database.insert(
                "UPDATE tools SET status = 'hired' WHERE id = '" + str(_id) +
                "'")
            database.insert(sql)
            database.insert(sql2)
            print('Order Executed\n', ('-' * 30))
        login.logged_user(username)
    else:
        print('Log in to book this item')
Пример #26
0
def fetchimg(url):
    global CLURL
    try:
        imgid = re.search('\/(\d+).html$', url).group(1)
        result = database.select(['*'], [['url', '=', url]], 't_caoliu')
        urlinfo = result[3]
        status = urlinfo['status'][0]
        if status[0] == '1' or status[1] == 'P':
            return
        database.execute("update t_caoliu set status = '%s' where url='%s'" %
                         ('0P' + status[2:], url))
        requesturl = CLURL + url
        asoup = yield from fetchcontent(requesturl)
        div = asoup.find('div', {'class': 'tpc_content do_not_catch'})
        for i in div.findAll('input', {'type': 'image'}):
            savepath = os.path.join(SAVEPATH, imgid)
            logger.info("save %s to %s" % (i.attrs['src'], savepath))
            try:
                os.mkdir(savepath)
            except FileExistsError:
                pass
            except Exception as e:
                raise e
            yield from asyncio.sleep(2)
            # asyncio.ensure_future(downimg(i.attrs['src'], savepath))
            yield from downimg(i.attrs['src'], savepath)
        database.execute("update t_caoliu set status = '%s' where url='%s'" %
                         ('1F' + status[2:], url))
    except:
        logger.error(traceback.format_exc())
        database.execute("update t_caoliu set status = '%s' where url = '%s'" %
                         ('0F' + status[2:], url))
    finally:
        pass
Пример #27
0
    def nextTab(self):
        self.saveProgressValid[self.tabWidget.currentIndex()] = True
        if self.saveProgressValid[0]is True and self.saveProgressValid[1] is True and self.saveProgressValid[2]is True:
            self.stackedWidget.setCurrentIndex(2)
            self.tabWidget.setCurrentIndex(0)

            database.update_count(self.user_id)
            count_results = database.get_count(self.user_id)
            count = count_results[0][0]
            if count % 3 == 1:
                for i in range(0, 3):

                    workout_counter = 0
                    for j in range (0,3):

                        workout_counter += 1

                        workout_session = WorkoutSession()

                        workout_session.workout_number = workout_counter
                        workout_session.day_number = count + i
                        workout_session.week_number = ((count - 1) / 3) + 1
                        workout_session.user_id = self.user_id

                        sql_statement = "SELECT Muscle_Group, Exercise from Workout_Session WHERE User_ID = %d AND Week_Number = 1 AND Workout_Number = %d AND Day_Number = %d" % \
                                       (self.user_id, workout_session.workout_number, i + 1)
                        results = database.select(sql_statement)

                        workout_session.muscle_group = results[0][0]
                        workout_session.exercise = results[0][1]
                        database.insert_workout_session(workout_session)

        elif self.tabWidget.currentIndex() is not 2:
            self.tabWidget.setCurrentIndex(self.tabWidget.currentIndex()+1)
Пример #28
0
    def __init__(self, bot):
        self.bot = bot
        conn = create_connection('raid_db')
        if conn:
            logger.info("RaidCog connected to raid database.")
            create_table(conn, 'raid')
            create_table(conn, 'player', columns=self.role_names)
            create_table(conn, 'assign')
        else:
            logger.error("RaidCog could not create database connection!")
        self.conn = conn
        self.raids = select(conn, 'raids', 'raid_id')
        logger.info("We have loaded {} raids in memory.".format(len(
            self.raids)))
        # Emojis
        host_guild = bot.get_guild(self.host_id)
        if not host_guild:
            host_guild = bot.guilds[0]
        logger.info("Using emoji from {0}.".format(host_guild))
        emojis = {}
        for emoji in host_guild.emojis:
            if emoji.name in self.role_names:
                emojis[emoji.name] = str(emoji)
        self.class_emojis_dict = emojis
        self.class_emojis = list(emojis.values())

        # Run background task
        self.background_task.start()
Пример #29
0
 async def cleanup(self, ctx):
     res = select(self.conn, 'Settings', ['guild_id', 'last_command'])
     current_time = datetime.datetime.now().timestamp()
     cutoff = 3600 * 24 * 90
     cutoff_time = current_time - cutoff
     active = 0
     inactive = 0
     deleted = 0
     for row in res:
         guild_id = row[0]
         last_command = row[1]
         guild = self.bot.get_guild(guild_id)
         if guild:
             if last_command and last_command > cutoff_time:
                 active += 1
             else:
                 inactive += 1
                 logger.info("Leaving guild {0}...".format(guild.name))
                 await guild.leave()
                 ## Don't immediately delete settings in case they rejoin.
         else:
             logger.info("We are no longer in {0}".format(guild_id))
             delete(self.conn, 'Settings', ['guild_id'], [guild_id])
             deleted += 1
     self.conn.commit()
     logger.info("Active guild count: {0}".format(active))
     logger.info("Inactive guild count: {0}".format(inactive))
     logger.info("Deleted guild count: {0}".format(deleted))
     await ctx.send("Active guild count: {0}".format(active))
     await ctx.send("Inactive guild count: {0}".format(inactive))
     await ctx.send("Deleted guild count: {0}".format(deleted))
Пример #30
0
def insti_reg():
    if "submit" in request.form:
        name = request.form['name']
        univer = request.form['uni_id']
        add = request.form['address']
        email = request.form['email']
        phone = request.form['phone']
        user = request.form['user']
        passw = request.form['pass']
        cpassw = request.form['cpass']

        if (passw == cpassw):
            loginid = db.insert(
                "insert into login(username,password,login_type) values('%s','%s','institution')"
                % (user, passw))
            print(loginid)
            r = "insert into institution(uni_id,clg_name,ins_address,email,phone,login_id) values('%s','%s','%s','%s','%s','%s')" % (
                univer, name, add, email, phone, loginid)
            db.insert(r)
            if (r > 0):
                flash('Institution Registration Completed')
                print("success")
                return render_template("public/login.html")
            else:
                print("failed" "")
                flash('Institution registration failed')
        else:
            flash('password and confirm password must be same')

    q = "select * from university"
    res = db.select(q)
    return render_template('public/insti_reg.html', university=res)
Пример #31
0
def subject():
    cor = session['course']
    if "submit" in request.form:
        q = "select * from subject where cou_id='%s'" % (cor)
        res = db.select(q)

        marks = []
        for row in res:

            name = 'mark' + str(row['sub_id'])
            marks.append(request.form[name])

        return redirect(url_for('ability'))
    q = "select * from subject where cou_id='%s'" % (cor)
    res = db.select(q)
    return render_template('user/subject.html', data=res)
Пример #32
0
def cmp():
    login_id = session['login_id']
    q = db.select("select f_name from users where login_id = '%s' " %
                  (login_id))[0]['f_name']
    q1 = db.select("select email from users where login_id = '%s' " %
                   (login_id))[0]['email']

    if 'submit' in request.form:
        t_id = request.form['t_id']
        sub = request.form['sub']
        msg = request.form['msg']
        # lo="insert into mail_id(t_id,f_id,sub,msg)values('%s','%s','%s')"%(user,passw,features)
        q2 = "insert into mail(t_id,f_id,sub,msg)values('%s','%s','%s','%s')" % (
            t_id, q1, sub, msg)
        res = db.insert(q2)
        return redirect(url_for('user_home'))
Пример #33
0
def register_action():
    data = {}
    if 'register' in request.form:
        fnam = request.form['fname']
        lnam = request.form['lname']
        ag = request.form['age']
        d = request.form['dob']
        plac = request.form['place']
        ci = request.form['city']
        st = request.form['state']
        eml = request.form['email']
        phn = request.form['phone']
        user = request.form['user']
        passw = request.form['pass']
        features = request.form['features']
        s = "select username,password from user_login where username='******'" % (
            user)
        sel = db.select(s)

        if (len(sel) == 1):
            data['status'] = 'Username Already Exists'
        else:
            lo = "insert into user_login(username,password,features,login_type)values('%s','%s','%s','user')" % (
                user, passw, features)
            log = db.insert(lo)
            print(log)
            q = "insert into users(login_id,f_name,l_name,age,dob,place,city,state,email,phone_no)values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (
                log, fnam, lnam, ag, d, plac, ci, st, eml, phn)
            res = db.insert(q)
            data['status'] = 'Successfully Registered'
            data['data'] = sel
            train()

    return demjson.encode(data)
Пример #34
0
def view_user():

    if "delete" in request.args:
        id = request.args['id']
        res = db.delete("delete from user where login _id='%s'" % (id))
        res1 = db.delete("delete from login where login_id='%s'" % (id))
        print(res)
        if (res > 0):
            res1 = db.select("select * from user")
            return render_template('admin/view_user.html', data=res1)

    if "login_id" in session['login_data']:
        res = db.select("select * from user")
        return render_template("admin/view_user.html", data=res)
    else:
        return redirect(url_for('public/login'))
Пример #35
0
 async def select(self, button: discord.ui.Button,
                  interaction: discord.Interaction):
     if not await self.raid_cog.has_raid_permission(
             interaction.user, interaction.guild, interaction.message.id):
         perm_msg = _(
             "You do not have permission to change the raid settings.")
         await interaction.response.send_message(perm_msg, ephemeral=True)
         return
     raid_id = interaction.message.id
     available = select(self.conn, 'Players', ['player_id, byname'],
                        ['raid_id', 'unavailable'], [raid_id, False])
     if not available:
         msg = _("There are no players to assign for this raid!")
         await interaction.response.send_message(msg, ephemeral=True)
         return
     msg = _("Please first select the player. The roster is updated when a class is selected. "
             "You can select a slot manually or leave it on automatic.\n") \
         + _("(This selection message is ephemeral and will cease to work after 60s without interaction.)")
     view = SelectView(self.raid_cog, raid_id)
     await interaction.response.send_message(msg, view=view, ephemeral=True)
     roster = select_one(self.conn, 'Raids', ['roster'], ['raid_id'],
                         [raid_id])
     if not roster:
         upsert(self.conn, 'Raids', ['roster'], [True], ['raid_id'],
                [raid_id])
Пример #36
0
def init(search_term):
    # it should return items somewhat like this\n1. Saw  $25\n2. Cutter  $34
    items = database.select(
        "SELECT * FROM tools WHERE name LIKE '%" + search_term +
        "%' AND status = 'available' AND t_condition = 'good'")
    if items:
        item_count = 1
        for x in items:
            print(
                str(item_count) + '. ' + x[1] + '  ---  $' + str(x[3]) + '/$' +
                str(x[4]))
            item_count += 1
        wrong = 1
        while wrong:
            choice = input('Enter any number to view more details: ')
            if str.isdigit(choice):
                if int(choice) < len(items) + 1:
                    wrong = 0
                    view(items[int(choice) - 1][0])
                else:
                    print(
                        'Invalid Response! Try again with any number shown above'
                    )
            else:
                print('Type in a digit! Try again with any number shown above')
    else:
        print('No Results! Do an empty search to view all items')
Пример #37
0
def recovermarks():
    '''Utilizing any tag information found in the database, recreate all the database marks.'''
    # collect
    result = []
    for fn,l in database.select('marks'):
        m = set( (l['marks']) if hasattr(l['marks'],'__iter__') else [int(x,16) for x in l['marks'].split(',')] if type(l['marks']) is str else [l['marks']])
        res = [(ea,d['mark']) for ea,d in function.select(fn,'mark')]
        if m != set(a for a,_ in res):
            logging.warning("%x: ignoring cached version of marks due to being out-of-sync with real values : %r : %r", fn, map(hex,m), map(hex,set(a for a,_ in res)))
        result.extend(res)
    result.sort(cmp=lambda x,y: cmp(x[1],y[1]))

    # discovered marks versus database marks
    result = dict(result)
    current = {ea:descr for ea,descr in database.marks()}

    # create tags
    for x,y in result.items():
        if (x not in current) or (current[x] != result[x]):
            if current[x] != result[x]:
                logging.info('%x: database tag is newer than mark description : %r', x, result[x])
            database.mark(x, y)
            continue
        logging.warning('%x: skipping already existing mark : %r', x, current[x])

    # marks that aren't reachable in the database
    for ea in set(current.viewkeys()).difference(result.viewkeys()):
        logging.warning('%x: unreachable mark (global) : %r', ea, current[ea])

    # color them
    colormarks()
Пример #38
0
    def __init__(self, bot):
        self.bot = bot
        self.conn = self.bot.conn
        self.role_names = self.bot.role_names
        self.time_cog = bot.get_cog('TimeCog')
        self.calendar_cog = bot.get_cog('CalendarCog')

        create_table(self.conn, 'raid')
        create_table(self.conn, 'player')
        create_table(self.conn, 'assign')

        raids = select(self.conn, 'Raids', ['raid_id'])
        self.raids = [raid[0] for raid in raids]
        logger.info("We have loaded {} raids in memory.".format(len(
            self.raids)))
        # Emojis
        host_guild = bot.get_guild(bot.host_id)
        if not host_guild:
            # Use first guild as host
            host_guild = bot.guilds[0]
        logger.info("Using emoji from {0}.".format(host_guild))
        self.class_emojis = [
            emoji for emoji in host_guild.emojis
            if emoji.name in self.role_names
        ]
        self.class_emojis_dict = {
            emoji.name: str(emoji)
            for emoji in self.class_emojis
        }

        # Run background task
        self.background_task.start()

        # Add raid view
        self.bot.add_view(RaidView(self))
def test(f_discretization=10, e_discretization=30, indep=False, selection=None, subset=None, corpus=None, smoothing=None, sensitivity=5, segmentation='reasonable'):
    if not selection:
        selection = (db.select())
    score = db.getScore1(selection)
    if not corpus:
        (f, e, m) = tools.chooseFeatures()
    else:
        (f, e, m) = tools.loadFeatures(corpus)
    if m['version'] != sf.version:
        print("Scorefeatures versions don't match! Corpus version: {0} Scorefeatures version: {1}".format(m['version'], sf.version))
        exit(0)
    if not subset:
        # Select a subset by hand
        subset = selectSubset(m['featureset'])
    print('\n\tPerforming {0}'.format(selection))
    print('\tFeatures version: {0}'.format(m['version']))
    print('\tFeatureset used: [', end=' ')
    print(', '.join([m['featureset'][i] for i in subset]), end=' ')
    print(']')
    print('\tScorefeatures discretization: {0}\n\tExpression discretization: {1}'.format(f_discretization, e_discretization))
    print('\tSensitivity: {0}'.format(sensitivity))
    print('\tSmoothing: {0}'.format(smoothing))
    print('\tCorpus: {0}\n'.format(corpus))
    if indep:
        hmm = HMM_indep(2, smoothing)
    else:
        hmm = HMM(2, smoothing)

    trainHMM(hmm, f, e, f_discretization, e_discretization, subset=subset, ignore=selection, sensitivity=sensitivity)
    #trainHMM(hmm, f, e, f_discretization, e_discretization, subset=subset)
    hmm.storeInfo('hmm2.txt')
    print("Loading score")
    melodyscore = Score(score).melody()
    melody = tools.parseScore(melodyscore)
    # Segmentate the the score
    print("Analysing score")
    if segmentation == 'reasonable':
        print('Using reasonable segmentation')
        onset = structure.reasonableSegmentation(melody)
    elif segmentation == 'new':
        print('Using new segmentation')
        onset = structure.newSegmentation(melody)
    elif segmentation == 'notelevel':
        print('Using notelevel segmentation')
        onset = structure.noteLevel(melody)

    #onset = structure.groupings(structure.list_to_tree(structure.first_order_tree(structure.onset, melody, 0.1)), 1)
    #namelist = []
    #for group in onset:
    #  namelist.append([leaf.name() for leaf in group])
    #print namelist

    (p, expression) = render(melodyscore, onset, hmm, f_discretization, e_discretization, subset, sensitivity=sensitivity)

    print("Done, resulting expression(with a probability of {1}): {0}".format(expression, p))

    performance = perform.perform(score, melodyscore, onset, expression, converter=melody)
    playPerformance(selection, performance, expression, onset, '{0}_{1}_on_{2}_discret_{3}-{4}_smoothing_{5}'.format(\
        selection[0], selection[1], corpus, f_discretization, e_discretization, smoothing))
Пример #40
0
  def list():
    results = []
    with select() as cursor:
      cursor.execute('''
        SELECT * FROM `comments` 
          ORDER BY `comment_id` DESC
      ''')
      records = Database.moulding_dataset()
      for record in records:
        results.append(Comment(**record)) 

    return results
Пример #41
0
def topic_strings_to_ids(topics):
  # First, see if they exist
  in_clause = ','.join(('%s',) * len(topics))
  results = select(
    'SELECT * FROM topics WHERE name IN (%s)' % in_clause,
    topics,
  ) 
  # Figure out which topics already exist
  ids = []
  for topic in topics:
    for result in results:
      if topic == result["name"]:
        ids.append(result["id"])
        break
  return ids
Пример #42
0
def check(key=None):
    data = database.select(key)
    isc_ldap = ldap.ldifsearch(data[5])

    return bottle.template(
        'check',
        name_last=data[0],
        name_first=data[1],
        kana_last=data[2],
        kana_first=data[3],
        club_account=data[4],
        isc_account=data[5],
        displayName=isc_ldap['displayName'],
        gecos=isc_ldap['gecos'],
        employeeNumber=isc_ldap['employeeNumber'],
        mail=isc_ldap['mail']
    )
Пример #43
0
def recovermarks():
    """Walk through the tags made by ``colormarks`` and re-create the marks that were found.

    This is useful if any marks were accidentally deleted and can be used for
    recovering them as long as they were initally tagged properly.
    """
    # collect
    result = []
    for fn, l in database.select('marks'):
        m = set( (l['marks']) if hasattr(l['marks'], '__iter__') else [int(x, 16) for x in l['marks'].split(',')] if type(l['marks']) is str else [l['marks']])
        res = [(ea, d['mark']) for ea, d in func.select(fn, 'mark')]
        if m != { a for a, _ in res }:
            logging.warning("{:s} : Ignoring the function tag \"{:s}\" for function {:#x} due to its value being out-of-sync with the contents values ({!s} <> {!s}).".format('.'.join((__name__, 'recovermarks')), fn, builtins.map(hex, m), builtins.map(hex, set(a for a, _ in res))))
        result.extend(res)
    result.sort(cmp=lambda x, y: cmp(x[1], y[1]))

    # discovered marks versus database marks
    result = dict(result)
    current = {ea : descr for ea, descr in database.marks()}

    # create tags
    for x, y in result.items():
        if x in current:
            logging.warning("{:#x}: skipping already existing mark : {!r}".format(x, current[x]))
            continue

        # x not in current
        if x not in current:
            logging.info("{:#x}: adding missing mark due to tag : {!r}".format(x, result[x]))
        elif current[x] != result[x]:
            logging.info("{:#x}: database tag is different than mark description : {!r}".format(x, result[x]))
        else:
            assert current[x] == result[x]
        database.mark(x, y)

    # marks that aren't reachable in the database
    for ea in set(current.viewkeys()).difference(result.viewkeys()):
        logging.warning("{:#x}: unreachable mark (global) : {!r}".format(ea, current[ea]))

    # color them
    colormarks()
Пример #44
0
    def login_clicked(self):

        user_name = str(self.lineEdit.text())
        password = str(self.lineEdit_2.text())

        if (user_name.isspace() or password.isspace()) or (user_name == "" or password == ""):
            self.label_validation.setText("Both fields required")
            return

        sql_statement = "select * from User where User_Name = '%s' and Password = '******'" % (user_name, password)

        results = database.select(sql_statement)

        if len(results) == 0:

            self.label_validation.setText("No user found.")

            return
        
        self.user_id = results[0][0]
        self.stackedWidget.setCurrentIndex(2)
Пример #45
0
def run():
    import database as db
    selection = db.select()
    print(">>> Extracting deviations")
    deviations = db.getDeviation1(selection)
    print(">>> Loading score")
    score = db.getScorePath1(selection)
    print(">>> Loading alignment")
    alignment = Alignment(score, deviations)
    alignment.store("alignments/a1")
    print(">>> Generating performance")
    performance = alignment.performance()
    performance.exportMidi('output/generated.mid')
    #for n in performance[0:20]:
    #  print n.info()


    #output = open('temp.txt', 'w')
    #for n in nlist:
    #  output.write(str(n) + '\n')
    #output.close()
    import sequencer as seq
    sequencer = seq.Sequencer()
    sequencer.play(performance)
Пример #46
0
#!/usr/bin/env python
#-*- coding: utf8 -*-

from dialog import *
import database as db
import dbconf
import re
import sys
import os

if os.environ.has_key('SUDO_USER'):
        user =  os.environ['SUDO_USER']
else:
        user = '******'

userfromdb = db.select('users', where="login = '******'" % user)
if len(userfromdb) == 0:
	print 'Votre utilisateur n\'a pas été autorisé à avoir un site.'
	print 'Merci de contacter l\'administrateur.'
	sys.exit()

id_user = list(userfromdb)[0].id

while True:
	domain = text('Nom de domaine du site :')
	if re.match(r'^([a-zA-Z0-9_\-]+\.)+(fr|cc|com|org|net|info|name|be|eu)$', domain):
		break

domains = db.select('domains', where="name = '%s'" % domain)

if len(domains) == 0:
Пример #47
0
def waiting(club_account):
    if database.select(club_account):
        return True
    else:
        return False
Пример #48
0
			return self.email.split('@')[1]
	
	def get_username(self):
		if self.email:
			return self.email.split('@')[0]

	def is_well_formatted(self):
		return re.match(r'''^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$''', self.email)


if os.environ.has_key('SUDO_USER'):
        user =  os.environ['SUDO_USER']
else:
        user = '******'

userfromdb = db.select('users', where="login = '******'" % user)
if len(userfromdb) == 0:
	print 'Votre utilisateur n\'a pas été autorisé à avoir un site.'
	print 'Merci de contacter l\'administrateur.'
	sys.exit()

id_user = list(userfromdb)[0].id

is_catchall = choices('Voulez vous créer un catch-all ?', dict(o=True, n=False), default='n')

print

if is_catchall:
	while True:
		email = text('Nom de domaine de l\'adresse :')
		if re.match(r'^([a-zA-Z0-9_\-]+\.)+(fr|com|be|org|net|info|name)$', email):
Пример #49
0
def valid_dbname(text):
	if len(text) >= 1 and len(text) < 30:
		for l in text:
			if not l in _GOOD_LETTERS:
				return False
		return True
	else:
		return False
				

if os.environ.has_key('SUDO_USER'):
        user =  os.environ['SUDO_USER']
else:
        user = '******'

userfromdb = db.select('users', where="login = '******'" % user)
if len(userfromdb) == 0:
	print 'Votre utilisateur n\'a pas été autorisé à avoir un site.'
	print 'Merci de contacter l\'administrateur.'
	sys.exit()

id_user = list(userfromdb)[0].id

while True:
	dbname = text('Suffixe du nom de la base de donnée :')
	if valid_dbname(dbname): break
	else:
		print 'Le suffixe doit utiliser les caractères `a-z A-Z 0-9 _ et -`, et'
		print 'ne doit pas dépasser les 30 caractères.'

dbs = db.select('bases', where="name = '%s' AND id_users='%s'" % (dbname, id_user))
Пример #50
0
#-*- coding: utf8 -*-

from dialog import *
import database as db
import dbconf
import re
import sys
import os
from md5 import md5

if os.environ.has_key('SUDO_USER'):
        user =  os.environ['SUDO_USER']
else:
        user = '******'

userfromdb = db.select('users', where="login = '******'" % user)
if len(userfromdb) == 0:
	print 'Votre utilisateur n\'a pas été autorisé à avoir un site.'
	print 'Merci de contacter l\'administrateur.'
	sys.exit()

id_user = list(userfromdb)[0].id

while True:
	email = text('Adresse email à ajouter :')
	if not re.match(r'''^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$''', email):
		print "Ça ne ressemble pas à une adresse email, veuillez réessayer"
	else:
		break

(username, domain) = email.split('@')
Пример #51
0
#!/usr/bin/env python
#-*- coding: utf8 -*-

from dialog import *
import database as db
import dbconf
import re
import sys
import os

if os.environ.has_key('SUDO_USER'):
        user =  os.environ['SUDO_USER']
else:
        user = '******'

userfromdb = db.select('users', where="login = '******'" % user)
if len(userfromdb) == 0:
	print 'Votre utilisateur n\'a pas été autorisé à utiliser cet outil.'
	print 'Merci de contacter l\'administrateur.'
	sys.exit()

id_user = list(userfromdb)[0].id

while True:
	domain = text('Nom de domaine du site :')
	if re.match(r'^([a-zA-Z0-9_\-]+\.)+(fr|com|org|net|info|name|be|eu)$', domain):
		break

domains = db.select('domains', where="name = '%s'" % domain)

if len(domains) == 0:
Пример #52
0
def noteLevel(notes):
    return [[n] for n in notes]


if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        l = [int(x) for x in sys.argv[1:]]
        print(relative_deltalist(test, l))
        print(second_order_tree(test, l, 0.0, deltalist_function=relative_deltalist))
        print(second_order_tree(test, l, 0.0))
        sys.exit(0)

    import database as db
    import tools
    w = db.select()
    score = Score(db.getScore1(w))
    melodyscore = score.melody()
    #melodyscore.show()
    melody = tools.parseScore(melodyscore, list(range(1, 9)))
    trees = [second_order_tree(onset, melody, 0.5), second_order_tree(pitch, melody, 0.0, ), first_order_tree(onset, melody, 0.0), first_order_tree(pitch, melody)]

    for tree in trees:
        print("Tree")
        print(tools.recursive_print(tree))


    for i in range(5):
        for j in range(len(trees)):
            groups = groupings(list_to_tree(trees[j]), i)
            avg_group = 0
Пример #53
0
import database as db
from alignment import *
from representation import *
from sequencer import *
from score import *
import tools

selection = db.select()
score = db.getScore1(selection)
notes = tools.parseScore(score)
seq = Sequencer()
seq.play(notes)
#s = Score(alignment.score, alignment)
Пример #54
0
    def openProgress(self):
        sql_statement = "select * from User where User_Id = %d" %self.user_id

        results = database.select(sql_statement)
        
        info = database.get_stat_info(self.user_id)
        
        day = float(results[0][8])
        self.progressBar.setValue((day / 18) * 100)
       
        workoutlist = []
        count = 1
        for workout in info:
            count = False
            if workoutlist:
                              
                for item in workoutlist:
                    
                    if item[0].exercise == workout.exercise:
                        count = True
                        item.append(workout)
                        break
                if count:
                    pass
                else:
                    exercise1 = []
                    exercise1.append(workout)
                    workoutlist.append(exercise1)
            else:
                exercise = []
                exercise.append(workout)
                workoutlist.append(exercise)
        
        
        self.tableWidget.setRowCount(len(workoutlist))
        self.tableWidget.setColumnCount(4)
        for item in range(len(workoutlist)):
            
            validate = True
            for work in workoutlist[item]:
                if work.weight != 1:
                    validate = False
            if validate:
                continue
            itemName = QtGui.QTableWidgetItem(workoutlist[item][0].exercise)
            self.tableWidget.setItem(item,0, itemName)
            max1 = min1 = workoutlist[item][0].weight
            reps = 0
            size = 0
            for work in workoutlist[item]:
                if work.weight == 1:
                    continue
                if work.weight < min1:
                    min1 = work.weight
                if max1 < work.weight:
                    max1 = work.weight
                reps += work.set_one
                reps += work.set_two
                reps += work.set_three
                size += 1
            finalReps = reps/(3*size)
            
            itemStartName = QtGui.QTableWidgetItem(str(min1))
            self.tableWidget.setItem(item,1, itemStartName)
            
            itemEndName = QtGui.QTableWidgetItem(str(max1))
            self.tableWidget.setItem(item,2, itemEndName)

            itemRepsName = QtGui.QTableWidgetItem(str(finalReps))
            self.tableWidget.setItem(item,3, itemRepsName)

        self.tableWidget.resizeColumnsToContents()
        self.stackedWidget.setCurrentIndex(5)
Пример #55
0
#-*- coding: utf8 -*-

from dialog import *
import database as db
import dbconf
import re
import sys
import os
from md5 import md5

if os.environ.has_key('SUDO_USER'):
        user =  os.environ['SUDO_USER']
else:
        user = '******'

userfromdb = db.select('users', where="login = '******'" % user)
if len(userfromdb) == 0:
	print 'Votre utilisateur n\'a pas été autorisé à avoir un site.'
	print 'Merci de contacter l\'administrateur.'
	sys.exit()

id_user = list(userfromdb)[0].id

while True:
	email = text('Adresse email à modifier :')
	if re.match(r'''^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$''', email):
		break

(username, domain) = email.split('@')

password = passwd('Nouveau mot de passe :')
Пример #56
0
def retrievedata(id):
	return [i for i, in select('sir_results', ('i',), {'id': id}, order=('t',))]
 segmentation = 'reasonable'
 if len(a) > 1:
     if a[1] == 'load':
         loadperformance()
         exit(0)
     elif a[1] == 'train':
         import train
         composers = input("Enter composers\n").split(" ")
         pianist = input("Enter pianist\n")
         if pianist == '': pianist = None
         set = train.trainset(composers, pianist)
         train.train(set)
         exit(0)
     elif a[1] == 'align':
         import train
         set = [db.select()]
         train.train(set)
         exit(0)
     elif a[1] == 'plotcorpus':
         plotCorpus()
         exit(0)
     elif a[1] == 'plot':
         (selection, expression) = tools.loadPerformance()
         if selection == None:
             selection = db.select()
         score = db.getScore1(selection)
         melodyscore = Score(score).melody()
         melody = tools.parseScore(melodyscore)
         segmentation = structure.reasonableSegmentation(melody)
         visualize(segmentation, expression)
         exit(0)
def country_list():
    return [c[0] for c in select('earsnet', ('country',), distinct=True)]
Пример #59
0
def getcountrylist():
    countries= select("earsnet", ["country"], distinct = True)
    countrylist=[]
    for country in countries:
        countrylist.append(country[0].decode('utf8'))
    return countrylist
Пример #60
0
	user = '******'

domains = db.query("""SELECT domains.id, domains.name, users.login
	FROM domains
	LEFT JOIN websites ON websites.id_domains=domains.id
	LEFT JOIN users ON websites.id_users=users.id""")

#print 'total %s' % len(domains)

for domain in domains:
	if domain.login == user:
		login = '******'
	else:
		login = domain.login
		
	mailboxes = len(db.select('mailboxes', where='domain_id = $domain.id', vars=locals()))
	mailaliases = len(db.select('mailaliases', where='domain_id = $domain.id', vars=locals()))

	if login or mailboxes or mailaliases:
		print '%s,' % domain.name,
	else:
		print domain.name,

	if login:
		print 'hébergé par %s' % login,
		if mailboxes or mailaliases:
			print 'avec',
	
	if mailboxes:
		print '%s boite(s)' % mailboxes,
		if mailaliases: