for loop over list KeyError: 664 - python-3.x

I am trying to iterate this list with words as
CTCCTC TCCTCT CCTCTC CTCTCC TCTCCC CTCCCA TCCCAA CCCAAA CCAAAC CAAACT
CTGGGC TGGGCC GGGCCA GGCCAA GCCAAT CCAATG CAATGC AATGCC ATGCCT TGCCTG GCCTGC
TGCCAG GCCAGG CCAGGA CAGGAG AGGAGG GGAGGG GAGGGG AGGGGC GGGGCT GGGCTG GGCTGG GCTGGT CTGGTC
TGGTCT GGTCTG GTCTGG TCTGGA CTGGAC TGGACA GGACAC GACACT ACACTA CACTAT
ATTCAG TTCAGC TCAGCC CAGCCA AGCCAG GCCAGT CCAGTC CAGTCA AGTCAA GTCAAC TCAACA CAACAC AACACA
ACACAA CACAAG ACAAGG AGGTGG GGTGGC GTGGCC TGGCCT GGCCTG GCCTGC CCTGCA CTGCAC
TGCACT GCACTC CACTCG ACTCGA CTCGAG TCGAGG CGAGGT GAGGTT AGGTTC GGTTCC
TATATA ATATAC TATACC ATACCT TACCTG ACCTGG CCTGGT CTGGTA TGGTAA GGTAAT GTAATG TAATGG AATGGA
I am trying for loop to read each item in the list and parse it through mk_model.vector
the code used is as follows
for x in all_seq_sentences[:]:
mk_model.vector(x)
print(x)
Usually, mk_model.vector("AGT") will give an array corresponding to defines dna2vec model, But here rather than actually performing the model run it throws error as
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-144-77c47b13e98a> in <module>
1 for x in all_seq_sentences[:]:
----> 2 mk_model.vector(x)
3 print(x)
4
~/Desktop/DNA2vec/dna2vec/dna2vec/multi_k_model.py in vector(self, vocab)
35
36 def vector(self, vocab):
---> 37 return self.data[len(vocab)].model[vocab]
38
39 def unitvec(self, vec):
KeyError: 664
Looking forward to some help here

The above problem was having issues because the for loop took all items in first line as one item, which is why .split() was best solution of it. To read follow https://python-reference.readthedocs.io/en/latest/docs/str/split.html
working code:
for i in all_seq_sentences:
word = i.split()
print(word[0])
and then later implement another loop to access the model.vector function
vec_of_all_seq = []
for sentence in all_seq_sentences:
sentence = sentence.split()
for word in sentence:
vec_of_all_seq.append(mk_model.vector(word))
vector representation derived from model.vector will be saved in numpy array named vec_of_all_seq.

Related

Issues using tkdraw.basic on jupyter VCS

So i tried to execute a code using the the tkdraw.basic library in jupyter notebook, and this is what i got :
Its just a simple program that is supposed to draw a line along the window :
import tkdraw.basic as graph
def ligne_horiz(y,larg):
for x in range(larg):
graph.plot(y,x)
graph.open_win(120,160)
ligne_horiz(50,160)
graph.wait()
hers the error :
AssertionError Traceback (most recent call last)
Cell In [12], line 7
4 for x in range(larg):
5 graph.plot(y,x)
----> 7 graph.open_win(120,160)
8 ligne_horiz(50,160)
9 graph.wait()
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/tkdraw/basic.py:63, in open_win(height, width, zoom)
59 # pylint: disable=global-statement
60 # I really want to use a global in this module, to make those functions
61 # easier to use.
62 global _WINDOW
---> 63 assert not _WINDOW, "ERROR: function open() was called twice!"
64 _WINDOW = tkd.Screen((height, width), zoom, grid=False)
AssertionError: ERROR: function open() was called twice!
The code work perfectly on the terminal or in an another .py folder so i think the issue come from the Extension,
I tried to find any similar issue or an update in the library but nothing wrong apparently.(maybe a parameter in the extension it self ?)

Setting all inputs of an activity to 0 in wurst and brightway

