how to display image from a column in sqlite database - image

i am developing a dictionary that display meaning and image of a word at the same time when the word is being searched.I want to display image from a column on a table in sqlite database but it is giving me error
def search(event=''):
conn = sqlite3.connect('G_DICTION.db')
cur = conn.cursor()
tex.delete(1.0, "end")
data = v.get()
cur.execute("SELECT Meaning, Image FROM DICTION WHERE Words= ?", (data,))
var = cur.fetchone()
if var:
tex.insert("end", var[0]) # accessing the meaning
else:
messagebox.showinfo("Dic", "Word not found")
#####################################
img_path = var[1] # accessing the path to the image
image_object = tk.PhotoImage(img_path) # here I'm not using PIL, but tkinter PhotoImage
ImageLabel.config(image=image_object)
ImageLabel.image = image_object
frame = tk.Frame(dictWin)
frame.place(x=50, y=395)
ImageLabel = tk.Label(frame, font=("calibra", 9), bg="white")
ImageLabel.pack(expand=True, fill=tk.BOTH, padx=65, pady=20)
this is the error below;
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Temmy\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705,
in __call__
return self.func(*args)
File "C:\Users\Temmy\.PyCharmEdu2019.1\config\scratches\newdatba.py", line 23, in search
ImageLabel.config(image=image_object)
NameError: name 'ImageLabel' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Temmy\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705,
in __call__
return self.func(*args)
File "C:\Users\Temmy\.PyCharmEdu2019.1\config\scratches\newdatba.py", line 23, in search
ImageLabel.config(image=image_object)
NameError: name 'ImageLabel' is not defined

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: 'главный'

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'

asyncio_redis and aioredis error on getting a list of keys

When I try to get values for a list of keys using asyncio_redis or aioredis, I am getting the following error. I know it is about something python socket, but unable to resolve the error. I attached both the code and error log with this issue. Here keys are a list of large byte arrays. get_params_redis is called by multiple processes. Any help would be appreciated, thanks!
async def multi_get_key_redis(keys):
redis = await aioredis.create_redis_pool(
'redis://localhost')
result =[]
for key in keys:
result.append(await redis.get(key))
# assert result == await asyncio.gather(*keys)
# return result
redis.close()
await redis.wait_closed()
print(result)
return result
def get_params_redis(shapes):
i = -1
params=[]
keys = []
for s in range(len(shapes)):
keys.append(s)
values = asyncio.get_event_loop().run_until_complete(multi_get_key_redis(keys))
for shape in shapes:
i = i + 1
param_np = pc._loads(values[i]).reshape(shape)
param_tensor = torch.nn.Parameter(torch.from_numpy(param_np))
params.append(param_tensor)
return params
Error Log:
Process Process-1:
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/Users/srujithpoondla/largescaleml_project/train_redis.py", line 33, in train_redis
train_redis_epoch(epoch, args, model, train_loader, optimizer,shapes_len, loop)
File "/Users/srujithpoondla/largescaleml_project/train_redis.py", line 43, in train_redis_epoch
params = get_params_redis(shapes_len,loop)
File "/Users/srujithpoondla/largescaleml_project/common_functions.py", line 76, in get_params_redis
params = loop.run_until_complete(multi_get_key_redis(keys))
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 454, in run_until_complete
self.run_forever()
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 421, in run_forever
self._run_once()
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 1395, in _run_once
event_list = self._selector.select(timeout)
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/selectors.py", line 577, in select
kev_list = self._kqueue.control(None, max_ev, timeout)
OSError: [Errno 9] Bad file descriptor

BrokenPipeError: [WinError 109] The pipe has been ended during data extraction

