Get artist name - python

I'm trying to get the names of my top 3 artists of last week with pylast (https://github.com/pylast/pylast) but I run into an error or get I get None as a result and I don't see what I'm doing wrong. pylast is a Python interface to Last.fm.
My code:
import pylast
API_KEY = ""
API_SECRET = ""
username = ""
password_hash = pylast.md5("")
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash)
user = network.get_authenticated_user();
weekly_artists = user.get_weekly_artist_charts();
# Keep the first three artists.
del weekly_artists[3:]
# Print the artist name and number of songs(weight).
for weekly_artist in weekly_artists:
artist,weight = weekly_artist
print (artist.get_name())
print (artist.get_correction())
artist.get_name() returns
None
artist.get_correction() returns
Traceback (most recent call last):
File "G:\projects\python\lastfm_weekly\lastfm-weekly.py", line 28, in <module>
print (artist.get_correction())
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 1585, in get_correction
self._request(self.ws_prefix + ".getCorrection"), "name")
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 1029, in _request
return _Request(self.network, method_name, params).execute(cacheable)
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 744, in __init__
network._get_ws_auth()
AttributeError: 'str' object has no attribute '_get_ws_auth'
What am I doing wrong?

Here is a quick and dirty solution, i'm sure someone will provide something better but i just installed the package to test and it works.
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)
artists = network.get_top_artists()
del artists[:3]
for i in artists:
artist, weight = i
print('Artist = {}. Weight = {}'.format(artist, weight))
I'm not really familiar with the package, I just installed it to help out with this but I do wonder what "get_name()" and "get_correction()" are as they're not in your provided code.
If they're not functions you created / are defined within your code then I'd look there for the problem.
Also, you're authenticating the user but the documentation explicitly states you don't need to unless you're writing data.

Related

How can I query the bittensor network using btcli?

btcli query
Enter wallet name (default): my-wallet-name
Enter hotkey name (default): my-hotkey
Enter uids to query (All): 18
Note that my-wallet-name, my-hotkey where actually correct names. My wallet with one of my hotkeys. And I decided to query the UID 18.
But btcli is returning an error with no specific message
AttributeError: 'Dendrite' object has no attribute 'forward_text'
Exception ignored in: <function Dendrite.__del__ at 0x7f5655e3adc0>
Traceback (most recent call last):
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_dendrite/dendrite_impl.py", line 107, in __del__
bittensor.logging.success('Dendrite Deleted', sufix = '')
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 341, in success
cls()
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 73, in __new__
config = logging.config()
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 127, in config
parser = argparse.ArgumentParser()
File "/usr/lib/python3.8/argparse.py", line 1672, in __init__
prog = _os.path.basename(_sys.argv[0])
TypeError: 'NoneType' object is not subscriptable
What does this means?
How can I query an UID correctly?
I have try to look for UIDs to query but the tool does not give me any.
I was expecting a semantic error or a way to look for a UID i can query but not a TypeError.
It appears that command is broken and should be removed.
I opened an issue for you here: https://github.com/opentensor/bittensor/issues/1085
You can use the python API like:
import bittensor
UID: int = 18
subtensor = bittensor.subtensor( network="nakamoto" )
forward_text = "testing out querying the network"
wallet = bittensor.wallet( name = "my-wallet-name", hotkey = "my-hotkey" )
dend = bittensor.dendrite( wallet = wallet )
neuron = subtensor.neuron_for_uid( UID )
endpoint = bittensor.endpoint.from_neuron( neuron )
response_codes, times, query_responses = dend.generate(endpoint, forward_text, num_to_generate=64)
response_code_text = response_codes[0]
query_response = query_responses[0]

How to fill a column of type 'multi-select' in notion-py(Notion API)?

