I'm trying to call multiple parameters (self, other) in a __str__() function defined in a class but I keep getting an error - python-2.x

As stated above, I'm currently trying to print multiple values inside of a string function using the (self, other) process, but I keep getting this error:
TypeError: str() takes exactly 2 arguments (1 given)
Here is my relevant code block:
def __str__(self, enemy):
s = "{} vs {}\n\n".format(self.name, enemy.name)
s += "Your move set: "
for move in self.moves.keys():
s += move + " - "
s += "\n\n"
s += "Current health: {}\n\n".format(self.health)
s += "Enemy health: {}\n\n".format(enemy.health)
return s
This is how I'm calling the function, obviously with the fat trimmed out.
c1 = Fighter("Gunsmith" , "gunsmith.gif")
Main.character = c1
statsList.insert(END, str(self.character))
The code works if I delete enemy from the parameters and all other enemy.x parameters.
https://pastebin.com/7dWi2DpB
my full code, as its too detailed to link multiple parts.
heres the full error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1547, in __call__
return self.func(*args)
File "C:\Users\CornTortilla\Desktop\Comp. Science\CSC132\Github\teamProject\Pi.py", line 197, in chooseGunsmith
self.fightWindow()
File "C:\Users\CornTortilla\Desktop\Comp. Science\CSC132\Github\teamProject\Pi.py", line 180, in fightWindow
statsList.insert(END, str(self.character))
TypeError: __str__() takes exactly 2 arguments (1 given)

Related

Discord.py error: "ValueError: <class 'str'> is not a valid ChannelType"

