Example #1
0
async def add_forbidden_word(ctx, *arg):
    forbidden_word = " ".join(arg)

    con = mysql.connector.connect(**con_info)
    insert(con, "forbidden_words", ["forbidden_word_id"], [forbidden_word])
    insert(con, "users", ["user_id"], [ctx.message.author.id])
    existance = does_exist(con, "forbidden_words_users",
                           ["forbidden_word_id", "user_id"],
                           [forbidden_word, ctx.message.author.id])

    if not existance:
        forbidden_words_users_id = insert(
            con, "forbidden_words_users", ["forbidden_word_id", "user_id"],
            [forbidden_word, ctx.message.author.id])

        if forbidden_words_users_id != -1:
            await ctx.send(
                f"Hewwo! I added **{forbidden_word}** to your Forbidden Words!"
            )
        else:
            await ctx.send(
                f"Oh nyo! I couldn't add **{forbidden_word}** to your Forbidden Words"
            )
    else:
        await ctx.send(
            f"Baka! **{forbidden_word}** is already in your Forbidden Words!")

    con.close()
Example #2
0
def book_create():
    try:
        #content = request.get_json(force=True)
        book_title = request.json['book_title']
        uuid = request.json['uuid']
        publisher_id = request.json['publisher_id']
        author_ids = request.json['author_ids']
        category_ids = request.json['category_ids']

        query = '''INSERT INTO `books` (`book_title`, `uuid`, `publisher_id`)
                   VALUES (%s, %s, %s) 
                '''
        arguments = [book_title, uuid, publisher_id]
        book_id = insert_then_select_id(query, arguments)['result']['ID']

        # insert authors
        for ids in author_ids:
            query = '''INSERT INTO `book_author` (`book_id`, `author_id`) VALUES (%s, %s)'''
            arguments = [book_id, ids]
            insert(query, arguments)

        # insert category
        for ids in category_ids:
            query = '''INSERT INTO `book_category` (`book_id`, `category_id`) VALUES (%s, %s)'''
            arguments = [book_id, ids]
            insert(query, arguments)

        return jsonify({'result': 'success'})
    except Exception as ex:
        print({'result': ex})
        return jsonify({'result': 'failure'})
Example #3
0
def add_to_table(table_name, columns, values):
    logging.info(
        f'{str(datetime.datetime.now())}: Adding {table_name}: {values}')
    con = psycopg2.connect(DATABASE_URL, sslmode='require')
    for value in values:
        insert(con, table_name, columns, [value])
    con.close()
Example #4
0
def dir_create():
    try:
        parent_id = request.json['parent_id']
        name = request.json['name']
        dir_id = request.json['dir_id']

        query = '''INSERT INTO `dir` (name, dir_id, parent_id) VALUES (%s, %s, %s)'''
        arguments = [name, dir_id, parent_id]
        insert(query, arguments)
        return jsonify({'result': 'success'})
    except Exception as ex:
        print(ex)
        return jsonify({'result', 'failure'})
Example #5
0
async def on_member_join(member):
    channel = client.get_channel(WELCOME_CHANNEL_ID)
    url = "https://imgur.com/ANEL8c3"
    role = discord.utils.get(member.guild.roles, name="Refugee")

    con = mysql.connector.connect(**con_info)
    insert(con, "users", ["user_id"], [member.id])
    con.close()

    await member.add_roles(role)
    await channel.send(url)
    await channel.send(
        f'Irasshaimase, {member.mention}!\n\Pwease read the rules at <#{RULES_CHANNEL_ID}>'
    )
Example #6
0
async def on_member_join(member):
    try:
        channel = client.get_channel(WELCOME_CHANNEL_ID)
        url = "https://i.imgur.com/ANEL8c3.mp4"
        role = discord.utils.get(member.guild.roles, name="Refugee")

        con = mysql.connector.connect(**con_info)
        insert(con, "users", ["user_id"], [member.id])
        con.close()

        await member.add_roles(role)
        await channel.send(url)
        await channel.send(
            f'Iwasshaimase, {member.mention}!\nPwease wead da wules at <#{RULES_CHANNEL_ID}>'
        )
    except Exception as e:
        logging.info(f'{str(datetime.datetime.now())}: Added {member}: ')
