why i got "rospy.ServiceException"? - python-3.x

i am working with ros about 3 month! I work on a robot controller.
i got error in ui about this client:
import sys
import rospy
from database_helper.srv import get_moves, get_movesRequest, get_movesResponse, get_move
def get_data(name: str):
"""This function can extract model names from DB"""
try:
rospy.init_node("get_moves_client")
except:
pass
rospy.wait_for_service('get_moves')
try:
moves = rospy.ServiceProxy('get_moves', get_moves)
except rospy.ServiceException as e:
print(31)
print(e)
return
id = 0
try:
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
except:
print(43)
return
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
try:
for i in range(len(wps)):
print(i)
data = {}
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
except rospy.ServiceException:
pass
print(list_of_data)
return list_of_data
this client can get data from DB and save with dict and save all dict in a list.
i most write "try/except" and i see 43 number! so i know my except is in for i in range(len(wps)):
the amazing point is, i can run this script and i get answer, but if call this script in my ui, after i using save waypoint and i try to load waypoint, i get ServiceException!
my "add_move.py" code:
from typing import List, Dict
import rospy
from database_helper.srv import add_move
from database_helper.msg import move, waypoint
def _add_move(name: str, wp: List[Dict]):
"""This Function can for send insert query for DB"""
rospy.init_node('add_move_client', anonymous=True)
rospy.wait_for_service('add_move')
_move = move()
_move.name = name
for i in range(len(wp)):
_waypoint = waypoint()
_waypoint.x = wp[i]['x_traj']
_waypoint.y = wp[i]['y_traj']
_waypoint.z = wp[i]['z_traj']
_waypoint.displacement_time_to_next_waypoint = wp[i]['time_tarj']
_waypoint.pitch = wp[i]['pich_traj']
_waypoint.roll = wp[i]['roul_traj']
_waypoint.yaw = wp[i]['ya_traj']
_waypoint.camera_focus = wp[i]['focus_camer']
_waypoint.camera_iris = wp[i]['iris_camera']
_waypoint.camera_zoom = wp[i]['zoom_camera']
_waypoint.rail_speed = wp[i]['speed_rail']
_waypoint.rail_displacement = wp[i]['disp_or_time_rail']
_waypoint.rail_direction = wp[i]['direction_rail']
_move.waypoints.append(_waypoint)
add = rospy.ServiceProxy('add_move', add_move)
return add(_move).id
if __name__ == "__main__":
from random import randint
data = {'x_traj': 12, 'y_traj': 12, 'z_traj': 33, 'time_tarj': 11,
'pich_traj': 13, 'roul_traj': 43, 'ya_traj': 21,
'focus_camer': 11, 'iris_camera': 55, 'zoom_camera': 32,
'disp_or_time_rail': 21, 'speed_rail': 109, 'direction_rail':44,
'joint1_slider': 12, 'joint2_slider': 666, 'joint3_slider': 567,
'joint4_slider': 32, 'joint5_slider': 79, 'joint6_spin': 100
}
wp = []
wp.append(data)
print(_add_move("t1", wp))
my error in terminal without "try/except" is:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 223, in deserialize_messages
msg_queue.append(data.deserialize(q))
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/srv/_get_moves.py", line 247, in deserialize
val2 = database_helper.msg.waypoint()
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/msg/_waypoint.py", line 95, in __init__
self.rail_displacement = 0
AttributeError: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 735, in receive_once
p.read_messages(b, msg_queue, sock)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 361, in read_messages
rospy.msg.deserialize_messages(b, msg_queue, self.recv_data_class, queue_size=self.queue_size, max_msgs=1, start=1) #rospy.msg
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 245, in deserialize_messages
raise genpy.DeserializationError("cannot deserialize: %s"%str(e))
genpy.message.DeserializationError: cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 522, in call
responses = transport.receive_once()
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 751, in receive_once
raise TransportException("receive_once[%s]: DeserializationError %s"%(self.name, str(e)))
rospy.exceptions.TransportException: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./benchmark_new_version_4_1.py", line 730, in get_data_query
self.wp_saver = get_data(response)
File "/home/ajax/Documents/iotive/src/gui/ui/scripts/get_moves_clinet.py", line 36, in get_data
for i in (moves(True).moves):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 442, in __call__
return self.call(*args, **kwds)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 532, in call
raise ServiceException("transport error completing service call: %s"%(str(e)))
rospy.service.ServiceException: transport error completing service call: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
what is my wrong?
srv/get_move:
int32 id
---
waypoint[] waypoints
srv/get_moves:
bool add_waypoints
---
move[] moves
msg/move:
int32 id
string name
waypoint[] waypoints
msg/waypoint:
int32 id
int32 order
float64 x
float64 y
float64 z
float64 roll
float64 pitch
float64 yaw
int32 camera_focus
int32 camera_iris
int32 camera_zoom
int32 rail_displacement
int32 rail_time
int32 rail_speed
bool rail_direction
int32 displacement_time_to_next_waypoint

