jiahuimbzuai/CoQuIR huggingface dataset:
// process_vote [python]
def process_vote(target,action,chan,mask,db,notice,conn):
    if ' ' in target: 
        notice('Invalid nick')
        return

    try: votes2kick = database.get(db,'channels','votekick','chan',chan)
    except: votes2kick = 10
    try: votes2ban = database.get(db,'channels','voteban','chan',chan)
    except: votes2ban = 10

    if len(target) is 0:
        if action is 'kick': notice('Votes required to kick: {}'.format(votes2kick))
        elif action is 'ban': notice('Votes required to ban: {}'.format(votes2ban))
        return

    votefinished = False
    global db_ready
    if not db_ready: db_init(db)
    chan = chan.lower()
    target = target.lower()
    voter = user.format_hostmask(mask)
    voters = db.execute("SELECT voters FROM votes where chan=? and action=? and target like ?", chan, action, target).fetchone()

    if conn.nick.lower() in target: return "I dont think so Tim."

    if voters: 
        voters = voters[0]
        if voter in voters: 
            notice("You have already voted.")
            return
        else:
            voters = '{} {}'.format(voters,voter).strip()
            notice("Thank you for your vote!")
    else: 
        voters = voter

    votecount = len(voters.split(' '))

    if 'kick' in action: 
        votemax = int(votes2kick)
        if votecount >= votemax:
            votefinished = True
            conn.send("KICK {} {} :{}".format(chan, target, "You have been voted off the island."))
    if 'ban' in action:
        votemax = int(votes2ban)
        if votecount >= votemax:
            votefinished = True
            conn.send("MODE {} +b {}".format(chan, user.get_hostmask(target,db)))
            conn.send("KICK {} {} :".format(chan, target, "You have been voted off the island."))
    
    if votefinished: db.execute("DELETE FROM votes where chan=? and action=? and target like ?", chan, action, target)
    else: db.execute("insert or replace into votes(chan, action, target, voters, time) values(?,?,?,?,?)", (chan, action, target, voters, time.time()))
        
    db.commit()
    return ("Votes to {} {}: {}/{}".format(action, target, votecount,votemax))
// process_vote [python]
def process_vote(target,action,chan,mask,db,notice,conn):
    if ' ' in target: 
        notice('Invalid nick')
        return

    try: votes2kick = database.get(db,'channels','votekick','chan',chan)
    except: votes2kick = 10
    try: votes2ban = database.get(db,'channels','voteban','chan',chan)
    except: votes2ban = 10

    if len(target) is 0:
        if action is 'kick': notice('Votes required to kick: {}'.format(votes2kick))
        elif action is 'ban': notice('Votes required to ban: {}'.format(votes2ban))
        return

    votefinished = False
    global db_ready
    if not db_ready: db_init(db)
    chan = chan.lower()
    target = target.lower()
    voter = user.format_hostmask(mask)
    voters = db.execute("SELECT voters FROM votes where chan='{}' and action='{}' and target like '{}'".format(chan,action,target)).fetchone()

    if conn.nick.lower() in target: return "I dont think so Tim."

    if voters: 
        voters = voters[0]
        if voter in voters: 
            notice("You have already voted.")
            return
        else:
            voters = '{} {}'.format(voters,voter).strip()
            notice("Thank you for your vote!")
    else: 
        voters = voter

    votecount = len(voters.split(' '))

    if 'kick' in action: 
        votemax = int(votes2kick)
        if votecount >= votemax:
            votefinished = True
            conn.send("KICK {} {} :{}".format(chan, target, "You have been voted off the island."))
    if 'ban' in action:
        votemax = int(votes2ban)
        if votecount >= votemax:
            votefinished = True
            conn.send("MODE {} +b {}".format(chan, user.get_hostmask(target,db)))
            conn.send("KICK {} {} :".format(chan, target, "You have been voted off the island."))
    
    if votefinished: db.execute("DELETE FROM votes where chan='{}' and action='{}' and target like '{}'".format(chan,action,target))
    else: db.execute("insert or replace into votes(chan, action, target, voters, time) values(?,?,?,?,?)", (chan, action, target, voters, time.time()))
        
    db.commit()
    return ("Votes to {} {}: {}/{}".format(action, target, votecount,votemax))
// like [python]
@mod.route('/like/<int:msg_id>', methods=['GET', 'POST'])
def like(msg_id):
    if request.method == 'GET':
        user_id = session['logged_id']
        c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute("INSERT INTO like_msg(msg_id, user_id,c_time) VALUES(%s,%s,%s);", (msg_id, user_id, c_time))
        conn.commit()
    return redirect(url_for('show_entries'))
// like [python]
@mod.route('/like/<int:msg_id>', methods=['GET', 'POST'])
def like(msg_id):
    if request.method == 'GET':
        user_id = session['logged_id']
        c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        sql = "INSERT INTO like_msg(msg_id, user_id,c_time) " + \
                "VALUES(%d,'%s','%s');" % (msg_id, user_id, c_time)
        cursor.execute(sql)
        conn.commit()
    return redirect(url_for('show_entries'))
// tag_to_tag_num [python]
    def tag_to_tag_num(self, tag):
        ''' Returns tag_num given tag. '''

        q = "SELECT rowid FROM tags WHERE tag = ?"
        self.query(q, tag)
        return self.c.fetchone()[0]
// tag_to_tag_num [python]
    def tag_to_tag_num(self, tag):
        ''' Returns tag_num given tag. '''

        q = "SELECT rowid FROM tags WHERE tag = '" + tag + "'"
        self.query(q)
        return self.c.fetchone()[0]