Example #7
0
async def on_ready():
    channel = client.get_channel(CHANNEL_ID)
    logging.info(f'{str(datetime.datetime.now())}: Bot is ready')

    while True:
        logging.info(
            f'{str(datetime.datetime.now())}: Checking for new submissions: ')

        con = psycopg2.connect(DATABASE_URL, sslmode='require')

        all_subreddits = '+'.join([d[1] for d in query_all(con, 'subreddit')])
        all_keywords = [d[1] for d in query_all(con, 'keyword')]
        all_forbidden_words = [d[1] for d in query_all(con, 'forbidden_word')]

        logging.info(
            f'{str(datetime.datetime.now())}: Subreddits: {all_subreddits}')
        logging.info(
            f'{str(datetime.datetime.now())}: Keywords: {all_keywords}')
        logging.info(
            f'{str(datetime.datetime.now())}: Forbidden Words: {all_forbidden_words}'
        )
        logging.info(f'{str(datetime.datetime.now())}: Begin scraping')

        submissions = get_scraped_submissions(all_subreddits, all_keywords,
                                              all_forbidden_words)

        for submission in submissions:
            submission_does_exist = does_exist(con, 'submission', 'id',
                                               submission.id)

            if not submission_does_exist:
                logging.info(
                    f'{str(datetime.datetime.now())}: Found new submission: {submission.title[:100]}'
                )
                insert(
                    con, 'submission', ['id', 'title'],
                    [submission.id, submission.title[:100].replace("'", "")])
                await channel.send(
                    f'```{submission.title}```\n @everyone \n\n{submission.url}'
                )

        logging.info(f'{str(datetime.datetime.now())}: Finished scraping')

        # # Close the connection and sleep for 1 minute
        con.close()
        await asyncio.sleep(60)
Example #8
0
def get_all_department_add():
    try:
        dept_name = request.json['dept_name']
        dept_uuid = request.json['dept_uuid']

        query = "INSERT INTO `department`(`dept_name`, `dept_uuid`) VALUES (%s, %s)"
        result = insert(query, [dept_name, dept_uuid])
        return jsonify(result)
    except Exception:
        return jsonify({'result': 'failure'})
Example #9
0
def create():
    name = request.json['name']
    email = request.json['email']
    username = request.json['username']
    password = request.json['password']

    query = "INSERT INTO `user` (`name`, `email`, `username`, `password`,`joined_on`) VALUES (%s, %s, %s, %s, CURDATE())"
    arguments = [name, email, username, md5_hash(password)]

    return jsonify(insert(query, arguments))
Example #10
0
def publisher_create():
    try:
        name = request.json['name']
        uuid = request.json['uuid']

        query = '''INSERT INTO `publishers` (`name`, `uuid`) VALUES (%s, %s)'''
        arguments = [name, uuid]
        result = insert(query, arguments)
        return jsonify(result)
    except Exception:
        return jsonify({'result': 'failure'})
Example #11
0
def add_classes():
    try:
        class_name = request.json['class_name']
        class_uuid = request.json['class_uuid']

        query = "INSERT INTO `classes` (`class_name`, `class_uuid`) values (%s, %s)"
        arguments = [class_name, class_uuid]
        return jsonify(insert(query, arguments))
    except Exception as ex:
        print(ex)
        return jsonify({'result': 'failure'})
Example #12
0
def add_subject():
    try:
        subject_name = request.json['subject_name']
        subject_uuid = request.json['subject_uuid']

        query = "INSERT INTO `subject` (`subject_name`, `subject_uuid`) values (%s, %s)"
        arguments = [subject_name, subject_uuid]
        return jsonify(insert(query, arguments))
    except Exception as ex:
        print(ex)
        return jsonify({'result': 'failure'})