So we need to remove service variables when we do not have anything else.
like this:
rospy.wait_for_service('get_moves')
moves = rospy.ServiceProxy('get_moves', get_moves)
id = 0
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
for i in range(len(wps)):
print(i)
data = {}
data['order_traj'] = wps[i].order
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
del move
del moves
print(list_of_data)
return list_of_data
I discovered this last night!

Related

An HTTP Client raised an unhandled exception: 'int' object is not callable

I'm facing the issue in two python libraries used in my code, Getting these randomly on prod on some of the pods and not all pods
Trace of The Error
Traceback (most recent call last):\n File \"/usr/local/lib/python3.10/site-packages/botocore/httpsession.py\",
line 448, in send\n
urllib_response = conn.urlopen(\n File \"/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py\",
line 703, in urlopen\n
httplib_response = self._make_request(\n File \"/usr/local/lib/python3.10/site-packages/newrelic/hooks/external_urllib3.py\",
line 32, in _nr_wrapper_make_request_\n
return wrapped(*args, **kwargs)\n
File \"/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py\",
line 386, in _make_request\n self._validate_conn(conn)\n
File \"/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py\",
line 1040, in _validate_conn\n
conn.connect()\n File \"/usr/local/lib/python3.10/site-packages/urllib3/connection.py\",
line 416, in connect\n
self.sock = ssl_wrap_socket(\n File \"/usr/local/lib/python3.10/site-packages/urllib3/util/ssl_.py\",
line 424, in ssl_wrap_socket\n context.set_alpn_protocols(ALPN_PROTOCOLS)\n
File \"/usr/local/lib/python3.10/ssl.py\",
line 566, in set_alpn_protocols\n
if len(b) == 0 or len(b) > 255:\nTypeError: 'int' object is not callable\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n
File \"/code/app/aws_utils/dynamo_db.py\", line 176, in update_multi_attributes\n
response = table.update_item(\n File \"/usr/local/lib/python3.10/site-packages/boto3/resources/factory.py\",
line 580, in do_action\n
response = action(self, *args, **kwargs)\n
File \"/usr/local/lib/python3.10/site-packages/boto3/resources/action.py\",
line 88, in __call__\n response = getattr(parent.meta.client, operation_name)(*args, **params)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/client.py\",
line 514, in _api_call\n
return self._make_api_call(operation_name, kwargs)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/client.py\",
line 921, in _make_api_call\n
http, parsed_response = self._make_request(\n
File \"/usr/local/lib/python3.10/site-packages/botocore/client.py\",
line 944, in _make_request\n
return self._endpoint.make_request(operation_model, request_dict)\n
File \"/usr/local/lib/python3.10/site-packages/newrelic/hooks/external_botocore.py\",
line 108, in _nr_endpoint_make_request_\n
result = wrapped(*args, **kwargs)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/endpoint.py\",
line 119, in make_request\n
return self._send_request(request_dict, operation_model)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/endpoint.py\",
line 231, in _send_request\n
raise exception\n File \"/usr/local/lib/python3.10/site-packages/botocore/endpoint.py\",
line 281, in _do_get_response\n
http_response = self._send(request)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/endpoint.py\",
line 377, in _send\n return self.http_session.send(request)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/httpsession.py\",
line 493, in send\n
raise HTTPClientError(error=e)\nbotocore.exceptions.HTTPClientError: An HTTP Client raised an unhandled exception: 'int' object is not callable\n",
Getting this in all dynamodb calls , adding one of the codes here, exception comes in the packages and not in the code as far as i understood
def update_multi_attributes(
self,
table,
partition_key,
sort_key,
attr_value_dict,
delete_attr=[],
):
try:
if not partition_key or not sort_key:
return None
if not attr_value_dict and len(delete_attr) == 0:
return None
if not attr_value_dict and len(delete_attr) > 0:
return self.delete_attributes(
table=table,
partition_key=partition_key,
sort_key=sort_key,
delete_attr=delete_attr,
)
expression_attribute_values = {}
expression_attribute_names = {}
update_expression = "SET "
remove_attr_expression = "REMOVE "
index = 0
attr_value_dict.pop("partition_key", None)
attr_value_dict.pop("sort_key", None)
for key, value in attr_value_dict.items():
index += 1
var_name = "#var" + str(index)
var_value_name = ":var" + str(index)
expression_attribute_values[var_value_name] = value
expression_attribute_names[var_name] = key
if index < len(attr_value_dict.keys()):
update_expression = (
update_expression + var_name + "=" + var_value_name + ","
)
else:
update_expression = (
update_expression + var_name + "=" + var_value_name
)
index = 0
for attr in delete_attr:
index += 1
var_name = "#rvar" + str(index)
expression_attribute_names[var_name] = attr
if index < len(delete_attr):
remove_attr_expression = remove_attr_expression + var_name + ","
else:
remove_attr_expression = remove_attr_expression + var_name
if len(delete_attr) > 0:
update_expression = update_expression + " " + remove_attr_expression
response = table.update_item(
Key=self.get_key(partition_key, sort_key),
ExpressionAttributeNames=expression_attribute_names,
UpdateExpression=update_expression,
ConditionExpression="attribute_exists(partition_key)"
"and attribute_exists(sort_key)",
ExpressionAttributeValues=expression_attribute_values,
)
return response
except botocore.exceptions.ClientError as e:
logger.info(
"Dynamo: Error Update MultiAttribute boto3{} error{},{}for{},{}".format(
attr_value_dict,
e,
e.response["Error"],
partition_key,
traceback.format_exc(),
)
)
except Exception as e:
logger.info(
"Dynamo: Error Update MultiAttribute {} error {} for {}, {}".format(
attr_value_dict, e, partition_key, traceback.format_exc()
)
)
return None
Adding Package versions used
urllib3-1.26.8
botocore-1.27.77
boto3-1.24.77
Had put a trace print, thinking of upgrading the urllib version but not sure if that would solve the problem, Suddenly this error started coming up, code was working fine for a month after integration.`

How do you a change guild icon from a list of randomly selected local image's?

I have been trying to make a Slash command to change the Guild's icon. The icon it changes it to is picked from a list of icons at random but I'm getting this error and have no idea what it means:
Ignoring exception in command icon_change: Traceback (most recent call last): File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 1053, in _call_with_hooks
await callback(*args) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 1135, in call_invoke_slash
await self.invoke_slash(interaction, **kwargs) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 1228, in invoke_slash
await self.callback(interaction, **kwargs) File "C:\PC Code\Python\Nextcord - Bots\utilities 2.6 - NextCord.py", line 255, in icon_change
await interaction.guild.edit(icon=ficon) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\guild.py", line 1570, in edit
fields['icon'] = utils._bytes_to_base64_data(icon) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\utils.py", line 495, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\utils.py", line 481, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'): TypeError: startswith first arg must be str or a tuple of str, not bytes
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
Here is the code I currently have:
#bot.slash_command(description="Change server icon")
#application_checks.is_owner()
async def icon_change(interaction : Interaction):
with open('C:\Server_Icons\Logoaa.png', 'rb') as Iconaa:
icona = Iconaa.read()
with open('C:\Server_Icons\Logocc.png', 'rb') as Iconcc:
iconc = Iconcc.read()
with open('C:\Server_Icons\Logodd.png', 'rb') as Icondd:
icond = Icondd.read()
with open('C:\Server_Icons\Logoff.png', 'rb') as Iconff:
iconf = Iconff.read()
with open('C:\Server_Icons\Logohh.png', 'rb') as Iconhh:
iconh = Iconhh.read()
iconch = ['icona', 'iconc', 'icond', 'iconf', 'iconh']
ficon = random.choice(iconch)
await interaction.guild.edit(icon=ficon)
Any help would be appreciated.
This can be fixed by converting the image to a byte array using 'bytearray()'
Example:
with open('C:\Images\Image.png', 'rb') as Image:
a = Image.read()
imageA = bytearray(a)
Fixed code:
#bot.slash_command(description="Change server icon")
#application_checks.is_owner()
async def icon_change(interaction : Interaction):
with open('C:\Server_Icons\Logoaa.png', 'rb') as Iconaa:
iconaaa = Iconaa.read()
icona = bytearray(iconaaa)
with open('C:\Server_Icons\Logocc.png', 'rb') as Iconcc:
iconccc = Iconcc.read()
iconc = bytearray(iconccc)
with open('C:\Server_Icons\Logodd.png', 'rb') as Icondd:
iconddd = Icondd.read()
icond = bytearray(iconddd)
with open('C:\Server_Icons\Logoff.png', 'rb') as Iconff:
iconfff = Iconff.read()
iconf = bytearray(iconfff)
with open('C:\Server_Icons\Logohh.png', 'rb') as Iconhh:
iconhhh = Iconhh.read()
iconh = bytearray(iconhhh)
iconch = [icona, iconc, icond, iconf, iconh]
ficon = random.choice(iconch)
await interaction.send(f"Icon changed!")
await interaction.guild.edit(icon=ficon)

IMAP4LIB When using the store command I get the error "BAD [b'Could not parse command']"

I am new to all of this so I'm sorry if I mess this up or have already made a mess. I have two classes a GUI and my MailSorter class in the GUI class I have method which logins, then one that fetches all the EmailIds then finally fetches all the From emails and stores it in a dict. which stores the From email and amount of times it appears and an array with the From email and the ID.
def fetchFrom(self,emailIDs):
EmailAmount = dict()
Email = []
count = 0
for emailId in emailIDs:
#Converts email into string
result2,email_data = self.mail.fetch(emailId,'(RFC822)')
try:
raw_email = email_data[0][1].decode("utf-8")
email_message = email.message_from_string(raw_email)
#Fetches email address sent from
From = email_message["From"]
Email.append((From,emailId))
#print(From)
if From in EmailAmount:
EmailAmount[From] = EmailAmount[From] + 1
else:
EmailAmount[From] = 1
count += 1
if count > 10:
break
except Exception as e:
self.log.append((emailId,e))
def mainScreenInterface(self):
#Process
print("Loading program")
EmailIds = self.Mail.fetchEmailId()
EmailDict, self.EmailArray = self.Mail.fetchFrom(EmailIds)
self.master.geometry("750x600")
self.master.title("Main Screen")
self.destoryWidget()
#New Frame
self.mainScreen = tk.Frame(self.master)
self.mainScreen.pack()
#Labels
mainText = tk.Label(self.mainScreen,text = "All Emails")
mainText.config(font=("Courier","25"))
#Buttons
delete = tk.Button(self.mainScreen,text="Delete", command = self.Delete)
deleteAll = tk.Button(self.mainScreen,text="Delete All", command = self.DeleteAll)
Help = tk.Button(self.mainScreen,text="Help", command = self.Help_)
#Scrollbar
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side="right",fill="y")
#Listbox
self.listbox = tk.Listbox(root,width = root.winfo_screenwidth(), height = 25)
#Attach a scrool wheel to the listbox
self.listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.listbox.yview)
#Add items to the list box
count = 1
for x,y in EmailDict.items():
self.listbox.insert(count,(x,y))
count += 1
#Placement
paddingValue = 40
mainText.pack(side="top")
self.listbox.pack(side="top")
delete.pack(side="left",padx=paddingValue)
deleteAll.pack(side="left",padx=paddingValue)
Help.pack(side="left",padx=paddingValue)
def Delete(self):
emailName = self.listbox.get(tk.ANCHOR)[0]
self.Mail.deleteEmail(emailName,self.EmailArray)
So the fetchFrom is from the mailSorter class and the other two are the GUI class, when I call the deleteEmail I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 197, in Delete
self.Mail.deleteEmail(emailName,self.EmailArray)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 66, in deleteEmail
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')
File "C:\Python\lib\imaplib.py", line 840, in store
typ, dat = self._simple_command('STORE', message_set, command, flags)
File "C:\Python\lib\imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python\lib\imaplib.py", line 1027, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: STORE command error: BAD [b'Could not parse command']
but when I run it as a text base with no GUI and use an example email it all works fine:
test = MailSorter("hamadnassor5#gmail.com","snerfulbubble1.")
test.login()
EmailIds = test.fetchEmailId()
EmailDict, EmailArray = test.fetchFrom(EmailIds)
test.displayEmails(EmailDict)
test.deleteEmail("Xbox <Xbox#outlook.com>",EmailArray)
test.closeCon()
DeleteMail code
def deleteEmail(self, emailName, EmailArray):
for Id in EmailArray:
if Id[0] == emailName:
print(Id[0])
print(emailName)
print(Id[1])
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')

AttributeError: 'NoneType' object has no attribute 'decode'

names, plot_dicts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'],
'xlink': repo_dict['owner']['html_url'],
}
plot_dicts.append(plot_dict)
my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'Most-Stared Python Project On Github'
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('new_repos.svg')
*If I run this, there will be an error.
Traceback (most recent call last):
File "new_repos.py", line 54, in <module>
chart.render_to_file('new_repos.svg')
File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\public.py", line 114, in render_to_file
f.write(self.render(is_unicode=True, **kwargs))
File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\public.py", line 52, in render
self.setup(**kwargs)
File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\base.py", line 217, in setup
self._draw()
File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\graph.py", line 933, in _draw
self._plot()
File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\bar.py", line 146, in _plot
self.bar(serie)
File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\bar.py", line 116, in bar
metadata)
File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\util.py", line 234, in decorate
metadata['label'])
File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\_compat.py", line 62, in to_unicode
return string.decode('utf-8')
AttributeError: 'NoneType' object has no attribute 'decode'
*How ever if I change part of the code to this, the error will disappear, *however the description will be ignored in the chart.
names, plot_dicts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
plot_dict = {
'value': repo_dict['stargazers_count'],
#'label': repo_dict['description'],
'xlink': repo_dict['owner']['html_url'],
}
plot_dicts.append(plot_dict)
*I don't know why, Can anyone help me with this problem?
'label':str(repo_dict['description'])
Try str() like above, it seems the data you got before hasn't clarifed the type of value that 'description' storged.
May be the API didn't match the description, so you can use ifelse to solve it. Just like this.
description = repo_dict['description']
if not description:
description = 'No description provided'
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': description,
'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)`
If the web API returns the value null, it means there's no result, so you can solve it with if statement. Maybe here, the items shadowsocks didn't return anything, so it maybe something went wrong.
from requests import get
from pygal import Bar, style, Config
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
# получение данных по API GitHub
get_data = get(url)
response_dict = get_data.json()
repositories = response_dict['items']
# получение данных для построения визуализации
names, stars_labels = [], []
for repository in repositories:
names.append(repository['name'])
if repository['description']:
stars_labels.append({'value': repository['stargazers_count'],
'label': repository['description'],
'xlink': repository['html_url']})
else:
stars_labels.append({'value': repository['stargazers_count'],
'label': "нет описания",
'xlink': repository['html_url']})
# задание стилей для диаграммы
my_config = Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.truncate_label = 15 # сокращение длинных названий проектов
my_config.show_y_guides = False # скроем горизонтальные линии
my_config.width = 1300
my_style = style.LightenStyle('#333366', base_style=style.LightColorizedStyle)
my_style.label_font_size = 16
my_style.major_label_font_size = 20
# построение визуализации
chart = Bar(my_config, style=my_style)
chart.title = "Наиболее популярные проекты Python на GitHub"
chart.x_labels = names
chart.add('', stars_labels)
chart.render_to_file("python_projects_with_high_stars.svg")

struct.pack in Python3 got struct.error: required argument is not an integer

I'm doing a zipping func of this:
open_file = open(file_path,'rb')
open_save = open(save_path,'wb+')
try:
open_read = open_file.read()
data = zip_data(open_read)
head_xis = b'XIS'
head_version = bytes(0)
head_type1 = bytes(1)
head_type2 = bytes(1)
head_en_type = bytes(0)
head_com_type = bytes(1)
head_sour_len = len(open_read)
# try:
md5 = hashlib.md5()
md5.update(open_read)
head_md5 = md5.digest()
print("byteeeeee")
# except:
# head_md5 = None
randoms = str(uuid.uuid1()).split('-')[0]
head_random = bytes(randoms,encoding = "utf-8")
print(head_md5)
print(head_random)
head_resour_len= len(data)
print(type(head_xis))
print(type(head_version))
print(type(head_type1))
print(type(head_type2))
print(type(head_en_type))
print(type(head_com_type))
print(type(head_sour_len))
print(type(head_md5))
print(type(head_random))
print(type(head_resour_len))
head = struct.pack('3sBBBBBI16s8sI',
head_xis,
head_version,
head_type1,
head_type2,
head_en_type,
head_com_type,
head_sour_len,
head_md5,
head_random,
head_resour_len
)
open_save.write(head)
# except Exception as e:
# print("eeeee" + str(e))
# return False,str(e)
# else:
# open_save.write(data)
# return True,''
finally:
open_file.close()
open_save.close()
and it shows exception and print like below:
byteeeeee
b'\xf9\xf4\xf2\xcb\xbfM\x11\xb5\xeeNP/\x02H\xebK'
b'f9f33502'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'bytes'
class 'int'
class 'bytes'
class 'bytes'
class 'int'
Traceback (most recent call last):
File "entrance.py", line 52, in startProcess
Helper.processCombine(self.selectedVer,False)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/Helper.py", line 86, in processCombine
itemConf.get(version,suffix),True,True)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 514, in process
compress(build_dir,zip_dir,filter_file)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 400, in compress
zfile = zip_file(src_file_path,save_path)
File "/Users/mapzchen/myShell/qtPro/fastColuaco/coluaco.py", line 131, in zip_file
head_resour_len
struct.error: required argument is not an integer
I have tried to print types of arguments,
and it seems to fit 3sBBBBBI16s8sI correctly
I'm confused by what arg that performs this exception
In structure formating string "B" for bytes need variable type 'int', that is main problem. So instead of head_type1 = bytes(1) use head_type1 = 1
Here given below code gives same error.
Problem:
n = bytes(2)
x = struct.pack("B", n)
Solution:
n = 2
x = struct.pack("B", n)
Suggestion:
Use Byte Orders like '=', while dealing with integers like 'I'.

Resources