// update_history_and_sourcebyinstitution [python]
def update_history_and_sourcebyinstitution(conn, sqlite, k10plus, ai):
    """
    Get all current sources and title numbers from Solr and log them into database.
    """
    current_sources = get_all_current_sources(k10plus, ai)
    current_institutions = get_all_current_institutions(k10plus, ai)
    old_sourcebyinstitutions = get_all_old_sourcebyinstitutions(conn, sqlite)
    current_sourcebyinstitutions = []

    for source in current_sources:

        for institution in current_institutions:

            if not institution or institution == " " or '"' in institution:
                continue

            sourcebyinstitution = "SID " + str(source) + " (" + institution + ")"
            current_sourcebyinstitutions.append(sourcebyinstitution)

            params = {
                "q": 'source_id:%s AND institution:"%s"' % (source, institution),
                "rows": 0,
                "wt": "json"
            }

            # check k10plus
            result = get_solr_result(k10plus, params)
            number = result["response"]["numFound"]
            if number != 0:
                sql = 'INSERT INTO history (sourcebyinstitution, titles) VALUES (?, ?)'
                sqlite.execute(sql, (sourcebyinstitution, number))
                conn.commit()
            else:
                # check ai
                result = get_solr_result(ai, params)
                number = result["response"]["numFound"]
                if number != 0:
                    # TODO: escape via sqlite
                    sql = 'INSERT INTO history (sourcebyinstitution, titles) VALUES (?, ?)'
                    sqlite.execute(sql, (sourcebyinstitution, number))
                    conn.commit()

            if sourcebyinstitution not in old_sourcebyinstitutions:
                logging.info("The %s is now connected to SID %s.", institution, source)
                sql = "INSERT INTO sourcebyinstitution (sourcebyinstitution) VALUES (?)"
                sqlite.execute(sql, (sourcebyinstitution))
                conn.commit()

            if number != 0:
                old_sourcebyinstitution_number = get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution)
                if number < old_sourcebyinstitution_number:
                    message = "Die Anzahl der Titel hat sich bei %s gegenueber einem frueheren Import verringert." % (sourcebyinstitution)
                    send_message(message)

            # requests.exceptions.ConnectionError: HTTPConnectionPool(XXXXXX): Max retries exceeded
            time.sleep(0.25)

    for old_sourcebyinstitution in old_sourcebyinstitutions:
        if old_sourcebyinstitution not in current_sourcebyinstitutions:
            message = "Die %s ist nicht laenger für die SID %s angesigelt." % (institution, source)
            send_message(message)
// update_history_and_sourcebyinstitution [python]
def update_history_and_sourcebyinstitution(conn, sqlite, k10plus, ai):
    """
    Get all current sources and title numbers from Solr and log them into database.
    """
    current_sources = get_all_current_sources(k10plus, ai)
    current_institutions = get_all_current_institutions(k10plus, ai)
    old_sourcebyinstitutions = get_all_old_sourcebyinstitutions(conn, sqlite)
    current_sourcebyinstitutions = []

    for source in current_sources:

        for institution in current_institutions:

            if not institution or institution == " " or '"' in institution:
                continue

            sourcebyinstitution = "SID " + str(source) + " (" + institution + ")"
            current_sourcebyinstitutions.append(sourcebyinstitution)

            params = {
                "q": 'source_id:%s AND institution:"%s"' % (source, institution),
                "rows": 0,
                "wt": "json"
            }

            # check k10plus
            result = get_solr_result(k10plus, params)
            number = result["response"]["numFound"]
            if number != 0:
                sql = 'INSERT INTO history (sourcebyinstitution, titles) VALUES ("%s", %s)' % (sourcebyinstitution, number)
                sqlite.execute(sql)
                conn.commit()
            else:
                # check ai
                result = get_solr_result(ai, params)
                number = result["response"]["numFound"]
                if number != 0:
                    # TODO: escape via sqlite
                    sql = 'INSERT INTO history (sourcebyinstitution, titles) VALUES ("%s", %s)' % (sourcebyinstitution, number)
                    sqlite.execute(sql)
                    conn.commit()

            if sourcebyinstitution not in old_sourcebyinstitutions:
                logging.info("The %s is now connected to SID %s.", institution, source)
                sql = "INSERT INTO sourcebyinstitution (sourcebyinstitution) VALUES ('%s')" % sourcebyinstitution
                sqlite.execute(sql)
                conn.commit()

            if number != 0:
                old_sourcebyinstitution_number = get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution)
                if number < old_sourcebyinstitution_number:
                    message = "Die Anzahl der Titel hat sich bei %s gegenueber einem frueheren Import verringert." % (sourcebyinstitution)
                    send_message(message)

            # requests.exceptions.ConnectionError: HTTPConnectionPool(XXXXXX): Max retries exceeded
            time.sleep(0.25)

    for old_sourcebyinstitution in old_sourcebyinstitutions:
        if old_sourcebyinstitution not in current_sourcebyinstitutions:
            message = "Die %s ist nicht laenger für die SID %s angesigelt." % (institution, source)
            send_message(message)
// change_message [python]
    def change_message(self, new_message, logged_user):
        update_sql = """
            UPDATE Clients
            SET message = ?
            WHERE client_id = ?
        """

        cursor = self.__conn.cursor()

        cursor.execute(update_sql, (new_message, logged_user.get_client_id()))
        self.__conn.commit()
        logged_user.set_message(new_message)
// change_message [python]
    def change_message(self, new_message, logged_user):
        update_sql = """
            UPDATE Clients
            SET message = '{}'
            WHERE client_id = '{}'
        """.format(new_message, logged_user.get_client_id())

        cursor = self.__conn.cursor()

        cursor.execute(update_sql)
        self.__conn.commit()
        logged_user.set_message(new_message)