Example #13
0
def post_comment():
    blog_id = request.json['blog_id']
    comment = request.json['comment']
    user_id = request.json['user_id']

    query = '''INSERT INTO `comment` (blog_id, user_id, commented_on, comment)
               VALUES (%s, %s, CURDATE(), %s)
            '''
    arguments = [blog_id, user_id, comment]
    result = insert(query, arguments)
    return jsonify(result)
Example #14
0
def create():
    try:
        name = request.json['name']
        email = request.json['email']
        username = request.json['username']
        password = request.json['password']

        query = "INSERT INTO `users` (`name`, `email`, `username`, `password`,`joined_on`) VALUES (%s, %s, %s, %s, CURDATE())"
        arguments = [name, email, username, md5_hash(password)]

        return jsonify(insert(query, arguments))
    except Exception as ex:
        print(ex)
        return jsonify({'result': 'failure'})
Example #15
0
def create_task():
    try:
        name = request.json['name']
        uuid = request.json['uuid']
        tasklists_id = request.json['tasklist_id']

        token = request.headers.get('Authorization').split(' ')[1]
        decoded = jwt.decode(token, 'secret', algorithms=['HS256'])
        # decoded successfully

        query = '''INSERT INTO `task` (`tasklist_id`, `name`, `uuid`) VALUES (%s, %s, %s)'''
        result = insert(query, [tasklists_id, name, uuid])
        return jsonify(result)
    except Exception:
            return jsonify({'result':'failure' })   
Example #16
0
def create():
    category_id = request.json['category_id']
    heading = request.json['heading']
    body = request.json['body']
    token = request.headers.get('Authorization').split()[1]

    try:
        decoded = jwt.decode(token, 'secret', algorithms=['HS256'])
        user_id = decoded['user_id']
    except Exception:
        return jsonify({'result': 'failure', 'user': '******'})

    query = '''INSERT INTO `blog` (`category_id`, `user_id`, `heading`, `body`, `created_on`)
               VALUES (%s, %s, %s, %s, CURDATE())
            '''
    arguments = [category_id, user_id, heading, body]
    result = insert(query, arguments)
    return jsonify(result)
Example #17
0
def create():
    try:
        emp_name = request.json['emp_name']
        email = request.json['email']
        gender = request.json['gender']
        dept_id = request.json['dept_id']
        salary = request.json['salary']
        emp_uuid = request.json['emp_uuid']
        token = request.headers.get('Authorization').split(' ')[1]

        decoded = jwt.decode(token, 'secret', algorithms=['HS256'])
        query = '''INSERT INTO `employee` (`emp_name`, `email`, `gender`, `dept_id`, `salary`, `emp_uuid`)
                    VALUES (%s, %s, %s, %s, %s, %s)
                '''
        arguments = [emp_name, email, gender, dept_id, salary, emp_uuid]
        result = insert(query, arguments)
        return jsonify(result)
    except Exception:
        return jsonify({'result': 'failure'})
Example #18
0
def post_comment():
    blog_id = request.json['blog_id']
    comment = request.json['comment']
    user_id = request.json['user_id']
    # token       = request.headers.get('Authorization').split()[1]
    """ 
    try:
        decoded = jwt.decode(token, 'secret', algorithms=['HS256'])
        user_id = decoded['user_id']
    except Exception:
        return jsonify({'result':'failure', 'user': '******'}) 
    """

    query = '''INSERT INTO `comment` (blog_id, user_id, commented_on, comment)
               VALUES (%s, %s, CURDATE(), %s)
            '''
    arguments = [blog_id, user_id, comment]
    result = insert(query, arguments)
    return jsonify(result)
