Best Python code snippet using avocado_python
flaskapp.py
Source:flaskapp.py  
...153def analytics():154    user = session.get('user')155    if get_total_num_likes(user) < 5:156        return flask.render_template('analytics.html',artist='', tag='', message = 'Add more likes for analytics!') 157    top_tag = get_top_tag(session.get('user'))158    top_artist = get_top_artist(session.get('user'))159    return flask.render_template('analytics.html',artist=top_artist, tag=top_tag, message = '')160@app.route('/logout')161def logout():162    session['user'] = None163    return redirect(url_for('index'))164def get_liked_songs():165    cursor = mydb.cursor()166    sql = "SELECT SongId FROM Likes WHERE Username = %s"167    val = (session['user'],)168    message = ""169    cursor.execute(sql,val)170    result = cursor.fetchall()171    songs = []172    for r in result: 173        sql = "SELECT * FROM Songs WHERE SongId = %s"174        cursor.execute(sql,r)175        result = cursor.fetchone()176        songs.append(result)177    cursor.close178    return songs179    180def remove_like_from_db(title, artist):181    cursor = mydb.cursor()182    sql = "SELECT SongId FROM Songs WHERE Title = %s AND Artist = %s"183    val = (title, artist)184    cursor.execute(sql, val)185    result = cursor.fetchone()186    sql = "DELETE FROM Likes WHERE SongId = %s AND Username = %s"187    val = (result[0], session.get('user'))188    cursor.execute(sql, val)189    mydb.commit()190    cursor.close()191    192def add_like(title, artist):193    cursor = mydb.cursor()194    sql = "SELECT * FROM Likes l, (SELECT SongId FROM Songs WHERE Title = %s AND Artist = %s) temp WHERE l.SongId = temp.SongId AND l.Username = %s"195    val = (title, artist, session.get('user'))196    cursor.execute(sql,val)197    result = cursor.fetchall()198    if len(result) > 0:199        return "You have already liked this song!"200    url = "{last_fm}&artist={artist}&track={title}&format=json".format(last_fm = LAST_FM, artist = artist, title = title)201    r = requests.get(url)202    resp = r.json()203    if "error" in resp:204        return "Sorry, we couldn't find that song!"205    song_metadata = get_metadata_from_resp(resp)206    song_id = add_song_to_db(song_metadata)207    add_like_to_db(song_id)208    message = "Added {song} by {artist}".format(song = resp["track"]["name"], artist = resp["track"]["artist"]["name"])209    return message210def get_metadata_from_resp(resp):211    name = resp["track"]["name"]212    artist = resp["track"]["artist"]["name"]213    if len(resp["track"]["toptags"]["tag"]) < 1:214        tag = None215    else:216        tag = resp["track"]["toptags"]["tag"][0]["name"]217    return (name, artist, tag)218def add_song_to_db(metadata):219    cursor = mydb.cursor()220    sql = "SELECT SongId FROM Songs WHERE Title = %s AND Artist = %s"221    val = (metadata[0], metadata[1])222    cursor.execute(sql, val)223    result = cursor.fetchone()224    cursor.reset()225    if result != None:226        return result[0]227    sql = "INSERT INTO Songs (Title,Artist,Tag) VALUES (%s, %s, %s)"228    cursor.execute(sql, metadata)229    song_id = cursor.lastrowid230    mydb.commit()231    cursor.close()232    return song_id233def add_like_to_db(song_id):234    cursor = mydb.cursor()235    sql = "INSERT IGNORE INTO Likes (SongId, Username) VALUES (%s,%s)"236    val = (song_id, session.get('user'))237    cursor.execute(sql, val)238    mydb.commit()239    cursor.close()240def update_tag(title, artist, new_tag):241    #TODO update tag not globally242    cursor = mydb.cursor()243    sql = "SELECT SongId FROM Songs WHERE Title = %s AND Artist = %s"244    val = (title, artist)245    cursor.execute(sql, val)246    result = cursor.fetchone()247    user = session.get('user')248    if result == None:249        return "Sorry, you haven't liked that song!" 250    song = result[0]251    sql = "SELECT * FROM Likes WHERE SongId = %s AND Username = %s"252    val = (song, user)    253    cursor.execute(sql, val)254    like_result = cursor.fetchone()255    if like_result == None:256        return "Sorry, you haven't liked that song!" 257    sql = "SELECT * FROM Tags WHERE SongId = %s AND Username = %s"258    val = (song, user)259    cursor.execute(sql,val)260    result = cursor.fetchone()261    if result == None:262        sql = "INSERT INTO Tags(Username, SongId, Tag) VALUES(%s,%s,%s)"263        val = (user, song, new_tag)264        cursor.execute(sql,val)265        mydb.commit()266        cursor.close()267    else:268        sql = "UPDATE Tags SET Tag = %s WHERE SongId = %s AND Username = %s"269        val = (new_tag, song, user)270        cursor.execute(sql,val)271        mydb.commit()272        cursor.close() 273    message = "Changed tag for {title} by {artist} to {new}".format(title=title, artist=artist, new=new_tag)274    return message275def get_song_from_id(id_):276   cursor = mydb.cursor() 277   sql = "SELECT Title, Artist FROM Songs WHERE SongId = %s"278   val = (id_,)279   cursor.execute(sql,val)280   result = cursor.fetchone() 281   cursor.close()282   return result283def generate_recommendations(user_id):284    cursor = mydb.cursor()285    sql = "SELECT u.Username, COUNT(SongId) FROM Likes l, Users u WHERE l.Username = %s AND SongId IN (SELECT SongId FROM Likes WHERE Likes.Username = u.Username AND Likes.Username <> %s) GROUP BY u.Username ORDER BY COUNT(SongId) DESC LIMIT 10;"286    val = (user_id, user_id)287    cursor.execute(sql,val)288    result = cursor.fetchall()289    if len(result) == 0:290        top_tag = get_top_tag(user_id)291        sql = "SELECT DISTINCT SongId FROM Songs WHERE tag = %s AND SongId NOT IN (SELECT SongId FROM Likes WHERE Username = %s) LIMIT 10"292        val = (top_tag,user_id)293        cursor.execute(sql,val)294        result = cursor.fetchall()295        if len(result) == 0:296            random_song_sql = "SELECT SongId FROM Songs ORDER BY RAND() LIMIT 10"297            cursor.execute(random_song_sql)298            result = cursor.fetchall()299        session['recs'] = result300        return301    scores = {}302    for user in result:303        scores[user[0]] = generate_similarity_score(user_id, user[0], user[1])304    most_similar = get_top_three(scores)305    recs = []306    for u in most_similar:307        other_user = u[0]308        sql = "SELECT SongId FROM Likes l WHERE l.Username = %s AND l.SongId NOT IN (SELECT SongId FROM Likes WHERE Likes.Username = %s)"309        val = (other_user, user_id)310        cursor.execute(sql, val)311        result = cursor.fetchall()312        recs += result313    cursor.close()314    session['recs'] = recs315def generate_similarity_score(current_user, other_user, num_similar_songs):316    score = (num_similar_songs / get_total_num_likes(current_user)) * 100317    if get_top_tag(current_user) == get_top_tag(other_user):318        score += 5319    if get_top_artist(current_user) == get_top_artist(other_user):320        score += 10321    if abs(get_age(current_user) - get_age(other_user)) < 5:322        score += 5323    return score324def get_top_three(scores):325    count = Counter(scores)326    return count.most_common(3)327def get_top_tag(user):328    cursor = mydb.cursor()329    sql = "SELECT tag, COUNT(tag) FROM (SELECT SongId FROM Likes WHERE Username = %s) temp JOIN Songs ON temp.SongId = Songs.SongId GROUP BY tag ORDER BY COUNT(tag) DESC LIMIT 1"330    val = (user,)331    cursor.execute(sql, val)332    result = cursor.fetchone()333    return result[0]334def get_top_artist(user):335    cursor = mydb.cursor()336    sql = "SELECT Artist, COUNT(Artist) FROM (SELECT SongId FROM Likes WHERE Username = %s) temp JOIN Songs ON temp.SongId = Songs.SongId GROUP BY Artist ORDER BY COUNT(Artist) DESC LIMIT 1"337    val = (user,)338    cursor.execute(sql, val)339    result = cursor.fetchone()340    return result[0]341def get_total_num_likes(user):...KNN.py
Source:KNN.py  
...24            example_and_distance.append((example_and_tag, distance))25        closest_k = sorted(example_and_distance, key=self.get_distance_from_tuple)[:5]  # get 5 closest examples26        # extract just the tags27        closest_k_tags = [item[0][1] for item in closest_k]28        return self.get_top_tag(closest_k_tags)29    def calc_hamming_distance(self, first_example, second_example):30        """31        calculate hamming distance between two examples32        :param first_example: first example33        :param second_example: second example34        :return: hamming distance between examples35        """36        distance = 037        for feature_1, feature_2 in zip(first_example, second_example):38            if feature_1 != feature_2:39                distance += 140        return distance41    def get_distance_from_tuple(self, tagged_example_and_distance):42        """43        for sorting the elements44        :param tagged_example_and_distance: tuple of (example and tag, distance)45        :return: distance46        """47        return tagged_example_and_distance[1]48    def get_top_tag(self, tags):49        """50        Get the common tag from tags list (5 elements)51        :param tags: list52        :return: common tag53        """54        tags_counter = Counter()55        for tag in tags:56            tags_counter[tag] += 1...oldmail.py
Source:oldmail.py  
...9  sys.stderr.write(" " + sys.argv[0] + " <xml file with addresses> <subject> <file with message body>\n")10  sys.exit(code)11def get_tags(node):12  return [(t.attrib['key'], t.attrib['value']) for t in node]13def get_top_tag(node):14  return dict(get_tags(node)).get('top-tag')15cfg = configparser.ConfigParser()16cfg.read('config.ini')17server = cfg.get('E-mail', 'server')18login = cfg.get('E-mail', 'login')19from_addr = cfg.get('E-mail', 'from')20password = cfg.get('E-mail', 'password')21timeout = int(cfg.get('Timeouts', 'send-mail'))22if len(sys.argv) < 3:23  usage(1)24src_xml = sys.argv[1]25msg_file = sys.argv[2]26with open(msg_file) as f:27  msg_text = f.read()28msg_text_orig = msg_text29required_name = msg_text.find('<<NAME>>') != -130required_top_tag = msg_text.find('<<TOP-TAG>>') != -131server = smtplib.SMTP(server)32server.ehlo()33server.starttls()34server.login(login, password)35tree = ET.parse(src_xml)36root = tree.getroot()37for p in root:38  msg_text = msg_text_orig39  if not ('email' in p.attrib):40    continue41  name = p.attrib.get('name')42  top_tag = get_top_tag(p)43 44  if required_name and name == None:45    print("No name. Skipped.")46    continue47  if required_top_tag and top_tag == None:48    print("No top-tag. Skipped.")49    continue50  subject = p.attrib['title']51  if required_name:52    msg_text = re.sub('<<NAME>>', name, msg_text)53  if required_top_tag:54    msg_text = re.sub('<<TOP-TAG>>', top_tag, msg_text)55  to_addr = p.attrib['email']56  msg = "\r\n".join([...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