// create_event [python]
    def create_event(self, title, start_time, time_zone, server_id, description):
        sql = """
              INSERT INTO events (title, start_time, time_zone, server_id, description)
              VALUES (%s, %s, %s, %s, %s)
              """
        self.cur.execute(sql, (title, start_time, time_zone, server_id, description))
        self.conn.commit()
// create_event [python]
    def create_event(self, title, start_time, time_zone, server_id, description):
        sql = """INSERT INTO events (title, start_time, time_zone, server_id, description)
                 VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')
                 """.format(title, start_time, time_zone, server_id, description)
        self.cur.execute(sql)
        self.conn.commit()
// get_login2 [python]
@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_LOGIN.value)
def get_login2(message):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
    conn = settings.cursor()
    if bases.createuserbase.check_username(message.text):
        bot.send_message(message.chat.id, "Invalid handle.")
        set_state(message.chat.id, config.States.S_START.value)
        return 0
    conn.execute("select * from users where chat_id = ?", (str(message.chat.id),))
    name = conn.fetchone()
    settings.close()
    bases.update.cf_update()
    bases.createuserbase.clean_base(name[1])
    bases.createuserbase.clean_base(message.text)
    bot.send_message(message.chat.id, "Creating base...")
    bases.createuserbase.init_user(message.text, message.chat.id)
    bot.send_message(message.chat.id, "Done!")
    set_state(message.chat.id, config.States.S_START.value)
// get_login2 [python]
@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_LOGIN.value)
def get_login2(message):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
    conn = settings.cursor()
    if bases.createuserbase.check_username(message.text):
        bot.send_message(message.chat.id, "Invalid handle.")
        set_state(message.chat.id, config.States.S_START.value)
        return 0

    conn.execute("select * from users where chat_id = '" + str(message.chat.id) + "'")
    name = conn.fetchone()
    settings.close()
    bases.update.cf_update()
    bases.createuserbase.clean_base(name[1])
    bases.createuserbase.clean_base(message.text)
    bot.send_message(message.chat.id, "Creating base...")
    bases.createuserbase.init_user(message.text, message.chat.id)
    bot.send_message(message.chat.id, "Done!")
    set_state(message.chat.id, config.States.S_START.value)
// get_bracket_graph_data [python]
def get_bracket_graph_data(db, tag):
    # First, we have to find out which scenes this player has brackets in
    sql = "SELECT DISTINCT scene FROM ranks WHERE player='{tag}'"
    args = {'tag': tag}
    scenes = db.exec(sql, args)
    scenes = [s[0] for s in scenes]

    bracket_placings_by_scene = {s: get_bracket_placings_in_scene(db, s, tag) for s in scenes}

    return bracket_placings_by_scene
// get_bracket_graph_data [python]
def get_bracket_graph_data(db, tag):
    # First, we have to find out which scenes this player has brackets in
    sql = "SELECT DISTINCT scene FROM ranks WHERE player='{}'".format(tag)
    scenes = db.exec(sql)
    scenes = [s[0] for s in scenes]

    bracket_placings_by_scene = {s: get_bracket_placings_in_scene(db, s, tag) for s in scenes}

    return bracket_placings_by_scene
// get [python]
    def get(self, email):
        """ Fetch data for admin with the corresponding email """
        return database_utilities.execute_query(f"""select * from admins where email = %s""", (email, ))
// get [python]
    def get(self, email):
        """ Fetch data for admin with the corresponding email """
        return database_utilities.execute_query(f"""select * from admins where email = '{email}'""")
// insertUsage [python]
def insertUsage(user, command):
	c, conn = getConnection()
	date = now()
	c.execute("INSERT INTO usage (date,user,command) VALUES (?,?,?)",(date,str(user),command))
	conn.commit()
	conn.close()
// insertUsage [python]
def insertUsage(user, command):
	c, conn = getConnection()
	date = now()
	c.execute("INSERT INTO usage (date,user,command) VALUES ('"+date+"','"+str(user)+"','"+command+"')")
	conn.commit()
	conn.close()
// verify_email [python]
    def verify_email(self, member):
        self.cursor.execute("SELECT COUNT(email) FROM members WHERE email = ':email'", {'email':member})
        result = self.cursor.fetchone()
        if (int(result[0]) > 0):
            return True 
        else:
            return False
// verify_email [python]
    def verify_email(self, member):
        query = "SELECT COUNT(email) FROM members WHERE email = '{email}'".format(email = member)
        self.cursor.execute(query)
        result = self.cursor.fetchone()
        if (int(result[0]) > 0):
            return True 
        else:
            return False
// get_previous_yields [python]
    def get_previous_yields(self, inverter_serial):
        query = '''
           SELECT TimeStamp, EToday, ETotal
           FROM Inverters
           WHERE Serial=?
        '''
        self.c.execute(query, (inverter_serial,))
        data = self.c.fetchone()
        return data[0], data[1], data[2]
// get_previous_yields [python]
    def get_previous_yields(self, inverter_serial):
        query = '''
           SELECT TimeStamp, EToday, ETotal
           FROM Inverters
           WHERE Serial = '%s'
        ''' % (inverter_serial)
        self.c.execute(query)
        data = self.c.fetchone()
        return data[0], data[1], data[2]
