Get track details from stream using gracenote python wrapper - gracenote

I'm using I'm using the dev version of the python wrapper for the gracenote gnsdk (gnsdk-3.06.0.1241o-20130927/wrappers/gnsdk_python/samples/musicid_stream/main.py) to identify 15 seconds of music, which seems to be working pretty well in terms of recognising the album the song is from.
Is it possible to use the data returned to get the artist, song, and other information, rather than just the album title?

I hope the snippet below is helpful. It gives a taste of some of the data that is available. You can also check the type() of any object returned from a query, and any objects down the hierarchy, and then find that type in gnsdk.py to see all of the methods that it supports.
Not every field will be populated for each album or track.
Enjoy.
Damon
def display_track_info(track):
print " title: %s" % track.title().display()
print " number: %s" % track.track_number()
print " artist: %s" % track.artist().name().display()
print " genre lvl 1: %s" % track.genre().level1()
print " genre lvl 2: %s" % track.genre().level2()
print " genre lvl 3: %s" % track.genre().level3()
print " mood lvl 1: %s" % track.mood().level1()
print " mood lvl 2: %s" % track.mood().level2()
def display_album_info(album):
print " title: %s" % album.title().display()
print " artist: %s" % album.artist().name().display()
tracks = album.tracks_matched()
print " Matched %d tracks" % tracks.count()
iterable = tracks.at(0)
for index in range(tracks.count()):
print " Track %d:" % (index+1)
track = iterable.next()
display_track_info(track)

Related

How to error check a function containing a SQL query with the placeholder %s

I am working on a project for school and run into a crossroad. I have a bunch of queries in a python script that a user can search when running the script. A couple of these function are using %s as a placeholder so that the user can enter a value.
However, I want to check that what they enter is actually in my database. For instance, if you ask a user for a movie genre, it should produce an error if they enter something that is not in my tables.
I have spent a few days trying to find a way to do it, with no luck. I am not the greatest with functions, and I get things mixed up some times.
To simplify things I copied one of my queries requiring user input for testing. I thought I had come up with a solution on how to error check, but no luck. I have pasted the code below. If you know what I am missing, your help would be much appreciated.
#!/usr/bin/python36
#Modules
############################
import psycopg2
import sys
import os
#Open Database
############################
global cursor
#def OpenDatabase():
try:
connection = psycopg2.connect(database='Blockbuster36', user='dbadmin')
cursor = connection.cursor()
except psycopg2.DatabaseError:
print("No connection to database.")
sys.exit(1)
#Functions
###########################
def Show_Tuples():
tuple = cursor.fetchone()
while tuple != None:
print(tuple)
tuple = cursor.fetchone()
#3) Display all films of a certain genre
def Qry3_Film_of_Genre(Genre_Choice):
Qry3 = '''select Film_Title, Genre_Name from Film
join Film_Genre
on Film.Film_ID = Film_Genre.Film_ID
join Genre
on Film_Genre.Genre_ID = Genre.Genre_ID
where Genre_Name = %s;'''
cursor.execute(Qry3, (Genre_Choice,))
Show_Tuples()
def Qry3_Error_Check(Genre_Choice):
try:
Qry3_ec = "select Genre_ID, Genre_Name from Genre where Genre_Name = %s;"
cursor.execute(Qry3_ec, (Genre_Choice,))
results = cursor.fetchone()
if results[0] > 0:
print()
Qry3_Film_of_Genre(Genre_Choice)
# else:
elif results[0] == None:
print("This Genre does not exist")
Genre_Choice = input("Please enter the Genre name to filter movies by: ")
except psycopg2.Error as query_issue:
print("Something wrong with the query", query_issue)
except Exception as unkown:
print("Error: Something else went wrong")
print("Here is the issue: ", unkown)
#Main Code
##########################
Genre_Choice = input("Please enter the Genre name to filter movies by: ")
Check_Genre = Qry3_Error_Check(Genre_Choice)
#print("Function Return: ", Check_Genre)
#print()
#print(Check_Genre)
#if Check_Genre == None:
# print("This Genre does not exist")
# Genre_Choice = input("Please enter the Genre name to filter movies by: ")
# Check_Genre = Qry3_Error_Check(Genre_Choice)
#elif Check_Genre != None:
# Qry3_Film_of_Genre(Genre_Choice)
#while Check_Genre != Genre_Choice:
# print("This Genre does not exist")
# Genre_Choice = input("Please enter the Genre name to filter movies by: ")
# Check_Genre = Qry3_Error_Check(Genre_Choice)
#if Check_Genre == None:
# Qry3_Film_of_Genre(Genre_Choice)
#Close Cursor and Database
###################################
cursor.close()
connection.close()
Essentially I want the error message to keep printing, along with entering another genre name, until a valid genre is entered. Right now it keeps saying it is wrong even if enter a valid genre name and get output with the Qry3_Error_Check function.
Once the user has entered a valid genre name, based on the error-checking function query, then the original query will appear.
I have made some progress, entering a valid genre now works. However, when entering an invalid genre name it jumps to the general except and prints the error "NoneType object is not subscriptable." Obviously, there are no rows that match, thus the NoneType error. However, it should re-prompt the user in the elif statement above. What do enter as an elif statement so that the user is re-prompted for a valid genre name?
Note: I commented out the bulk of my main code for now.
If you want to check specifically for SQL errors, you can have a separate except block for them. Also, its usually (but not always) a bad idea to use exceptions for control flow.
Something like below (I have not tested this) is probably close to what you need.
try:
Qry3_ec = "select Genre_ID, Genre_Name from Genre where Genre_Name = %s;"
cursor.execute(Qry3_ec, (Genre_Choice,))
results = cursor.fetchall()
if results.count > 0:
print(results)
else:
print("Nothing found!")
except psycopg2.Error as e:
print("Something wrong with the query")
print(e)
except Exception as e
print("Something else went wrong")
print(e)
Good luck with your project. :)