I don't understand what the error is.
> Ignoring exception in command weather:
> Traceback (most recent call last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/enums.py", line 168, in __call__
> return cls._enum_value_map_[value]
> KeyError: <class 'str'>
> During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "/home/timoha/discord_bot/main.py", line 166, in weather
async with discord.channel.ChannelType(value=str):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/enums.py", line 170, in __call__
> raise ValueError(f"{value!r} is not a valid {cls.__name__}")
> ValueError: <class 'str'> is not a valid ChannelType
>
> The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
> raise ApplicationCommandInvokeError(exc) from exc
> discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ValueError: <class 'str'> is not a valid ChannelType
Code:
#bot.slash_command(name="weather", description="Погода")
async def weather(ctx, *, city: str):
city_name = city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
channel = ctx.message
if x["cod"] != "404":
async with discord.channel.ChannelType(value=str):
value=str
y = x["главный"]
current_temperature = y["температура"]
current_temperature_celsiuis =str(round(current_temperature - 273.15))
current_pressure = y["давление"]
current_humidity = y["влажность"]
z = x["погода"]
weather_description = z[0]["описание"]
weather_description = z[0]["описание"]
embed = discord.Embed(title=f"Погода в {city_name}",
color=ctx.guild.me.top_role.color,
timestamp=ctx.message.created_at,)
embed.add_field(name="Описание", value=f"**{weather_description}**", inline=False)
embed.add_field(name="Температура(C)", value=f"**{current_temperature_celsiuis}°C**", inline=False)
embed.add_field(name="Влажность(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(name="Atmospheric Pressure(hPa)", value=f"**{current_pressure}hPa**", inline=False)
embed.set_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
embed.set_footer(text=f"Запрошенный {ctx.author.name}")
await channel.send(embed=embed)
else:
await channel.send("Город не найден.")
I tried to change a lot of things, but I still can't figure out what the problem is.
There's a few issues with your code - that error is probably just the first one. I've attempted to rewrite what you've provided with some explanation but hopefully it replicates what you're trying to do.
#bot.slash_command(name="weather", description="Погода")
async def weather(ctx, *, city: str):
# as we're doing an API call here - let's defer so the interaction doesn't timeout
await ctx.defer()
# no reason to redefine another variable called 'city_name' equal to 'city' - just use 'city' everywhere
# could also use a f-string for creating the URL here
# complete_url = f"{base_url}appid={api_key}&q={city}"
complete_url = base_url + "appid=" + api_key + "&q=" + city
response = requests.get(complete_url)
json_response = response.json()
if json_response["cod"] == "404":
# if it's 404, let's send the error message and return early
# means we don't have a big nested "if" block
await channel.send("Город не найден.")
return
y = json_response["главный"]
z = json_response["погода"]
current_temperature = y["температура"]
current_temperature_celsiuis =str(round(current_temperature - 273.15))
current_pressure = y["давление"]
current_humidity = y["влажность"]
weather_description = z[0]["описание"]
weather_description = z[0]["описание"]
# create the embed
embed = discord.Embed(
title=f"Погода в {city}",
color=ctx.guild.me.top_role.color,
timestamp=ctx.message.created_at
)
embed.add_field(name="Описание", value=f"**{weather_description}**", inline=False)
embed.add_field(name="Температура(C)", value=f"**{current_temperature_celsiuis}°C**", inline=False)
embed.add_field(name="Влажность(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(name="Atmospheric Pressure(hPa)", value=f"**{current_pressure}hPa**", inline=False)
embed.set_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
embed.set_footer(text=f"Запрошенный {ctx.author.name}")
# now let's send our response
# ctx.send will send to the channel that the user used the slash command in
await ctx.send(embed=embed)
The ctx variable docs.
What I changed:
removed creating a variable called city_name that was exactly equal to city - seemed redundant
added ctx.defer() - if our code takes a little while it's good to defer so the interaction doesn't timeout
removed channel = ctx.message. We can get the channel later if we need to (we don't in this case) but this was setting it equal to the message that invoked the application command (which isn't really a message) so we aren't accomplishing anything here anyways
if we get a 404 response; send error message and return. Better to do this than have a big nested if block in my opinion.
I also renamed x to json_response as I prefer descriptive variable names but I gave up on y and z.
got rid of the whatever the async with statement was trying to accomplish
used ctx.send(embed=embed) at the bottom to send your created embed to the channel that the user used the application command in
Hopefully, this is what you want it to do and hopefully you understand what's going on a bit now. It might be worth having a look through some of the examples and documentation to get a better grasp on how it all works.
Another change you could make, is swapping out requests for aiohttp-requests to make non-blocking API calls.
I took advantage of your help, and I am grateful to you in many ways, but I am just starting my way in programming and learning from a real example. So I corrected my code to yours and I was given a new set of errors, which I also can't figure out a little.
gnoring exception in command weather: Traceback (most recent call
last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs) File
"/home/timoha/discord_bot/main.py", line 162, in weather
y = json_response["главный"] KeyError: 'главный'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command
raised an exception: KeyError: 'главный'

ADSError 857212673: Can't read variable values through name (pyads)

I've been having a problem lately where I can't access the value of any variable through their name. It's not a connection problem since I can read the value from the read() function just fine. However whenever I use the read_by_name function there's always the same error pyads.pyads_ex.ADSError: ADSError: Unknown Error (857212673).
Because it's an unknown error I haven't been able to find documentation on it. I'm using a BC9120 as a PLC and TwinCat 2. Does anyone know what might be causing this?
Code:
if self.plc.is_open == False:
self.plc.open()
print(self.plc.read(pyads.INDEXGROUP_MEMORYBIT, 0*8 + 0, pyads.PLCTYPE_BOOL))
print(self.plc.read_by_name("Test.M0", pyads.PLCTYPE_BOOL))
Logs:
False
Traceback (most recent call last):
File "c:\Users\MAP9AV\Documents\Banca\Modelo Preditivo\Thread_Sup.py", line 50, in run
print(self.plc.read_by_name("Test.M0", pyads.PLCTYPE_BOOL))
File "C:\Users\MAP9AV\AppData\Local\Programs\Python\Python39\lib\site-packages\pyads\connection.py", line 540, in read_by_name
return adsSyncReadByNameEx(
File "C:\Users\MAP9AV\AppData\Local\Programs\Python\Python39\lib\site-packages\pyads\pyads_ex.py", line 1154, in adsSyncReadByNameEx
handle = adsGetHandle(port, address, data_name)
File "C:\Users\MAP9AV\AppData\Local\Programs\Python\Python39\lib\site-packages\pyads\pyads_ex.py", line 890, in adsGetHandle
handle = adsSyncReadWriteReqEx2(
File "C:\Users\MAP9AV\AppData\Local\Programs\Python\Python39\lib\site-packages\pyads\pyads_ex.py", line 774, in adsSyncReadWriteReqEx2
raise ADSError(err_code)
pyads.pyads_ex.ADSError: ADSError: Unknown Error (857212673).

argument must be a string or unicode object: got tuple instead

The following below is the actual code:
I get the following error: TypeError: list indices must be
integers or slices, not str and TypeError: argument 1 must be a
string or unicode object: got list instead
def search(gss=None, description=None, postcode=None):
if request.method == "POST":
postcodevar = request.form['postcodevar']
print("Asssigning SQl statement to a postgreSQL variable")
postgreSQL_select_Query_2 = [("""SELECT DISTINCT gss,description,
postcode FROM postcodelatlng pt, gss.shapes g
WHERE st_contains(geom,pos) AND %(postcode)s~* '(\y(?:[A-PR-
UWYZ](?:[A-HK-]?\d{1,2}|d[A-HJKMNP-Y]|[A-HK-Y]\d[ABEHMNPRV-
Y]))(?:\s*\d[ABD-HJLNP-UW-]{2})\y)'
LIMIT 50""", {'postcode': postcodevar})]
cursor.execute(postgreSQL_select_Query_2, postcodevar)
print("Selecting rows from mobile table using
cursor.fetchall")
records = cursor.fetchall()
return render_template('idm_prototype.html', data=records)
File "/Users/fernandocamutari/PycharmProjects/DeploymentPrototype/main.py", line 69, in search
WHERE st_contains(geom,pos)
AND %(postcode)s~* '(\y(?:[A-PR-UWYZ](?:[A-HK-]?\d{1,2}|d[A-HJKMNP-Y]|[A-HK-Y]\d[ABEHMNPRV-Y]))(?:\s*\d[ABD-HJLNP-UW-]{2})\y)'
LIMIT 50""", {'postcode': postcodevar})]
cursor.execute(postgreSQL_select_Query_2)
print("Selecting rows from mobile table using cursor.fetchall")
records = cursor.fetchall()
return render_template('idm_prototype.html', data=records)
TypeError: argument 1 must be a string or unicode object: got list instead
This is the Copy/Paste friendly version of the traceback.
Traceback (most recent call last):
File "/Users/fernandocamutari/PycharmProjects/DeploymentPrototype/venv/lib/python3.8/site-packages/flask/app.py", line 2088, in call
return self.wsgi_app(environ, start_response)
File "/Users/fernandocamutari/PycharmProjects/DeploymentPrototype/venv/lib/python3.8/site-packages/flask/app.py", line 2073, in wsgi_app
response = self.handle_exception(e)
File "/Users/fernandocamutari/PycharmProjects/DeploymentPrototype/venv/lib/python3.8/site-packages/flask/app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "/Users/fernandocamutari/PycharmProjects/DeploymentPrototype/venv/lib/python3.8/site-packages/flask/app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/fernandocamutari/PycharmProjects/DeploymentPrototype/venv/lib/python3.8/site-packages/flask/app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/fernandocamutari/PycharmProjects/DeploymentPrototype/venv/lib/python3.8/site-packages/flask/app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/Users/fernandocamutari/PycharmProjects/DeploymentPrototype/main.py", line 54, in search
postgreSQL_select_Query_2 = {"""SELECT DISTINCT gss, description,
TypeError: unhashable type: 'dict'

Repost: Discord.py & Sympy(mostly discord.py I think)

I'm trying to make a math discord bot.
I am pretty sure that my Sympy code is correct and it is just discord.py being funky.
Code:
#client.command()
async def solve(ctx, equation):
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
equation = equation.split("=")
eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
await ctx.send(f"```{solve(eqn)}```")
Please assume that I have all imports necessary.
I am getting this error:
Ignoring exception in command solve:
Traceback (most recent call last):
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "math.py", line 42, in solve
eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\sympy\parsing\sympy_parser.py", line 1008, in parse_expr
return eval_expr(code, local_dict, global_dict)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\sympy\parsing\sympy_parser.py", line 902, in eval_expr
expr = eval(
File "<string>", line 1
Integer (2 )+Integer (3 )Symbol ('x' )
^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SyntaxError: invalid syntax (<string>, line 1)
Judging from the error you are getting, the problem is not from discord.py, it comes from sympy. And judging at the output of the code it has to do with the way you are introducing the parameter equation.
I did the following calls in SymPy Live and it outputted well:
>>> from sympy.parsing.sympy_parser import parse_expr
>>> equation = 'x+1 = 0'
>>> equation = equation.split('=')
>>> eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
>>> print(eqn)
Eq(x + 1, 0)
In your code, however, it is telling you that the parse_expr cannot evaluate the expression correctly due to the syntax being introduced. Make sure your input equation has a valid format.

h2o set_params() takes exactly 1 argument (2 given), even though only 1 given?

Getting error
TypeError: set_params() takes exactly 1 argument (2 given)
even though I only appear to be providing a single argument...
HYPARAMS = {
unicode(HYPER_PARAM): best_random_forest.params[unicode(HYPER_PARAM)][u'actual']
for HYPER_PARAM in list_of_hyperparams_names
}
assert isinstance(HYPARAMS, dict)
print 'Setting optimal params for full-train model...'
pp.pprint(HYPARAMS)
model = model.set_params(HYPARAMS)
#output
{ u'col_sample_rate_per_tree': 1.0,
u'max_depth': 3,
u'min_rows': 1024.0,
u'min_split_improvement': 0.001,
u'mtries': 5,
u'nbins': 3,
u'nbins_cats': 8,
u'ntrees': 8,
u'sample_rate': 0.25}
model = model.set_params(OPTIM_HYPARAMS)
TypeError: set_params() takes exactly 1 argument (2 given)
Looking at the source code,
def set_params(self, **parms):
"""Used by sklearn for updating parameters during grid search.
Parameters
----------
parms : dict
A dictionary of parameters that will be set on this model.
Returns
-------
Returns self, the current estimator object with the parameters all set as desired.
"""
self._parms.update(parms)
return self
there does not appear to be much going on that I see could go wrong. Anyone know what I'm missing here or what is happening to cause this error?
TLDR: Need to unpack the keys/values as **kwargs keywords in order to get the expected behavior of updating the _parms dict. So do
model = model.set_params(**HYPARAMS) #see https://stackoverflow.com/a/22384521/8236733
Example:
# here's a basic standin for the set_params method
>>> def kfunc(**parms):
... print parms
...
# what I was doing
>>> kfunc({1:2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# and also tried
>>> kfunc(parms={1:2})
{'parms': {1: 2}}
>>> kfunc({u'1':2, u'2':3})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# what should have been done
>>> kfunc(**{'1':2})
{'1': 2}
>>> kfunc(**{u'1':2, u'2':3})
{u'1': 2, u'2': 3}
Can now see that this is not directly related to h2o, but keeping post up anyway so others with this problem may find, since did not immediately think to do this from just reading the popup docs for the method (and also since the other SE post commented in the example that I used to actually use variables as **kwarg keywords was not even on the first page of a Google search of "How to use python variable as keyword for kwargs parameter?" so would like to add more avenues to it).

Resources