// referrer_count [python]
@app.route('/referrer_count')
def referrer_count():
    account_id = request.args.get('account_id')

    if not isObject(account_id):
        ws.send('{"id":1, "method":"call", "params":[0,"lookup_account_names",[["' + account_id + '"], 0]]}')
        result_l = ws.recv()
        j_l = json.loads(result_l)

        account_id = j_l["result"][0]["id"]

    con = psycopg2.connect(**config.POSTGRES)
    cur = con.cursor()

    query = "select count(*) from referrers where referrer=%s"
    cur.execute(query, (account_id,))
    results = cur.fetchone()

    return jsonify(results)
// referrer_count [python]
@app.route('/referrer_count')
def referrer_count():
    account_id = request.args.get('account_id')

    if not isObject(account_id):
        ws.send('{"id":1, "method":"call", "params":[0,"lookup_account_names",[["' + account_id + '"], 0]]}')
        result_l = ws.recv()
        j_l = json.loads(result_l)

        account_id = j_l["result"][0]["id"]

    con = psycopg2.connect(**config.POSTGRES)
    cur = con.cursor()

    query = "select count(*) from referrers where referrer='"+account_id+"'"
    cur.execute(query)
    results = cur.fetchone()

    return jsonify(results)
// get_article [python]
def get_article(index):
    with conn.cursor(cursor_factory=DictCursor) as cur:
        query = "SELECT * FROM articles WHERE index=%s"
        cur.execute(query, (index, ))
        article = cur.fetchone()
        return article
// get_article [python]
def get_article(index):
    with conn.cursor(cursor_factory=DictCursor) as cur:
        query = "SELECT * FROM articles WHERE index="+str(index)
        cur.execute(query)
        article = cur.fetchone()
        return article
// create_cf_base [python]
def create_cf_base():
    url = 'http://codeforces.com/problemset/'
    r = requests.get(url)
    max_page = 0
    soup = BeautifulSoup(r.text, "lxml")
    base = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\cf.db")
    conn = base.cursor()
    conn.execute("create table problems (problem INTEGER, diff CHAR)")
    for i in available_tags:
        conn.execute("create table ? (problems INTEGER, diff CHAR)", (i,))

    for link in soup.find_all(attrs={"class" : "page-index"}):
        s = link.find('a')
        s2 = s.get("href").split('/')
        max_page = max(max_page, int(s2[3]))

    a = 0
    b = 0
    f = False
    for i in range(1, max_page + 1):
        r = requests.get('http://codeforces.com/problemset/' + '/page/' + str(i))
        soup = BeautifulSoup(r.text, "lxml")
        old = ''
        for link in soup.find_all('a'):
            s = link.get('href')
            if s != None and s.find('/problemset') != -1:
                s = s.split('/')
                if len(s) == 5 and old != s[3] + s[4]:
                    a = s[3]
                    b = s[4]
                    old = s[3] + s[4]
                    if not f:
                        f = True
                        last_update = old
                    conn.execute("insert into problems values (?, ?)", (a, b))
                if len(s) == 4 and s[3] in available_tags:
                    conn.execute("insert into ? values (?, ?)", (s[3], a, b))

    base.commit()
    base.close()
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\settings.db")
    conn = settings.cursor()
    conn.execute("create table users (chat_id INTEGER, username STRING, last_update STRING, last_problem STRING, state INTEGER)")
    conn.execute("create table last_update_problemset (problem STRING)")
    conn.execute("insert into last_update_problemset values (?)", (last_update, ))
    settings.commit()
    settings.close()
// create_cf_base [python]
def create_cf_base():
    url = 'http://codeforces.com/problemset/'
    r = requests.get(url)
    max_page = 0
    soup = BeautifulSoup(r.text, "lxml")
    base = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\cf.db")
    conn = base.cursor()
    conn.execute("create table problems (problem INTEGER, diff CHAR)")
    for i in available_tags:
        conn.execute("create table " + i + " (problems INTEGER, diff CHAR)")

    for link in soup.find_all(attrs={"class" : "page-index"}):
        s = link.find('a')
        s2 = s.get("href").split('/')
        max_page = max(max_page, int(s2[3]))

    a = 0
    b = 0
    f = False
    for i in range(1, max_page + 1):
        r = requests.get('http://codeforces.com/problemset/' + '/page/' + str(i))
        soup = BeautifulSoup(r.text, "lxml")
        old = ''
        for link in soup.find_all('a'):
            s = link.get('href')
            if s != None and s.find('/problemset') != -1:
                s = s.split('/')
                if len(s) == 5 and old != s[3] + s[4]:
                    a = s[3]
                    b = s[4]
                    old = s[3] + s[4]
                    if not f:
                        f = True
                        last_update = old
                    conn.execute("insert into problems values (?, ?)", (a, b))
                if len(s) == 4 and s[3] in available_tags:
                    conn.execute("insert into " + s[3] + " values (?, ?)", (a, b))

    base.commit()
    base.close()
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\settings.db")
    conn = settings.cursor()
    conn.execute("create table users (chat_id INTEGER, username STRING, last_update STRING, last_problem STRING, state INTEGER)")
    conn.execute("create table last_update_problemset (problem STRING)")
    conn.execute("insert into last_update_problemset values (?)", (last_update, ))
    settings.commit()
    settings.close()
// closeGame [python]
def closeGame(ID):
	db.execute("UPDATE games set Running = 'No' WHERE ID = ?", ID)
	database.commit()
// closeGame [python]
def closeGame(ID):
	db.execute("UPDATE games set Running = 'No' WHERE ID = %i" % ID)
	database.commit()
// cancelFollow [python]
    def cancelFollow(self,userid,friendid):
        sqlText="delete from friends where userid=%d and friendid=%s;"
        params=[userid,friendid]
        result=sql.deleteDB(self.conn,sqlText,params)
        return result;