Matching dict key to text file and returning Test Pass/fail

I'm a novice at Python, and am currently working on a small test case assignment where I am to find and match the dictionary keys to a small text file, and see if the keys are present in the text file.
As follows, the dictionary goes:
dict = {"description, translation": "test_translation(serial,",
"unit": "test_unit(",}
The text in text file, henceforth called "requirement.txt" as follows:
The description shall display the translation of XXX.
The unit shall be hidden.
The value is read from the file "version.txt".
To the key, I am to find and match if they are present or absent - a match should return a "test pass", no match would return a skip.
Keys from dictionary are to be sorted to a list, then iterated and matched to text. (Values from dictionary are to be sorted to a seperate list and iterated over a seperate file, to which I shall not delve into it here.)
This is the code that I currently have (and stuck):
list = sorted(key_words.keys(), key=lambda d: d[0])
with open('C:/Users-------/requirement.txt', 'r') as outfile:
lines = outfile.readlines()
for line in lines:
line = line.strip()
if line == '':
continue
line_strings = line.split(' ')
for word in list:
if word in line:
print("Test Pass")
print(word)
break
else:
print("Test Fail")
print(line + "\n")
Result currently obtained:
Test Fail
Test Pass
display
The description shall display the translation of XXX.
Test Fail
Test Fail
Test Fail
Test Pass
unit
The unit shall be hidden.
Test Fail
Test Fail
Test Fail
Test Fail
The value is read from the file "version.txt".
Using the current code which I have, (and I am stuck), running the code returned multiple times of "Test pass" and "Test fail", suggesting that the keys are iterated multiple times over each line and the results returned for each multiple iteration.
I am stuck at two fronts:
After seperating the key into a list, how to order them in the sequence of "description, translation", "unit)?
How to modify the code so as to ensure that result is returned once as "Test pass" or "test fail"
Results should ideally return in the following format:
Ideal outcome:
('Text:', "The description shall display the translation of XXX.
('Key:', 'description, translation')
Test Pass
('Text:', 'The unit shall be hidden.')
('Key:', 'unit')
Test Pass
('Text:', 'The value is read from the file "version.txt".')
('Key:', (none))
Test Fail
For your kind enlightenment please, thank you!
Try with this:
list = sorted(key_words.keys(), key=lambda d: d[0])
with open('C:/Users-------/requirement.txt', 'r') as outfile:
lines = outfile.readlines()
for line in lines:
line = line.strip()
if line == '':
continue
# Create an empty list which will contain all the word that match
words_found = []
for word in list:
# if the word match then add it to the list words_found
if word in line:
words_found.append(word)
print("(\'Text:\',\"{}\"")' ".format(line))
print("(\'Keys:\',\"{}\"")' ".format(words_found))
# if the list of words found it's not empty then the test passed
if(words_found):
print("Test Passed")
else:
print("Test Failed")
the idea is to create a list of the words founds and then print them all
I'm using the format Operation and you can find a guide on how to use it here. And the line if(words_found): check if the list is empty.
Additional Notes
In this case, you won't need it but if you wanted to solve only the second point you can use the for else statement as explained in the docs
4.4 break and continue Statements, and else Clauses on Loops
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
Reducing by one tab the indentation the else of your if statement it became the else of the for statement so it will be executed only if the for never had a break the problem is solved.
list = sorted(key_words.keys(), key=lambda d: d[0])
with open('C:/Users-------/requirement.txt', 'r') as outfile:
lines = outfile.readlines()
for line in lines:
line = line.strip()
if line == '':
continue
line_strings = line.split(' ')
for word in list:
if word in line:
print(word)
print("Test Pass")
break
else:
print("Test Fail")
print(line + "\n")
Edit
To split the key into description and translation we just have to split the two word at the comma with the builtin function split
list = sorted(key_words.keys(), key=lambda d: d[0])
with open('C:/Users-------/requirement.txt', 'r') as outfile:
lines = outfile.readlines()
for line in lines:
line = line.strip()
if line == '':
continue
# Create an empty list which will contain all the word that match
words_found = []
for word in list:
description, translation = word.split(",")
# if the word match then add it to the list words_found
if description in line:
words_found.append(description)
print("(\'Text:\',\"{}\"")' ".format(line))
print("(\'Keys:\',\"{}\"")' ".format(words_found))
# if the list of words found it's not empty then the test passed
if(words_found):
print("Test Passed")
else:
print("Test Failed")

How to get max date time value in data and get respective data

The input looks like:
9999993612,10/Feb/2016:19:04:16
9999993612,10/Feb/2016:19:04:15
9999993612,10/Feb/2016:19:04:09
9999993612,10/Feb/2016:01:31:47
9999993612,10/Feb/2016:01:31:46
9999993612,10/Feb/2016:01:31:43
We need output.
9999993612,10/Feb/2016:19:04:16
using linux command.
**** It's working fine**********
awk 'BEGIN{FS=","; print "NO time"} NR!=1 {a[$1]++;b[$1]=$2}END{for (i in a) printf("%s %s \n" ,i, b[i])} ' FILENAME

String Formatting with python3

Ok so basically I have the following code:
name=raw_input("What is your name?")
quest=raw_input("What is your quest?")
print ("As so your name is %s, your quest is %s ") %(name,quest)
This runs perfection in Python 2.7.9
I have tried to run this same exact code in Python 3.4.2 and it does't work (figured), so I modified it to this thinking it would work:
name=input("What is your name?")
quest=input("What is your quest?")
print ("As so your name is %s, your quest is %s ") %(name,quest)
And this:
name=input("What is your name?")
quest=input("What is your quest?")
print ("As so your name is {}, your quest is {} ") .format(name,quest)
And of course that didn't work either, I have searched for over an hour now multiple sites, what am I missing here? How do you do this in Python 3.4.2, all I keep getting is sites and answers showing you the first way (I listed), and all it does is work on the older version python 2.
Thanks
print is a function in Python 3. Thus, doing print(...).format(...) is effectively trying to format the return value of the print() call, which is None.
Call .format() on the string you want formatted instead:
print("As so your name is {}, your quest is {} ".format(name,quest))
Your modified code was nearly right, you just needed to move a bracket to apply the % operator to the string instead of the print function result.
So change this:
print ("As so your name is %s, your quest is %s ") % (name, quest)
to this:
print ("As so your name is %s, your quest is %s " % (name, quest))
and it runs fine in Python 3.

Get words out of a file in Ada

I have a folder with files containing some text. I am trying to go through all the files one after the other, and count how many times we see every word in the text files.
I know how to open the file, but once I'm in the file I don't know how to read each word one after the other, and go to the next word.
If anyone has some ideas to guide me it'd be great.
Read the file a line at a time into a string using Get_Line, then break the line up into the individual words.
Here's one way of doing it, I needed some playtime with the containers.
Using streams is still the best solution for your problem, given the multiple files.
Text_Search.ads
Pragma Ada_2012;
With
Ada.Containers.Indefinite_Ordered_Maps;
Package Text_Search with Elaborate_Body is
Text : Constant String :=
ASCII.HT &
"We hold these truths to be self-evident, that all men are created " &
"equal, that they are endowed by their Creator with certain unalienable "&
"Rights, that among these are Life, Liberty and the pursuit of " &
"Happiness.--That to secure these rights, Governments are instituted " &
"among Men, deriving their just powers from the consent of the governed" &
", --That whenever any Form of Government becomes destructive of these " &
"ends, it is the Right of the People to alter or to abolish it, and to " &
"institute new Government, laying its foundation on such principles " &
"and organizing its powers in such form, as to them shall seem most " &
"likely to effect their Safety and Happiness. Prudence, indeed, will " &
"dictate that Governments long established should not be changed for " &
"light and transient causes; and accordingly all experience hath shewn, "&
"that mankind are more disposed to suffer, while evils are sufferable, " &
"than to right themselves by abolishing the forms to which they are " &
"accustomed. But when a long train of abuses and usurpations, pursuing " &
"invariably the same Object evinces a design to reduce them under " &
"absolute Despotism, it is their right, it is their duty, to throw off " &
"such Government, and to provide new Guards for their future security." &
"now the necessity which constrains them to alter their former Systems " &
"of Government. The history of the present King of Great Britain is a " &
"history of repeated injuries and usurpations, all having in direct " &
"object the establishment of an absolute Tyranny over these States. To " &
"prove this, let Facts be submitted to a candid world.";
Package Word_List is New Ada.Containers.Indefinite_Ordered_Maps(
Key_Type => String,
Element_Type => Positive
);
Function Create_Map( Words : String ) Return Word_List.Map;
Words : Word_List.map;
End Text_Search;
Text_Search.adb
Package Body Text_Search is
Function Create_Map( Words : String ) Return Word_List.Map is
Delimiters : Array (Character) of Boolean:=
('.' | ' ' | '-' | ',' | ';' | ASCII.HT => True, Others => False);
Index, Start, Stop : Positive := Words'First;
begin
Return Result : Word_List.Map do
Parse:
loop
Start:= Index;
-- Ignore initial delimeters.
while Delimiters(Words(Start)) loop
Start:= 1+Start;
end loop;
Stop:= Start;
while not Delimiters(Words(Stop)) loop
Stop:= 1+Stop;
end loop;
declare
-- Because we stop *on* a delimiter we mustn't include it.
Subtype R is Positive Range Start..Stop-1;
Substring : String renames Words(R);
begin
-- if it's there, increment; otherwise add it.
if Result.Contains( Substring ) then
Result(Substring):= 1 + Result(Substring);
else
Result.Include( Key => substring, New_Item => 1 );
end if;
end;
Index:= Stop + 1;
end loop parse;
exception
When Constraint_Error => null; -- we run until our index fails.
end return;
End Create_Map;
Begin
Words:= Create_Map( Words => Text );
End Text_Search;
Test.adb
Pragma Ada_2012;
Pragma Assertion_Policy( Check );
With
Text_Search,
Ada.Text_IO;
Procedure Test is
Procedure Print_Word( Item : Text_Search.Word_List.Cursor ) is
use Text_Search.Word_List;
Word : String renames Key(Item);
Word_Column : String(1..20) := (others => ' ');
begin
Word_Column(1..Word'Length+1):= Word & ':';
Ada.Text_IO.Put_Line( Word_Column & Positive'Image(Element(Item)) );
End Print_Word;
Begin
Text_Search.Words.Iterate( Print_Word'Access );
End Test;
Instead of going by individual words, you could read the file a line at a time into a string using Get_Line, and then use regular expressions: Regular Expressions in Ada?
If you're using Ada 2012 here's how I would recommend doing it:
With Ada.Containers.Indefinite_Ordered_Maps.
Instantiate a Map with String as key, and Positive as Key;
Grab the string; I'd use either a single string or stream-processing.
Break the input-text into words; this can be done on-the-fly if you use streams.
When you get a word (from #4) add it to your map if it doesn't exist, otherwise increment the element.
When you are finished, just run a For Element of WORD_MAP Loop that prints the string & count.
There's several ways you could handle strings in #3:
Perfectly sized via recursive function call [terminating on a non-word character or the end of input].
Unbounded_String
Vector (Positive, Character) -- append for valid characters, convert to array [string] and add to the map when an invalid-character [or the end of input] is encountered -- working variable.
Not Null Access String working variable.

Resources