Example #19
0
def add_teacher():
    try:
        class_uuid = request.json['class_uuid']
        section_uuid = request.json['section_uuid']
        subject_uuid = request.json['subject_uuid']
        teacher_name = request.json['teacher_name']
        teacher_uuid = request.json['teacher_uuid']

        query = """
                INSERT INTO teachers (`class_uuid`, `section_uuid`, 
                    `subject_uuid`, `teacher_name`, `teacher_uuid`)
                VALUES (%s, %s, %s, %s, %s)
                """
        arguments = [
            class_uuid, section_uuid, subject_uuid, teacher_name, teacher_uuid
        ]
        return jsonify(insert(query, arguments))
    except Exception as ex:
        print(ex)
        return jsonify({'result': 'failure'})
Example #20
0
async def on_ready():
    bot_testing_channel = client.get_channel(BOT_TESTING_CHANNEL_ID)
    mechmarket_channel = client.get_channel(MECH_MARKET_CHANNEL_ID)
    keeb_updates_channel = client.get_channel(KEEB_UPDATES_CHANNEL_ID)
    artisans_update_channel = client.get_channel(ARTISAN_UPDATES_CHANNEL_ID)

    subreddits = ["MechMarket", "MechGroupBuys", "MechanicalKeyboards"]
    announcement_keywords = [
        "[gb]", "[ic]", "[IN STOCK]", "[PRE-ORDER]", "Novelkeys Updates"
    ]

    logging.info(f'{str(datetime.datetime.now())}: Bot is ready')
    await bot_testing_channel.send("MAZ Chan is ready! uWu")

    while True:
        con = mysql.connector.connect(**con_info)

        keywords = query_keywords()

        logging.info(
            f'{str(datetime.datetime.now())}: Checking for new submissions: ')
        submissions = get_scraped_submissions("+".join(subreddits))

        for submission in submissions:
            post_does_exist = does_exist(con, "mechmarket_posts", ["post_id"],
                                         [submission.id])

            if not post_does_exist:
                logging.info(
                    f'{str(datetime.datetime.now())}: Found new submission: {submission.title[:20]}'
                )
                insert(con, "mechmarket_posts", ["post_id", "title"],
                       [submission.id, submission.title[:100]])

                if any(announcement_keyword.lower() in
                       submission.title.lower()
                       for announcement_keyword in announcement_keywords):
                    await keeb_updates_channel.send(
                        f'```{submission.title}```\n \nhttps://redd.it/{submission.id}'
                    )

                if "[Artisan]" in submission.title:
                    await artisans_update_channel.send(
                        f'```{submission.title}```\n \nhttps://redd.it/{submission.id}'
                    )

                if submission.subreddit == "MechMarket":
                    matching_keywords = list(
                        filter(
                            lambda keyword: keyword.lower() in submission.title
                            .lower(), keywords))
                    mentions = set()

                    for matching_keyword in matching_keywords:
                        users = query_users_by_keywords(matching_keyword)

                        for uid in users:
                            forbidden_words = query_forbidden_words_by_user_id(
                                uid)

                            if not any(forbidden_word.lower() in
                                       submission.title.lower()
                                       for forbidden_word in forbidden_words):
                                mentions.add(client.get_user(uid).mention)

                    embed = discord.Embed()
                    embed.title = submission.title
                    embed.url = f"https://redd.it/{submission.id}"
                    image_url = get_url_at(0, submission.selftext_html)

                    if mentions:
                        await mechmarket_channel.send(
                            f'{", ".join(list(set(mentions)))}')
                    await mechmarket_channel.send(embed=embed)
                    if image_url:
                        await mechmarket_channel.send(image_url)

        logging.info(f'{str(datetime.datetime.now())}: Finished scraping')
        con.close()
        await asyncio.sleep(60)
    # update the FPS counter
    cv2.waitKey(1)
    fps.update()

frames_with_face_ratio = frames_with_face / total_frames
faces_relevance = []
for index, count in enumerate(faces_count):
    relevance = count / total_frames
    result = dict(index=index, relevance=relevance)
    faces_relevance.append(result)