// cancelFollow [python]
    def cancelFollow(self,userid,friendid):
        sqlText="delete from friends where userid=%d and friendid=%d;"%(userid,friendid)
        result=sql.deleteDB(self.conn,sqlText)
        return result;
// change_pass [python]
    def change_pass(self, new_pass, logged_user):
        update_sql = """
            UPDATE Clients
            SET password = ?
            WHERE client_id = ?
        """

        cursor = self.__conn.cursor()

        cursor.execute(update_sql, (new_pass, logged_user.get_client_id()))
        self.__conn.commit()
// change_pass [python]
    def change_pass(self, new_pass, logged_user):
        update_sql = """
            UPDATE Clients
            SET password = '{}'
            WHERE client_id = '{}'
        """.format(new_pass, logged_user.get_client_id())

        cursor = self.__conn.cursor()

        cursor.execute(update_sql)
        self.__conn.commit()
// getCommentsByPostid [python]
    def getCommentsByPostid(self,postid,userid):
        sqlText="select (select Count(*) from comment_like where \
        comments.commentid = comment_like.commentid) as like,(select Count(*) \
                from comment_like where comments.commentid = \
                comment_like.commentid and comment_like.userid=%s) as \
                flag,commentid,name,comment from users,comments where \
                users.userid=comments.userid and postid=%s order by date desc;"
        params=[userid,postid]
        result=sql.queryDB(self.conn,sqlText,params)
        return result;
// getCommentsByPostid [python]
    def getCommentsByPostid(self,postid,userid):
        sqlText="select (select Count(*) from comment_like where comments.commentid = comment_like.commentid) as like,(select Count(*) from comment_like where comments.commentid = comment_like.commentid and comment_like.userid=%d) as flag,commentid,name,comment from users,comments where users.userid=comments.userid and postid=%d order by date desc;"%(userid,postid)
        result=sql.queryDB(self.conn,sqlText)
        return result;
// __init__.callback [python]
        def callback(recipeName):
            menu.pack_forget()
            viewRecipeFrame.pack(expand=True, fill='both')
            groceryButton.pack_forget()
            database_file = "meal_planner.db"
            print(recipeName)
            with sqlite3.connect(database_file) as conn:
                cursor = conn.cursor()
                selection = cursor.execute("""SELECT * FROM recipe WHERE name = ?;""", (recipeName, ))
                for result in [selection]:
                    for row in result.fetchall():
                        name = row[0]
                        time = row[1]
                        servings = row[2]
                        ingredients = row[4]
                        directions = row[5]

                        string = ("Name: {} \n Cook time: {} \n Number of Servings: {} \n ".format(name, time, servings))
                        secondString = ("Ingredients: {}".format(ingredients))
                        thirdString = ("Directions: {}".format(directions))
            Label(viewRecipeFrame, text=string, font=MEDIUM_FONT, bg="#f8f8f8", fg="#000000").pack(side=TOP)
            Label(viewRecipeFrame, text=secondString, font=MEDIUM_FONT, bg="#f8f8f8", fg="#000000").pack(side=TOP)
            Label(viewRecipeFrame, text=thirdString, font=MEDIUM_FONT, bg="#f8f8f8", fg="#000000").pack(side=TOP)
            returnButton = Button(menuFrame, text = "Return to Menu", highlightbackground="#e7e7e7", command=lambda: [viewRecipeFrame.pack_forget(),
                                                                                     menu.pack(), returnButton.pack_forget(), label.configure(text="Meal Planer"),
                                                                                    groceryButton.pack(side=RIGHT)])
            returnButton.pack(side=RIGHT)
// __init__.callback [python]
        def callback(recipeName):
            menu.pack_forget()
            viewRecipeFrame.pack(expand=True, fill='both')
            groceryButton.pack_forget()
            database_file = "meal_planner.db"
            print(recipeName)
            with sqlite3.connect(database_file) as conn:
                cursor = conn.cursor()
                selection = cursor.execute("""SELECT * FROM recipe WHERE name = """ + "\"" + recipeName + "\"")
                for result in [selection]:
                    for row in result.fetchall():
                        name = row[0]
                        time = row[1]
                        servings = row[2]
                        ingredients = row[4]
                        directions = row[5]

                        string = ("Name: {} \n Cook time: {} \n Number of Servings: {} \n ".format(name, time, servings))
                        secondString = ("Ingredients: {}".format(ingredients))
                        thirdString = ("Directions: {}".format(directions))
            Label(viewRecipeFrame, text=string, font=MEDIUM_FONT, bg="#f8f8f8", fg="#000000").pack(side=TOP)
            Label(viewRecipeFrame, text=secondString, font=MEDIUM_FONT, bg="#f8f8f8", fg="#000000").pack(side=TOP)
            Label(viewRecipeFrame, text=thirdString, font=MEDIUM_FONT, bg="#f8f8f8", fg="#000000").pack(side=TOP)
            returnButton = Button(menuFrame, text = "Return to Menu", highlightbackground="#e7e7e7", command=lambda: [viewRecipeFrame.pack_forget(),
                                                                                     menu.pack(), returnButton.pack_forget(), label.configure(text="Meal Planer"),
                                                                                    groceryButton.pack(side=RIGHT)])
            returnButton.pack(side=RIGHT)
// patch [python]
    @jwt_required
    def patch(self, user_id):
        """ Replaces information of corresponding user_id with request body """
        query = f"""update users set user_id = %s """
        query += f"""where user_id = %s"""
        json_data = request.get_json()
        parameters = (json_data['user_id'], user_id)
        database_utilities.execute_query(query, parameters)