I am new to multiprocessing in python.I am extracting some features from a list of 70,000 URLs. I have them from 2 different files. After the feature extraction process I pass the result to a list and then to a CSV file.
The code runs but then stops with the error.I tried to catch the error but it produced another one.
Python version = 3.5
from feature_extractor import Feature_extraction
import pandas as pd
from pandas.core.frame import DataFrame
import sys
from multiprocessing.dummy import Pool as ThreadPool
import threading as thread
from multiprocessing import Process,Manager,Array
import time
class main():
lst = None
def __init__(self):
manager = Manager()
self.lst = manager.list()
self.dostuff()
self.read_lst()
def feature_extraction(self,url):
if self.lst is None:
self.lst = []
features = Feature_extraction(url)
self.lst.append(features.get_features())
print(len(self.lst))
def Pool(self,url):
pool = ThreadPool(8)
results = pool.map(self.feature_extraction, url)
def dostuff(self):
df = pd.read_csv('verified_online.csv',encoding='latin-1')
df['label'] = df['phish_id'] * 0
mal_urls = df['url']
df2 = pd.read_csv('new.csv')
df2['label'] = df['phish_id']/df['phish_id']
ben_urls = df2['urls']
t = Process(target=self.Pool,args=(mal_urls,))
t2 = Process(target=self.Pool,args=(ben_urls,))
t.start()
t2.start()
t.join()
t2.join
def read_lst(self):
nw_df = DataFrame(list(self.lst))
nw_df.columns = ['Redirect count','ssl_classification','url_length','hostname_length','subdomain_count','at_sign_in_url','exe_extension_in_request_url','exe_extension_in_landing_url',
'ip_as_domain_name','no_of_slashes_in requst_url','no_of_slashes_in_landing_url','no_of_dots_in_request_url','no_of_dots_in_landing_url','tld_value','age_of_domain',
'age_of_last_modified','content_length','same_landing_and_request_ip','same_landing_and_request_url']
frames = [df['label'],df2['label']]
new_df = pd.concat(frames)
new_df = new_df.reset_index()
nw_df['label'] = new_df['label']
nw_df.to_csv('dataset.csv', sep=',', encoding='latin-1')
if __name__ == '__main__':
start_time = time.clock()
try:
main()
except BrokenPipeError:
print("broken pipe....")
pass
print (time.clock() - start_time, "seconds")
Error Traceback
Process Process-3:
Traceback (most recent call last):
File "F:\Continuum\Anaconda3\lib\multiprocessing\connection.py", line 312, in _recv_bytes
nread, err = ov.GetOverlappedResult(True)
BrokenPipeError: [WinError 109] The pipe has been ended
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "F:\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
self.run()
File "F:\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "H:\Projects\newoproject\src\main.py", line 33, in Pool
results = pool.map(self.feature_extraction, url)
File "F:\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 260, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "F:\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 608, in get
raise self._value
File "F:\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "F:\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 44, in mapstar
return list(map(*args))
File "H:\Projects\newoproject\src\main.py", line 26, in feature_extraction
self.lst.append(features.get_features())
File "<string>", line 2, in append
File "F:\Continuum\Anaconda3\lib\multiprocessing\managers.py", line 717, in _callmethod
kind, result = conn.recv()
File "F:\Continuum\Anaconda3\lib\multiprocessing\connection.py", line 250, in recv
buf = self._recv_bytes()
File "F:\Continuum\Anaconda3\lib\multiprocessing\connection.py", line 321, in _recv_bytes
raise EOFError
EOFError
My response is late and does not address the posted problem directly; but hopefully will provide a clue to others who encounter similar errors.
Errors that I encountered:
BrokenPipeError
WinError 109 The pipe has been ended &
WinError 232 The pipe is being closed
Observed with Python 36 on Windows 7, when:
(1) the same async function was submitted multiple times, each time with a different instance of a multiprocessing data store, a Queue in my case (multiprocessing.Manager().Queue())
AND
(2) the references to the Queues were saved in short-life local variables in the enveloping function.
The errors were occurring despite the fact that the Queues, shared with the successfully spawned and executing async-functions, had items and would still be in active use (put() & get()) at the time of exception.
The error consistently occurred when the same async_func was called the 2nd time with a 2nd instance of the Queue. Immediately after apply_async() of the function, the connection to the 1st Queue supplied to the async_func the 1st time, would get broken.
The issue got resolved when the references to the Queues were saved in non-overlapping (like a Queue-list) & longer-life variables (like variables returned to functions higher in the call-stack) in the enveloping function.

gdata.docs.client.DocsClient

I have the following code, reads oauth2 token form file, then try's to perform a doc's list query to find a specific spreadsheet that I want to copy, however no matter what I try the code either errors out or returns with an object containing no document data.
I am using gdata.docs.client.DocsClient which as far as I can tell is version 3 of the API
def CreateClient():
"""Create a Documents List Client."""
client = gdata.docs.client.DocsClient(source=config.APP_NAME)
client.http_client.debug = config.DEBUG
# Authenticate the user with CLientLogin, OAuth, or AuthSub.
if os.path.exists(config.CONFIG_FILE):
f = open(config.CONFIG_FILE)
tok = pickle.load(f)
f.close()
client.auth_token = tok.auth_token
return client
1st query attempt
def get_doc():
new_api_query = gdata.docs.client.DocsQuery(title='RichSheet', title_exact=True, show_collections=True)
d = client.GetResources(q = new_api_query)
this fails with the following stack trace
Traceback (most recent call last):
File "/Users/richard/PycharmProjects/reportone/make_my_report.py", line 83, in <module>
get_doc()
File "/Users/richard/PycharmProjects/reportone/make_my_report.py", line 57, in get_doc
d = client.GetResources(q = new_api_query)
File "/Users/richard/PycharmProjects/reportone/gdata/docs/client.py", line 151, in get_resources
**kwargs)
File "/Users/richard/PycharmProjects/reportone/gdata/client.py", line 640, in get_feed
**kwargs)
File "/Users/richard/PycharmProjects/reportone/gdata/docs/client.py", line 66, in request
return super(DocsClient, self).request(method=method, uri=uri, **kwargs)
File "/Users/richard/PycharmProjects/reportone/gdata/client.py", line 267, in request
uri=uri, auth_token=auth_token, http_request=http_request, **kwargs)
File "/Users/richard/PycharmProjects/reportone/atom/client.py", line 115, in request
self.auth_token.modify_request(http_request)
File "/Users/richard/PycharmProjects/reportone/gdata/gauth.py", line 1047, in modify_request
token_secret=self.token_secret, verifier=self.verifier)
File "/Users/richard/PycharmProjects/reportone/gdata/gauth.py", line 668, in generate_hmac_signature
next, token, verifier=verifier)
File "/Users/richard/PycharmProjects/reportone/gdata/gauth.py", line 629, in build_oauth_base_string
urllib.quote(params[key], safe='~')))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1266, in quote
if not s.rstrip(safe):
AttributeError: 'bool' object has no attribute 'rstrip'
Process finished with exit code 1
then my second attempt
def get_doc():
other = gdata.docs.service.DocumentQuery(text_query='RichSheet')
d = client.GetResources(q = other)
this returns an ResourceFeed object, but has no content. I have been through the source code for these function but thing are not any obvious.
Have i missed something ? or should i go back to version 2 of the api ?

Resources