i'm using replits database but when i try to load it in it returns an error
any ideas?
cookie = db[name]
cookiepc = db[name + "cookiepc"]
increase = db[name + "increase"]
the error is
Traceback (most recent call last):
File "main.py", line 25, in <module>
cookiepc = db[name + "cookiepc"]
File "/home/runner/Cookie-clicker/venv/lib/python3.8/site-packages/replit/database/database.py", line 439, in __getitem__
raw_val = self.get_raw(key)
File "/home/runner/Cookie-clicker/venv/lib/python3.8/site-packages/replit/database/database.py", line 479, in get_raw
raise KeyError(key)
KeyError: 'shdfgwbdhfbadwcookiepc'
According to the documentation for replit-py, a KeyError is raised when an attempt is made to read from a key that doesn't exist in the database.
You can use db.get to specify a default value for if the key doesn't exist:
print(db.get("b", "default")) # default
db["b"] = "pie"
print(db.get("b", "default")) # pie
Related
i am running a python Application with Mongo DB Backend.
For an EOS Blockchain Query i need to find out the highest Value for an Attribute called eosTimestamp (String)
I created this code:
def getLastEOSTimestampProperty(client,db):
mydb = client[db]
collection = mydb["properties"]
ensure_index(collection,[('eosTimestamp',-1)])
filter={}
project={
'eosTimestamp': 1
}
sort=list({
'eosTimestamp': -1
}.items())
result = list(client[db][collection].find(
filter=filter,
projection=project,
sort=sort
).limit(1))
maxtimestamp=result[0]['eosTimestamp']
#return(maxblocknum)
return str(maxtimestamp)
When i run this code i get the following Error Message:
Traceback (most recent call last):
File "c:\projects\UplandDB\worker.py", line 408, in <module>
print(getLastEOSTimestampProperty(client,db))
File "c:\projects\UplandDB\worker.py", line 387, in getLastEOSTimestampProperty
result = list(client[db][collection].find(
File "C:\projects\UplandDB\.venv\lib\site-packages\pymongo\database.py", line 237, in __getitem__
return Collection(self, name)
File "C:\projects\UplandDB\.venv\lib\site-packages\pymongo\collection.py", line 212, in __init__
raise TypeError("name must be an instance of str")
TypeError: name must be an instance of str
Do You have any hints what i made wrong?
I am tring to resample Chirps data from 0.25 to 0.0025degrees resolution with the following code, I am still using 1 as an upscale factor to get the code to run:
import rasterio
from rasterio.enums import Resampling
import os
upscale_factor = 1
i = 0
for files in os.listdir(r'D:/CHIRPS RSDATA/CHIRPS(1981-1983)'):
if files [-4:] == '.tif':
i = i + 1
fp = r'D:\CHIRPS RSDATA\CHIRPS(1981-1983)'+'\\'+files
print(fp)
dataset = rasterio.open(fp)
data = dataset.read(out_shape=(dataset.count,
int(dataset.height*upscale_factor),
int(dataset.width*upscale_factor)),
resampling=Resampling.bilinear) #You can change the resamplng technique here
if data.shape[-1] != 0 and data.shape[-2] != 0:
transform=dataset.transform*dataset.transform.scale((dataset.width/data.shape[-1]),(dataset.height/data.shape[-2]))
height = int(dataset.height*upscale_factor)
width = int(dataset.width*upscale_factor)
with rasterio.Env():
profile = dataset.profile
profile.update(transform=transform,driver='GTiff',height=height,width=width)
with rasterio.open('D:\CHIRPS RSDATA\CHIRPS(1981-1983)\Rainfalls',"w",**profile) as output:
output.write(data)
print("Image resampled...")
and I am getting this error:
runfile('D:/CHIRPS RSDATA/CHIRPS(1981-1983)/Resampling_python.py', wdir='D:/CHIRPS RSDATA/CHIRPS(1981-1983)')
D:\CHIRPS RSDATA\CHIRPS(1981-1983)\chirps-v2.0.1981.01.01.tif
Traceback (most recent call last):
File "rasterio\_io.pyx", line 1139, in rasterio._io.DatasetWriterBase.__init__
File "rasterio\_err.pyx", line 215, in rasterio._err.exc_wrap_pointer
CPLE_OpenFailedError: Attempt to create new tiff file 'D:/CHIRPS RSDATA/CHIRPS(1981-1983)/Rainfalls' failed: Permission denied
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\CHIRPS RSDATA\CHIRPS(1981-1983)\Resampling_python.py", line 42, in <module>
with rasterio.open('D:\CHIRPS RSDATA\CHIRPS(1981-1983)\Rainfalls',"w",**profile) as output:
File "C:\Users\khoda\anaconda3\lib\site-packages\rasterio\env.py", line 435, in wrapper
return f(*args, **kwds)
File "C:\Users\khoda\anaconda3\lib\site-packages\rasterio\__init__.py", line 225, in open
s = writer(path, mode, driver=driver,
File "rasterio\_io.pyx", line 1143, in rasterio._io.DatasetWriterBase.__init__
RasterioIOError: Attempt to create new tiff file 'D:/CHIRPS RSDATA/CHIRPS(1981-1983)/Rainfalls' failed: Permission denied
I tried changing the permissions of the folder with no luck, I also double checked the synaxes as other people have suggested. Please help.
I want to create multiple databases but I don't know how I can make it
this is python code:
# 1 - for import data in listbox
def clear_item_list():
items.delete(0, END)
# 2 - for import data in listbox
def fill_item_list(items):
for item_ in items:
items.insert(END, item_)
# 3 - for import data in listbox
def item_list_view():
clear_item_list()
items = app.data_1.view()
fill_item_list(items)
# and that for placement data in entries
def get_selected_row_item(event):
global selected_item
if len(items.curselection()) > 0:
index = items.curselection()[0]
selected_item = items.get(index)[:]
item_name.delete(0, END)
item_name.insert(END, selected_item[1])
item_price.delete(0, END)
item_price.insert(END, selected_item[2])
items.bind("<<ListboxSelect>>", get_selected_row_item)
This code is for making a table:
"CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY , Namee VARCHAR , price INTEGER )"
I don't have any idea this is my problem or not, because when I wanna use price, type that data is string and python raise this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\manager\manager_sign_in.py", line 44, in back_to_main_manager
main_screen()
NameError: name 'main_screen' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\manager\sign.py", line 33, in back_to_main_mngr
main_screen()
NameError: name 'main_screen' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\main.py", line 33, in user_sign
user_screen()
NameError: name 'user_screen' is not defined
Traceback (most recent call last):
File "D:\python\WindowsProject\app\main.py", line 4, in <module>
from app.user.user_sign_in import *
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 240, in <module>
user_screen()
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 236, in user_screen
item_list_view()
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 55, in item_list_view
fill_item_list(items)
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 48, in fill_item_list
items.insert(END, item_)
TypeError: 'str' object cannot be interpreted as an integer
and this is input data:
(1, 'pizza', '6')
if you can help me pls say to I give you more data about that if you need
The issue is on the below function:
def fill_item_list(items): # <- items is passed argument
for item_ in items:
# "items" below is expected to be an instance of tkinter Listbox
# but it is actually the passed argument (a list object)
items.insert(END, item_)
You used same name on the passed argument as the tkinter Listbox.
Use another name for the passed argument:
def fill_item_list(data): # used "data" instead of "items"
for item_ in data:
items.insert(END, item_)
I set up a try catch in my code, but it appears that my exception was not correct because it did not seem to catch it.
I am using an exception from a module, and perhaps I didn't import it correctly? Here is my code:
import logging
import fhirclient.models.bundle as b
from fhirclient.server import FHIRUnauthorizedException
logging.disable(logging.WARNING)
def get_all_resources(resource, struct, smart):
'''Perform a search on a resource type and get all resources entries from all retunred bundles.\n
This function takes all paginated bundles into consideration.'''
if smart.ready == False:
smart.reauthorize
search = resource.where(struct)
bundle = search.perform(smart.server)
resources = [entry.resource for entry in bundle.entry or []]
next_url = _get_next_url(bundle.link)
while next_url != None:
try:
json_dict = smart.server.request_json(next_url)
except FHIRUnauthorizedException:
smart.reauthorize
continue
bundle = b.Bundle(json_dict)
resources += [entry.resource for entry in bundle.entry or []]
next_url = _get_next_url(bundle.link)
return resources
Now when i ran the code I got the following error:
Traceback (most recent call last):
File "code.py", line 79, in <module>
main()
File "code.py", line 42, in main
reports = get_all_resources(dr.DiagnosticReport, search, smart)
File "somepath/fhir_tools/resource.py", line 23, in get_all_resources
json_dict = smart.server.request_json(next_url)
File "/usr/local/lib/python3.6/dist-packages/fhirclient/server.py", line 153, in request_json
res = self._get(path, headers, nosign)
File "/usr/local/lib/python3.6/dist-packages/fhirclient/server.py", line 181, in _get
self.raise_for_status(res)
File "/usr/local/lib/python3.6/dist-packages/fhirclient/server.py", line 256, in raise_for_status
raise FHIRUnauthorizedException(response)
server.FHIRUnauthorizedException: <Response [401]>
Shouldn't my exception catch this?
Hey I am having problems accessing some lists.
I can access Items using this code:
data = session.get(BASE_URL + 'tori_market.php',params={'format': 'json'}).json()
except ValueError:
for item in data['items']:
print(item['price'])
But I can not access User using the same code:
data = session.get(BASE_URL + 'tori_market.php',params={'format': 'json'}).json()
except ValueError:
for users in data['user']:
print(user['max'])
Edit: I've posted the wrong code,here is the one i'm using.
data = session.get(BASE_URL + 'tori_market.php',params={'format': 'json'}).json()
except ValueError:
for users in data['user']:
print(users['balance'])
What is wrong with it?
You can check how the API directory are build in this link.
The full traceback is:
Traceback (most recent call last):
File "/Users/Cristi/Desktop/RealBot/prova.py", line 34, in <module>
data = session.get(BASE_URL + 'tori_market.php',params={'format': 'json'}).json()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/models.py", line 799, in json
return json.loads(self.text, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/Cristi/Desktop/RealBot/prova.py", line 37, in <module>
print(users['balance'])
TypeError: string indices must be integers
As soon as it's a passworded page i can give you a screenshot,here.
Edited answer
the user in above is a key in json data, so when you do
for users in data["user"]
you are already iterating over its keys.
Instead, for sake of brevity, do,
for key in data["user"]:
print key, data["user"][key]
This will print all the data within the user dict for you. So now key can take the values of "balance" etc.
Original answer
This is a typo between users and user, you use:
for users in data['user']:
but access it as:
print(user['max'])
Instead access it as:
print(users['max'])