// patch [python]
    @jwt_required
    def patch(self, user_id):
        """ Replaces information of corresponding user_id with request body """
        query = f"""update users set user_id = %s """
        query += f"""where user_id = '{user_id}'"""
        json_data = request.get_json()
        parameters = (json_data['user_id'], )
        database_utilities.execute_query(query, parameters)
// edit [python]
@mod.route('/edit', methods=['GET', 'POST'])
def edit():
    cursor.execute("SELECT * FROM users where email = %s;", (session['logged_email'],))
    u = cursor.fetchone()
    if request.method == 'POST':
        cursor.execute("UPDATE users SET nickname = %s where email = %s", (request.form['nickname'], session['logged_email']))
        cursor.execute("SELECT * FROM users where email = %s;", (session['logged_email'],))
        u = cursor.fetchone()
        conn.commit()
        flash('Edit Nickname Success!')
    return render_template('users/edit.html', u=u)
// edit [python]
@mod.route('/edit', methods=['GET', 'POST'])
def edit():
    sql = "SELECT * FROM users where email = '%s';" % (session['logged_email'])
    cursor.execute(sql)
    u = cursor.fetchone()
    if request.method == 'POST':
        sql = "UPDATE users SET nickname = '%s' where email = '%s'" \
        % (request.form['nickname'], session['logged_email'])
        cursor.execute(sql)
        sql = "SELECT * FROM users where email = '%s';" \
            % (session['logged_email'])
        cursor.execute(sql)
        u = cursor.fetchone()
        conn.commit()
        flash('Edit Nickname Success!')
    return render_template('users/edit.html', u=u)
// shame_add [python]
def shame_add(name):
    shame = shame_ask(name)
    db = db_connect()
    cursor = db.cursor()
    if shame is None:
        try:
            cursor.execute('''
                INSERT INTO people(name,karma,shame) VALUES(%(name)s,0,1)
                ''', (name, ))
            db.commit()
            logger.debug('Inserted into karmadb 1 shame for {}'.format(name))
            db.close()
            return 1
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise

    else:
        shame = shame + 1
        try:
            cursor.execute('''
                UPDATE people SET shame = %(karma)s WHERE name = %(name)s
                ''' (
                shame,
                name,
            ))
            db.commit()
            logger.debug('Inserted into karmadb {} shame for {}'.format(
                shame, name))
            db.close()
            return shame
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise
// shame_add [python]
def shame_add(name):
    shame = shame_ask(name)
    db = db_connect()
    cursor = db.cursor()
    if shame is None:
        try:
            cursor.execute('''
                INSERT INTO people(name,karma,shame) VALUES('{}',0,1)
                '''.format(name))
            db.commit()
            logger.debug('Inserted into karmadb 1 shame for {}'.format(name))
            db.close()
            return 1
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise

    else:
        shame = shame + 1
        try:
            cursor.execute('''
                UPDATE people SET shame = {0} WHERE name = '{1}'
                '''.format(shame, name))
            db.commit()
            logger.debug('Inserted into karmadb {} shame for {}'.format(
                shame, name))
            db.close()
            return shame
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise
// can_user_pass_that_amount_of_money [python]
    def can_user_pass_that_amount_of_money(self, user_id, money):
        self.cursor.execute("SELECT count(id) FROM kickstarter.users where id = %s and money >= %s", (user_id, money))
        return self.cursor.fetchall()[0][0]
// can_user_pass_that_amount_of_money [python]
    def can_user_pass_that_amount_of_money(self, user_id, money):
        self.cursor.execute("SELECT count(id) FROM kickstarter.users where id = %s and money >= %s" % (user_id, money))
        return self.cursor.fetchall()[0][0]
// placings [python]
@endpoints.route("/placings")
def placings():
    if db == None:
        init()

    tag = request.args.get('tag', default='christmas mike')

    # Get all the urls that this player has participated in
    sql = "SELECT * FROM placings WHERE player = '{tag}'"
    args = {'tag': tag}
    results = list(db.exec(sql, args))
    results.sort(key=lambda x: int(x[2]))

    return json.dumps(results)
// placings [python]
@endpoints.route("/placings")
def placings():
    if db == None:
        init()

    tag = request.args.get('tag', default='christmas mike')

    # Get all the urls that this player has participated in
    sql = "SELECT * FROM placings WHERE player = '{}'".format(tag)
    results = list(db.exec(sql))
    results.sort(key=lambda x: int(x[2]))

    return json.dumps(results)
// markTokenUsedExternal [python]
def markTokenUsedExternal(token, optStr=""):
    conn, c = connectDB()
    req = "UPDATE {} SET \"options_selected\"=? WHERE token=?".format(CFG("tokens_table_name"))
    c.execute(req, (optStr, token,))
    closeDB(conn)
// markTokenUsedExternal [python]
def markTokenUsedExternal(token, optStr=""):
    conn, c = connectDB()
    req = "UPDATE {} SET \"options_selected\"='{}' WHERE token='{}'".format(CFG("tokens_table_name"), \
                    optStr, token)
    c.execute(req)
    closeDB(conn)
// get_roster [python]
    def get_roster(self, server_id):
        sql = """
              SELECT username, role
              FROM roles
              WHERE roles.server_id = %s;
              """
        self.cur.execute(sql, (server_id,))
        return self.cur.fetchall()
// get_roster [python]
    def get_roster(self, server_id):
        sql = """SELECT username, role
                 FROM roles
                 WHERE roles.server_id = {0};
                 """.format(server_id)
        self.cur.execute(sql)
        return self.cur.fetchall()
// retrieve_video [python]
def retrieve_video(id, playlist_id, db):
    db.execute(
        "SELECT id, position from video WHERE id=%s and playlist_id=%s;", (id, playlist_id))
    row = db.fetchone()
    return row