Trying to set the existing exchanges (inputs) of an activity to zero and additionally adding an exchange, the following is returned:
"MultipleResults("Multiple production exchanges found")"
"NoResults: No suitable production exchanges founds"
Firstly I set all the input amounts to zero except for the output:
for idx, item in enumerate(ds['exchanges']):
item['amount'] = 0
ds['exchanges'][0]['amount'] = 1
Secondly, I add the a new exchange:
ds['exchanges'].append({
'amount': 1,
'input': (new['database'], new['code']),
'type': 'technosphere',
'name': new['name'],
'location': new['location']
})
Writing the database in the last steps returns the errors.
w.write_brightway2_database(DB, NEW_DB_NAME)
Does anyone see where the problem could be or if there are alternative ways to replace multiple inputs with another one?
Thanks a lot for any hints!
Lukas
Full error traceback:
--------------------------------------------------------------------------
NoResults Traceback (most recent call last)
<ipython-input-6-d4f2dde2b33d> in <module>
2
3 NEW_DB_NAME = "ecoinvent_copy_new"
----> 4 w.write_brightway2_database(ecoinvent, NEW_DB_NAME)
5
6 # Check for new databases
~\Miniconda3\envs\ab\lib\site-packages\wurst\brightway\write_database.py in write_brightway2_database(data, name)
47
48 change_db_name(data, name)
---> 49 link_internal(data)
50 check_internal_linking(data)
51 check_duplicate_codes(data)
~\Miniconda3\envs\ab\lib\site-packages\wurst\linking.py in link_internal(data, fields)
11 input_databases = get_input_databases(data)
12 get_tuple = lambda exc: tuple([exc[f] for f in fields])
---> 13 products = {
14 get_tuple(reference_product(ds)): (ds['database'], ds['code'])
15 for ds in data
~\Miniconda3\envs\ab\lib\site-packages\wurst\linking.py in <dictcomp>(.0)
12 get_tuple = lambda exc: tuple([exc[f] for f in fields])
13 products = {
---> 14 get_tuple(reference_product(ds)): (ds['database'], ds['code'])
15 for ds in data
16 }
~\Miniconda3\envs\ab\lib\site-packages\wurst\searching.py in reference_product(ds)
82 and exc['type'] == 'production']
83 if not excs:
---> 84 raise NoResults("No suitable production exchanges founds")
85 elif len(excs) > 1:
86 raise MultipleResults("Multiple production exchanges found")
NoResults: No suitable production exchanges found
It seems that setting the exchanges to zero caused the problem. The database cannot be written in this case. What I did now is setting the exchanges to a very small number, so that they have no effect on the impact assessment, but are not zero. Not the most elegant way, but works for me. So if anyone has similar problems, that might be a quick solution.

Problems Reading Zip of Shapefiles without loading memory

I've been trying to adapt Andrew Gaidus shapefile reading routine for my needs. The Jupyter Notebook I'm using acts like it partitioned the disk of my MacBook Pro so I can't read or write to disk. Gaidus has a good procedure for avoiding using disk, but is written for prior version of Python.
Here is the code:
dls = "https://github.com/ItsMeLarry/Coursera_Capstone/raw/master/tl_2010_25009_tract00%202.zip"
lynntracts = ZipFile(io.BytesIO(urllib.request.urlopen(dls).read()))
print("Done")
filenames = [y for y in sorted(lynntracts.namelist()) for ending in ['dbf', 'prj', 'shp', 'shx'] if y.endswith(ending)]
#For some reason, I get 8, instead of 4, filenames. The first 4 start with __MACOSX. I get rid of those. The problem I
#have with the 'TypeError' occurs no matter which set of 4 files I use.
print(filenames[0], 'Example of the 4 files that I remove in the for loop')
for i in range(0,4):
del filenames[0]
print(filenames)
dbf, prj, shp, shx = [io.StringIO(ZipFile.read(filename)) for filename in filenames]
r = shapefile.Reader(shp=shp, shx=shx, dbf=dbf)
print(r.numRecords)
Opening with io.BytesIO cured the prior problem of byte/str collision. Now see the TypeError for the ZipFile.read. I get the same error if I use io.BytesIO when calling it. Here is error output followed by error info:
Done
__MACOSX/tl_2010_25009_tract00/._tl_2010_25009_tract00.dbf Example of the 4 files that I remove in the for loop
['tl_2010_25009_tract00/tl_2010_25009_tract00.dbf', 'tl_2010_25009_tract00/tl_2010_25009_tract00.prj', 'tl_2010_25009_tract00/tl_2010_25009_tract00.shp', 'tl_2010_25009_tract00/tl_2010_25009_tract00.shx']
TypeError Traceback (most recent call last)
in ()
12 del filenames[0]
13 print(filenames)
---> 14 dbf, prj, shp, shx = [io.StringIO(ZipFile.read(filename)) for filename in filenames]
15 r = shapefile.Reader(shp=shp, shx=shx, dbf=dbf)
16 print(r.numRecords)
in (.0)
12 del filenames[0]
13 print(filenames)
---> 14 dbf, prj, shp, shx = [io.StringIO(ZipFile.read(filename)) for filename in filenames]
15 r = shapefile.Reader(shp=shp, shx=shx, dbf=dbf)
16 print(r.numRecords)
TypeError: read() missing 1 required positional argument: 'name'
Clearly, I am a beginner. I've come up empty handed trying to research this. Where do I go? What do I need to understand here? Thanks