I am trying to create a telegram-bot that will create notes in notion, for this I use:
notion-py
pyTelegramBotAPI
then I connected my notion by adding token_v2, and then receiving data about the note that I want to save in notion, at the end I save a note on notion like this:
def make_notion_row():
collection_view = client.get_collection_view(list_url[temporary_category]) #take collection
print(temporary_category)
print(temporary_name)
print(temporary_link)
print(temporary_subcategory)
print(temporary_tag)
row = collection_view.collection.add_row() #make row
row.ssylka = temporary_link #this is link
row.nazvanie_zametki = temporary_name #this is name
if temporary_category == 0: #this is category, where do I want to save the note
row.stil = temporary_subcategory #this is subcategory
tags = temporary_tag.split(',') #temporary_tags is text that has many tags separated by commas. I want to get these tags as an array
for tag_one in tags:
**add_new_multi_select_value("Теги", tag_one): #"Теги" is "Tag column" in russian. in this situation, tag_one takes on the following values: ['my_hero_academia','midoria']**
else:
row.kategoria = temporary_subcategory
this script works, but the problem is filling in the Tags column which is of type multi-select.
Since in the readme 'notion-py', nothing was said about filling in the 'multi-select', therefore
I used the bkiac function:https://github.com/jamalex/notion-py/issues/51
here is the slightly modified by me ​function:
art_tags = ['ryuko_matoi', 'kill_la_kill']
def add_new_multi_select_value(prop, value, style=None):
​global temporary_prop_schema
​if style is None:
​style = choice(art_tags)
​collection_schema = collection_view.collection.get(["schema"])
​prop_schema = next(
​(v for k, v in collection_schema.items() if v["name"] == prop), None
​)
​if not prop_schema:
​raise ValueError(
​f'"{prop}" property does not exist on the collection!'
​)
​if prop_schema["type"] != "multi_select":
​raise ValueError(f'"{prop}" is not a multi select property!')
​dupe = next(
​(o for o in prop_schema["options"] if o["value"] == value), None
​)
​if dupe:
​raise ValueError(f'"{value}" already exists in the schema!')
​temporary_prop_schema = prop_schema
​prop_schema["options"].append(
​{"id": str(uuid1()), "value": value, "style": style}
​)
​collection.set("schema", collection_schema)`
But it turned out that this function does not work, and gives the following error:
add_new_multi_select_value("Теги","my_hero_academia)
Traceback (most recent call last):
​File "<pyshell#4>", line 1, in <module>
​add_new_multi_select_value("Теги","my_hero_academia)
​File "C:\Users\laere\OneDrive\Documents\Programming\Other\notion-bot\program\notionbot\test.py", line 53, in add_new_multi_select_value
​collection.set("schema", collection_schema)
​File "C:\Users\laere\AppData\Local\Programs\Python\Python39-32\lib\site-packages\notion\records.py", line 115, in set
​self._client.submit_transaction(
​File "C:\Users\laere\AppData\Local\Programs\Python\Python39-32\lib\site-packages\notion\client.py", line 290, in submit_transaction
​self.post("submitTransaction", data)
​File "C:\Users\laere\AppData\Local\Programs\Python\Python39-32\lib\site-packages\notion\client.py", line 260, in post
​raise HTTPError(
requests.exceptions.HTTPError: Unsaved transactions: Not allowed to edit column: schema
this is my table image: link
this is my telegram chatting to bot: link
Honestly, I don’t know how to solve this problem, the question is how to fill a column of type 'multi-select'?
I solved this problem using this command
row.set_property("Категория", temporary_subcategory)
and do not be afraid if there is an error "options ..." this can be solved by adding settings for the 'multi-select' field.

Attribute Error in python. Object has no attribute

This code is part of a bigger program that uses the google Sheets API to get data from a cloud database (not really relevant, but a bit of context never hurt!)
I have this black of code in one python file named 'oop.py'
class SetupClassroom:
def __init__(self, arraynumber='undefined', tkroot='undefined'):
self.arraynumber = arraynumber
self.tkroot = tkroot
def setarraynumber(self, number):
from GUI_Stage_3 import showclassroom
self.arraynumber = number
print ('set array number:', number)
showclassroom()
def settkroot(self, tkrootinput):
self.tkroot = tkrootinput
self.tkroot has been assigned by another part of the code. This bit works, as I have already tested that it is being assigned, however, when I call 'self.tkroot' in another another file like this
def showclassroom():
from oop import SetupClassroom
username = current_user.username
classnumber = getnumberofuserclassrooms(username)
if SetupClassroom.arraynumber > classnumber:
errorwindow('you are not enrolled in that many classrooms!')
else:
classtoget = SetupClassroom.arraynumber
print('classtoget:', classtoget)
root = SetupClassroom.tkroot
name_label = Label(root, text=classtoget)
getclassroom(username, classtoget)
SetupClassroom = SetupClassroom
I get this error
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/GUI_Stage2_better.py", line 176, in <lambda>
l0 = ttk.Button(teacher_root, text=button0text, command=lambda: (SetupClassroom.setarraynumber(SetupClassroom, number=button0text), SetupClassroom.settkroot(SetupClassroom, 'teacher_root')))
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/oop.py", line 99, in setarraynumber
showclassroom()
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/GUI_Stage_3.py", line 29, in showclassroom
root = SetupClassroom.tkroot
AttributeError: type object 'SetupClassroom' has no attribute 'tkroot'
I tried setting it up in the python console and it worked, so I have no idea what the problem is.
If anyone could help, it would be very much appreciated
Thanks!
John
You should create an instance of class, it will create the attribute in __init__, self.tkroot is the attribute of instance not class:
setupClassroom = SetupClassroom()
print(setupClassroom.tkroot)
Hope that will help you.

Django create_or_update model attribute command works fine but update fails

I am trying to write a CSV helper that reads the CSV file and updates or creates fields in the model. The create_or_update query is working fine, but it is only creating not updating. On changing the create_or_update to update it throws an error. The code of the CSV helper is :
def insert_books_from_dictionary(data):
category, created = Category.objects.update_or_create(name=data['category'])
sub_category = None
if data['sub_category'].decode('utf-8') != '':
sub_category, created = SubCategory.objects.update_or_create(name=data['sub_category'], category=category)
publisher, created = Publisher.objects.update_or_create(name=data['publishers'])
# convert strings to float
# ToDo : Fix constraints and create a function
# to handle data check and conversion
try:
price = float(data['mrp_price'])
except ValueError:
price = 0.0
pass
try:
pages = float(data['pages'])
except ValueError:
pages = None
pass
isbn_13_str = str(data['isbn_13'])
isbn_10_str = str(data['isbn_10'])
image_url_str = str(data['image_url'])
binding = 1 if data['binding'] == 'Hardboard' else 2
book, created = Book.objects.update(title=data['title'],description=data['description'], pages=pages, binding=binding, price=price, category=category,sub_category=sub_category, edition_and_year=data['edition_and_year'],
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
book.publishers.add(publisher)
authors = re.split(",", data['authors'].decode('utf-8'))
for author in authors:
author, created = Author.objects.update_or_create(name=author.strip())
book.authors.add(author)
return dict(book_id=book.id)
It throws the following error:
Traceback (most recent call last):
File "common/util/upload.py", line 18, in <module>
uploadbooks = book_upload(old_file, newfile)
File "common/util/upload.py", line 12, in book_upload
insert_seller_books_from_dictionary(req_data)
File "/home/subhajit/textnook/common/util/csv_helper.py", line 132, in insert_seller_books_from_dictionary
book_id = insert_books_from_dictionary(data)
File "/home/subhajit/textnook/common/util/csv_helper.py", line 167, in insert_books_from_dictionary
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
TypeError: 'long' object is not iterable
On changing update to create the error is no more. How do i resolve this issue?
in
book, created = Book.objects.update(title=data['title'],description=data['description'], pages=pages, binding=binding, price=price, category=category,sub_category=sub_category, edition_and_year=data['edition_and_year'],
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
you are using update, not update_or_create
Book.objects.update updates only and returns the number of rows affected, which is the 'long' object is not iterable python complains about, since it has to assign its elements to the tuple book, created

I can't access an activity on Strava API using Python

I'm trying to access data for an individual ride using the Strava API but when I add the ride ID I get an error. Essentially I'd like to be able to access things like distance and times and see this as the first step but I can't pull back much information on a single ride. Here is the code and error:
from stravalib.client import Client
client = Client(access_token='My token here')
athlete = client.get_athlete() # Get John's full athlete record
print("Hello, {}. I know your email is {}".format(athlete.firstname, athlete.email))
# "Hello, John. I know your email is john#example.com"
activities = client.get_activities(limit=10)
assert len(list(activities)) == 10
#View activities
for x in activities:
print (x)
#<Activity id=270828720 name='Evening Ride' resource_state=2>
#<Activity id=270590277 name='Morning Ride' resource_state=2>
#<Activity id=270577804 name='Evening Ride' resource_state=2>
#<Activity id=270137878 name='Morning Ride' resource_state=2>
a = client.get_activity(270137878)
#Traceback (most recent call last):
# File "<ipython-input-22-a7e56786804d>", line 1, in <module>
# a = client.get_activity(270137878)
# File "C:\Anaconda3\lib\site-packages\stravalib\client.py", line 423, in get_activity
# return model.Activity.deserialize(raw, bind_client=self)
# File "C:\Anaconda3\lib\site-packages\stravalib\model.py", line 106, in deserialize
# o.from_dict(v)
# File "C:\Anaconda3\lib\site-packages\stravalib\model.py", line 41, in from_dict
# raise AttributeError("Error setting attribute {0} on entity {1}, value: {2!r}".format(k, self, v))
#AttributeError: Error setting attribute photos on entity <Activity id=270137878 name=None resource_state=3>, value: {'primary': None, 'count': 0}
Did you get an answer to this? The issue was a change to the Strava API V3 which added photos, and stravalib hadnt been updated to reflect this -
https://github.com/hozn/stravalib/issues/45
Its been fixed now

Categories

Resources