// retrieve_video [python]
def retrieve_video(id, playlist_id, db):
    db.execute("SELECT id, position from video WHERE id={id} and playlist_id={playlist_id};".format(
        id=id, playlist_id=playlist_id))
    row = db.fetchone()
    return row
// followFriends [python]
    def followFriends(self,userid,friendid):
        sqlText="insert into friends values(%s,%s);"
        params=[friendid,userid]
        result=sql.insertDB(self.conn,sqlText,params)
        return result;
// followFriends [python]
    def followFriends(self,userid,friendid):
        sqlText="insert into friends values(%d,%d);"%(friendid,userid)
        result=sql.insertDB(self.conn,sqlText)
        return result;
// getGameID [python]
def getGameID(ID):
	db.execute("SELECT * FROM games WHERE ID = ?", ID)
	ID = db.fetchone()
	return ID
// getGameID [python]
def getGameID(ID):
	db.execute("SELECT * FROM games WHERE ID = %i" % ID)
	ID = db.fetchone()
	return ID
// top_proxies [python]
@app.route('/top_proxies')
def top_proxies():
    con = psycopg2.connect(**config.POSTGRES)
    cur = con.cursor()

    query = "SELECT sum(amount) FROM holders"
    cur.execute(query)
    total = cur.fetchone()
    total_votes = total[0]

    query = "SELECT voting_as FROM holders WHERE voting_as<>'1.2.5' group by voting_as"
    cur.execute(query)
    results = cur.fetchall()
    #con.close()

    proxies = []

    for p in range(0, len(results)):

        proxy_line = [0] * 5

        proxy_id = results[p][0]
        proxy_line[0] = proxy_id

        query = "SELECT account_name, amount FROM holders WHERE account_id=%s LIMIT 1"
        cur.execute(query, (proxy_id,))
        proxy = cur.fetchone()

        try:
            proxy_name = proxy[0]
            proxy_amount = proxy[1]
        except:
            proxy_name = "unknown"
            proxy_amount = 0


        proxy_line[1] = proxy_name

        query = "SELECT amount, account_id FROM holders WHERE voting_as=%s"
        cur.execute(query, (proxy_id,))
        results2 = cur.fetchall()

        proxy_line[2] = int(proxy_amount)

        for p2 in range(0, len(results2)):
            amount = results2[p2][0]
            account_id = results2[p2][1]
            proxy_line[2] = proxy_line[2] + int(amount)  # total proxy votes
            proxy_line[3] = proxy_line[3] + 1       # followers

        if proxy_line[3] > 2:
            percentage = float(float(proxy_line[2]) * 100.0/ float(total_votes))
            proxy_line[4] = percentage
            proxies.append(proxy_line)

    con.close()

    proxies = sorted(proxies, key=lambda k: int(k[2]))
    r_proxies = proxies[::-1]

    return jsonify(filter(None, r_proxies))
// top_proxies [python]
@app.route('/top_proxies')
def top_proxies():
    con = psycopg2.connect(**config.POSTGRES)
    cur = con.cursor()

    query = "SELECT sum(amount) FROM holders"
    cur.execute(query)
    total = cur.fetchone()
    total_votes = total[0]

    query = "SELECT voting_as FROM holders WHERE voting_as<>'1.2.5' group by voting_as"
    cur.execute(query)
    results = cur.fetchall()
    #con.close()

    proxies = []

    for p in range(0, len(results)):

        proxy_line = [0] * 5

        proxy_id = results[p][0]
        proxy_line[0] = proxy_id

        query = "SELECT account_name, amount FROM holders WHERE account_id='"+proxy_id+"' LIMIT 1"
        cur.execute(query)
        proxy = cur.fetchone()

        try:
            proxy_name = proxy[0]
            proxy_amount = proxy[1]
        except:
            proxy_name = "unknown"
            proxy_amount = 0


        proxy_line[1] = proxy_name

        query = "SELECT amount, account_id FROM holders WHERE voting_as='"+proxy_id+"'"
        cur.execute(query)
        results2 = cur.fetchall()

        proxy_line[2] = int(proxy_amount)

        for p2 in range(0, len(results2)):
            amount = results2[p2][0]
            account_id = results2[p2][1]
            proxy_line[2] = proxy_line[2] + int(amount)  # total proxy votes
            proxy_line[3] = proxy_line[3] + 1       # followers

        if proxy_line[3] > 2:
            percentage = float(float(proxy_line[2]) * 100.0/ float(total_votes))
            proxy_line[4] = percentage
            proxies.append(proxy_line)

    con.close()

    proxies = sorted(proxies, key=lambda k: int(k[2]))
    r_proxies = proxies[::-1]

    return jsonify(filter(None, r_proxies))
// userLogin [python]
    def userLogin(self):

        sqlName="select count(*) from users where name=%s and password=%s;"
        params = [self.name,self.password]
        checkName=sql.queryDB(self.conn,sqlName,params)
        result=checkName[0][0]
        if result == 0:
            self.clean()
            return False
        else:
            return True
// userLogin [python]
    def userLogin(self):

        sqlName="select count(*) from users where name='%s' and \
                password='%s';"%(self.name,self.password)
        checkName=sql.queryDB(self.conn,sqlName)

        result=checkName[0][0]
        if result == 0:
            self.clean()
            return False
        else:
            return True
// search_pages [python]
@app.route("/search", methods = ["POST"])
def search_pages():
    search = request.form.get("search")
    page = db.query("select title from page where title = $1", search).namedresult()
    if len(page) == 0:
        return redirect("/%s" % search)
    else:
        return place_holder(search)