How to fix Key error - "Groups" in using Fousquare API # Python?

I am trying to list nearby venues using get Nearby venues that are previously defined, and every line worked fine and then I cannot label properly nearby venues using Foursquare although its working fine ( I have to reset my Id and Secret as it just stop working). Im using Python 3.5 at Jupyter Notebook
What Im doing wrong? Thank you!!
BT_venues=getNearbyVenues(names=BT_df['Sector'],
latitudes=BT_df['Latitude'],
longitudes=BT_df['Longitude']
)
-----------------------------------------------------------------------
----
KeyError Traceback (most recent call
last)
<ipython-input-99-563e09cdcab5> in <module>()
1 BT_venues=getNearbyVenues(names=BT_df['Sector'],
2 latitudes=BT_df['Latitude'],
----> 3 longitudes=BT_df['Longitude']
4 )
<ipython-input-93-cfc09962ae0b> in getNearbyVenues(names, latitudes,
longitudes, radius)
18
19 # make the GET request
---> 20 results = requests.get(url).json()['response']
['groups'][0]
['items']
21
22 # return only relevant information for each nearby venue
KeyError: 'groups'
As for groups this was the code
venues = res['response']['groups'][0]['items']
nearby_venues = json_normalize(venues) # flatten JSON
# columns only
filtered_columns = ['venue.name', 'venue.categories',
'venue.location.lat', 'venue.location.lng']
nearby_venues =nearby_venues.loc[:, filtered_columns]
# only one category per a row
nearby_venues['venue.categories'] =
nearby_venues.apply(get_category_type,
axis=1)
# columns cleaning up
nearby_venues.columns = [col.split(".")[-1] for col in
nearby_venues.columns]
nearby_venues.head()
Check response['meta'], you may have exceeded your quota.
If you need an instant resolution, create a new foursquare account. Then create new application and use your new client id and secret to call api

Tkinter Alarm Clock

I am trying to build a countdown timer with tkinter. I want to pass on the values from the entries onto the countdown(count) function. Here is what I tried:
def countdown(count):
label['text'] = count
if count > 0:
top.after(1000, countdown,count-1)
top = tkinter.Tk()
top.geometry("700x100")
hoursT=tkinter.Label(top, text="Hours:")
hoursE=tkinter.Entry(top)
minuteT=tkinter.Label(top, text="Minutes:")
minuteE=tkinter.Entry(top)
secondT=tkinter.Label(top, text="Seconds:")
secondE=tkinter.Entry(top)
hoursT.grid(row=1,column=1)
hoursE.grid(row=1,column=2)
minuteT.grid(row=1,column=3)
minuteE.grid(row=1,column=4)
secondT.grid(row=1,column=5)
secondE.grid(row=1,column=6)
label = tkinter.Label(top)
label.grid(row=3)
t=(int(hoursE.get())*360+int(minuteT.get())*60+int(secondE.get())
button=tkinter.Button(top,text="Start Timer",command=lambda count=t:countdown(count))
button.grid(row=2)
However, I get this error:
Traceback (most recent call last):
File "C:\Users\charley.ACER-PC\AppData\Local\Programs\Python\Python35- 32\tkinterTutorial.py", line 30, in <module>
t=(int(hoursE.get())*360+int(minuteT.get())*60+int(secondE.get()))
ValueError: invalid literal for int() with base 10: ''
How can I run this code:
t=(int(hoursE.get())*360+int(minuteT.get())*60+int(secondE.get())
only when the entries are filled with integers?
Thanks :)
One solution is to have the button there in the first place and change the command at run time with event listeners:
button=tkinter.Button(top,text="Start Timer",command=lambda:None)
button.grid(row=2)
def updateButton():
hour,min,sec=hoursE.get(),minuteT.get(),secondE.get()
if hour.isdigit() and min.isdigit() and sec.isdigit():
time=int(hour)*360+int(min)*60+int(sec)
button.configure(command=lambda count=time:countdown(count))
for widget in (hoursE,minuteT,secondE):
widget.bind("<FocusOut>", updateButton)

Resources