document = {
    "name": name,
    "frames_with_face_ratio": frames_with_face_ratio,
    "faces_relevance": faces_relevance,
    "data": data
}

db_helper.insert("faceDetection", document)
db_helper.printDocumentByName("faceDetection", name)

# stop the timer and display FPS information
fps.stop()
print("[INFO] Elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] Approx. FPS: {:.2f}".format(fps.fps()))

# do a bit of cleanup
cv2.destroyAllWindows()
fvs.stop()
    result = dict(timestamp=timestamp, fm=fm, quality=quality)
    data.append(result)

    # show the frame and the result
    if args["show"]:
        cv2.putText(frame, "{:.2f}".format(fm), (10, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)
        cv2.imshow("Video", frame)

    # update the FPS counter
    cv2.waitKey(1)
    fps.update()

# save results to db
name = utils.basename(args["video"])
avg = fmSum / total_frames
document = {"name": name, "avg": avg, "data": data}

db_helper.insert("blurDetection", document)
db_helper.printDocumentByName("blurDetection", name)

# stop the timer and display FPS information
fps.stop()
print("[INFO] Avg. variance of Laplacian: {:.2f}".format(avg))
print("[INFO] Elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] Approx. FPS: {:.2f}".format(fps.fps()))

# do a bit of cleanup
cv2.destroyAllWindows()
fvs.stop()
Example #23
0
def optype(ocode=0, name=mname):
    if ocode == 0:
        print('exit')
    else:
        if ocode == 1:
            op = int(
                input(
                    '请选择记录类型: \n  1:固定收支记录;\n  2:非固定收支记录;\n  3:所有记录;\n 0:查询可用金额 \n  9:退出;\n>>>>'
                ))
            if op == 9:
                print('exit')
            if op == 0:
                queryrecord(op, 'A', 'Q', name)
            else:
                transactioncode = input('请输入类型代码 I 为收入 C 为支出 A 为所有:\n>>>>')
                queryrecord(op, transactioncode, 'Q', name)

        elif ocode == 2:  #insert
            op = int(
                input('请选择记录类型: \n  1:固定收支记录;\n  2:非固定收支记录;\n  9:退出;\n>>>>'))
            if op == 9:
                print('exit')
            if op == 1:
                transactioncode = input('请输入类型代码 I 为收入 C 为支出 A 为所有:\n>>>>')
                col, data, idate, endate = queryrecord(op, transactioncode,
                                                       'I', name)

                if data:
                    iu = input(
                        '存在已有记录! 请选择修改时间,还是更新。\n 1:修改时间;\n 2:更新当前数据;\n>>>>')
                    if iu == '1':
                        col, data, idate, endate = queryrecord(
                            op, transactioncode, 'I', name)
                        if data2:
                            oo = input(
                                '仍存在已有记录,建议您返回先进行记录查询,然后增加新记录\n 1:返回主目录;\n 2:更新当前数据;\n>>>>'
                            )
                            if oo == '2':

                                amountstr = input('请输入金额:')
                                amount = float(amountstr)
                                inputn = int(input('请输入持续月份:\n>>>>'))
                                db.update(udate=idate,
                                          code=op,
                                          qtype=None,
                                          itype=transactioncode,
                                          amt=amount,
                                          dbname=name)
                            else:
                                main()

                    if iu == '2':

                        amountstr = input('请输入金额:')
                        amount = float(amountstr)
                        inputn = int(input('请输入持续月份:\n>>>>'))
                        update(udate=idate,
                               code=op,
                               qtype=None,
                               itype=transactioncode,
                               amt=amount,
                               dbname=name)
                else:

                    amountstr = input('请输入金额:')
                    amount = float(amountstr)
                    inputn = int(input('请输入持续月份:\n>>>>'))
                    insert(code=op,
                           date=idate,
                           itype=transactioncode,
                           cycle=inputn,
                           amt=amount,
                           dbname=name)

            if op == 2:
                transactioncode = input('请输入类型代码 I 为收入 C 为支出 A 为所有:\n>>>>')
                col, data, idate, endate = queryrecord(op, transactioncode,
                                                       'I', name)

                if data:
                    iu = input(
                        '存在已有记录! 请选择修改时间,还是更新。\n 1:修改时间;\n 2:更新当前数据;\n>>>>')
                    if iu == '1':
                        col, data, idate, endate = queryrecord(
                            op, transactioncode, 'I', name)
                        if data2:
                            oo = input(
                                '仍存在已有记录,建议您返回先进行记录查询,然后增加新记录\n 1:返回主目录;\n 2:更新当前数据;\n>>>>'
                            )
                            if oo == '2':

                                amountstr = input('请输入金额:')
                                amount = float(amountstr)
                            else:
                                main()
                    if iu == '2':

                        amountstr = input('请输入金额:')
                        amount = float(amountstr)
                        update(udate=idate,
                               code=op,
                               qtype=None,
                               itype=transactioncode,
                               amt=amount,
                               dbname=name)

                else:

                    amountstr = input('请输入金额:')
                    amount = float(amountstr)
                    insert(code=op,
                           date=idate,
                           itype=transactioncode,
                           cycle=0,
                           amt=amount,
                           dbname=name)

        elif ocode == 3:  #delete
            op = int(
                input('请选择记录类型: \n  1:固定收支记录;\n  2:非固定收支记录;\n   9:退出;\n>>>>'))
            if op == 9:
                print('exit')
            else:
                transactioncode = input('请输入类型代码 I 为收入 C 为支出 A 为所有:\n>>>>')
                col, data, idate, endate = queryrecord(op, transactioncode,
                                                       'D')
                delete(code=op,
                       sdate=idate,
                       edate=endate,
                       ctype=transactioncode,
                       dbname=name)
        elif ocode == 4:  #update
            op = int(
                input(
                    '请选择记录类型: \n  1:固定收支记录;\n  2:非固定收支记录;\n 3:所有记录; \n9:退出;\n>>>>'
                ))
            if op == 9:
                print('exit')
            else:
                opcode = int(
                    input(
                        '请选择搜索条件(时间为必填项)1:只查询收入记录;\n 2:只查询支出记录;\n 3:查询特定金额;\n 0:跳过;\n>>>>>>> '
                    ))
                if opcode == 1:
                    trancode = 'I'
                    queryamount = None
                elif opcode == 2:
                    trancode = 'C'
                    queryamount = None
                elif opcode == 3:
                    queryamount = float(input('请输入要查询的金额:'))
                    trancode = 'A'
                else:
                    trancode = 'A'
                    queryamount = None

                col, data, idate, endate = queryrecord(op, trancode, 'Q', name)
                if data:
                    transactioncode = input(
                        '请输入更改后的类型代码: I 为收入 C 为支出 A 为忽略:\n>>>>')
                    amountstr = input('请输入更改后金额:')
                    amount = float(amountstr)
                    if op == 2:
                        ucycle = None
                    if op == 1 or op == 3:
                        inputcycle = int(input('请输入持续月份, 如无变动则输入0:\n>>>>'))
                        if inputcycle == 0:
                            ucycle = None
                        else:
                            ucycle = inputcycle

                    update(udate=idate,
                           code=op,
                           qtype=trancode,
                           itype=transactioncode,
                           qamt=queryamount,
                           amt=amount,
                           cycle=inputcycle,
                           edate=endate,
                           dbname=name)
                else:

                    if endate is None:
                        print('不存在记录!将直接新增记录!')
                        insert(code=op,
                               date=idate,
                               itype=transactioncode,
                               cycle=ucycle,
                               amt=amount,
                               dbname=name)

        else:
            return ()