// search_pages [python]
@app.route("/search", methods = ["POST"])
def search_pages():
    search = request.form.get("search")
    page = db.query("select title from page where title = '%s'" % search).namedresult()
    if len(page) == 0:
        return redirect("/%s" % search)
    else:
        return place_holder(search)
// get_articles_by_subject [python]
def get_articles_by_subject(subject):
    with conn.cursor(cursor_factory=DictCursor) as cur:
        query = "SELECT * FROM articles WHERE subject=%s ORDER BY last_submitted DESC"
        cur.execute(query, (subject,))
        articles = cur.fetchall()
        return articles
// get_articles_by_subject [python]
def get_articles_by_subject(subject):
    with conn.cursor(cursor_factory=DictCursor) as cur:
        query = "SELECT * FROM articles WHERE subject='" + subject + "' ORDER BY last_submitted DESC"
        cur.execute(query)
        articles = cur.fetchall()
        return articles
// getQueue [python]
    def getQueue(self, numberOfLinks=10):
        self.cursor.execute("SELECT url FROM queue WHERE visited = '0' LIMIT ?;", numberOfLinks)
        result = self.cursor.fetchall()
        self.remove(result)
        return result
// getQueue [python]
    def getQueue(self, numberOfLinks=10):
        self.cursor.execute("SELECT url FROM queue WHERE visited = '0' LIMIT {};".format(numberOfLinks))
        result = self.cursor.fetchall()
        self.remove(result)
        return result
// showPoll [python]
@hook.command(autohelp=False)
def showPoll(pollID, db=None):
    """Shows the answers for a given poll."""
    if not db_ready: db_init(db)
    if pollID == None:
        poll = db.execute("SELECT pollID, question FROM polls WHERE active = 1")
        if len(poll) == 0:
            reply("There's no poll open.")
            return
    else:
        poll = db.execute("SELECT pollID, question FROM polls WHERE pollID = ?", (pollID,))
        if len(poll) == 0:
            reply("No such poll found.")
            return
    pollID = poll[0][0]
    question = poll[0][1]
    reply(question)
    for (index, answer, votes) in db.execute("SELECT 'index', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = ? GROUP BY answers.answerID, 'index', answer ORDER BY 'index' ASC", (pollID, )):
        reply("%s. %s (%s)" % (index, answer, votes))
// showPoll [python]
@hook.command(autohelp=False)
def showPoll(pollID, db=None):
    """Shows the answers for a given poll."""
    if not db_ready: db_init(db)
    if pollID == None:
        poll = db.execute("SELECT pollID, question FROM polls WHERE active = 1")
        if len(poll) == 0:
            reply("There's no poll open.")
            return
    else:
        poll = db.execute("SELECT pollID, question FROM polls WHERE pollID = '{}'".format(pollID))
        if len(poll) == 0:
            reply("No such poll found.")
            return
    pollID = poll[0][0]
    question = poll[0][1]
    reply(question)
    for (index, answer, votes) in db.execute("SELECT 'index', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = {} GROUP BY answers.answerID, 'index', answer ORDER BY 'index' ASC".format(pollID, )):
        reply("%s. %s (%s)" % (index, answer, votes))
// process_ranks [python]
    def process_ranks(self, scene, urls, recent_date):
        PLAYER1 = 0
        PLAYER2 = 1
        WINNER = 2
        DATE = 3
        SCENE = 4

        # make sure if we already have calculated ranks for these players at this time, we do not do it again
        sql = "SELECT * FROM ranks WHERE scene = '{scene}' AND date='{date}';"
        args = {'scene': scene, 'date': recent_date}
        res = self.db.exec(sql, args)
        if len(res) > 0:
            LOG.info('We have already calculated ranks for {} on date {}. SKipping'.format(scene, recent_date))
            return

        matches = bracket_utils.get_matches_from_urls(self.db, urls)
        LOG.info('About to start processing ranks for scene {} on {}'.format(scene, recent_date))

        # Iterate through each match, and build up our dict
        win_loss_dict = {}
        for match in matches:
            p1 = match[PLAYER1]
            p2 = match[PLAYER2]
            winner = match[WINNER]
            date = match[DATE]

            #Add p1 to the dict
            if p1 not in win_loss_dict:
                win_loss_dict[p1] = {}

            if p2 not in win_loss_dict[p1]:
                win_loss_dict[p1][p2] = []

            # Add an entry to represent this match to p1
            win_loss_dict[p1][p2].append((date, winner == p1))

            # add p2 to the dict
            if p2 not in win_loss_dict:
                win_loss_dict[p2] = {}

            if p1 not in win_loss_dict[p2]:
                win_loss_dict[p2][p1] = []

            win_loss_dict[p2][p1].append((date, winner == p2))

        ranks = get_ranks(win_loss_dict)

        tag_rank_map = {}
        for i, x in enumerate(ranks):
            points, player = x
            rank = len(ranks) - i

            sql = "INSERT INTO ranks (scene, player, rank, points, date) VALUES ('{scene}', '{player}', '{rank}', '{points}', '{recent_date}');"
            args = {'scene': scene, 'player': player, 'rank': rank, 'points': points, 'recent_date': recent_date}
            self.db.exec(sql, args)

            # Only count this player if this is the scene he/she belongs to
            sql = "SELECT scene FROM players WHERE tag='{player}';"
            args = {'player': player}
            res = self.db.exec(sql, args)

            if len(res) == 0 or res[0][0] == scene:
                # Also create a list to update the player web
                map = {'rank':rank, 'total_ranked':len(ranks)}
                tag_rank_map[player] = map

        player_web.update_ranks(tag_rank_map)