Issues using tkdraw.basic on jupyter VCS - python-3.x

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 ?)

Related

Python debugging in jupyter notebook

I am trying to understand debugging in jupyter notebooks. As per my understanding applying breakpoint() is the way to go about it but I am landing into a few issues that I describe below. I have a file named test_debugger.py in ./ that I am using as a prop in my little understanding endeavor.
#./test_debugger.py
def fun1(a):
print(a)
breakpoint()
if a > 3:
print(a+1)
breakpoint()
print(a+2)
breakpoint()
return None
Setup:
from test_debugger import *
Issues:
breakpoint() enters into debugging the interactive shell:
print(5)
breakpoint()
fun1(4)
breakpoint()
Running the above code gives me
5
--Return--
None
> <ipython-input-2-4276bdd18b42>(2)<module>()
1 print(5)
----> 2 breakpoint()
3 fun1(4)
4 breakpoint()
ipdb>
I press n and I want to jump to the next line in the cell but it gets into debugging the interactive shell I guess. Upon pressing nI get:
ipdb> n
[... skipped 1 hidden frame]
[... skipped 1 hidden frame]
[... skipped 1 hidden frame]
[... skipped 1 hidden frame]
> /home/nitin/miniconda/envs/nyraml386/lib/python3.8/site-packages/IPython/core/interactiveshell.py(3330)run_ast_nodes()
3328 to_run.append((node, 'single'))
3329
-> 3330 for node,mode in to_run:
3331 if mode == 'exec':
3332 mod = Module([node], [])
ipdb>
Question: How do I get the desired functionality of n (jump to next line in code written by me while remaining in the same function score) and s (jump to the next line in code written by me while switching the function scope wherever necessary).
PYTHONBREAKPOINT not available in jupyter notebook
The behavior expected: I have read that in case I want to disable all breakpoint() then I can set the env variable PYTHONBREAKPOINT to manage the behavior of breakpoint(). Specifically, I can set PYTHONBREAKPOINT=0 to disable breakpoint()
The behavior seen: PYTHONBREAKPOINT is not a variable available at all in jupyter notebook. Even if I set it equal to 0 that does not alter the disable breakpoint(). It is as if nothing happened
Question: How to manage breakpoint() when operating in jupyter notebooks. What is the way to bring in PYTHONBREAKPOINT into the notebook

for loop over list KeyError: 664

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.

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

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)

Components.interfaces.nsIProcess2 in Firefox 3.6 -- where did it go?

I am beta testing an application that includes a Firefox extension as one component. It was originally deployed when FF3.5.5 was the latest version, and survived 3.5.6 and 3.5.7. However on FF3.6 I'm getting the following in my error console:
Warning: reference to undefined property Components.interfaces.nsIProcess2
Source file: chrome://overthewall/content/otwhelper.js
Line: 55
Error: Component returned failure code: 0x80570018 (NS_ERROR_XPC_BAD_IID)
[nsIJSCID.createInstance]
Source file: chrome://overthewall/content/otwhelper.js
Line: 55
The function throwing the error is:
48 function otwRunHelper(cmd, aCallback) {
49 var file =
50 Components.classes["#mozilla.org/file/local;1"].
51 createInstance(Components.interfaces.nsILocalFile);
52 file.initWithPath(otwRegInstallDir+'otwhelper.exe');
53
54 otwProcess = Components.classes["#mozilla.org/process/util;1"]
55 .createInstance(Components.interfaces.nsIProcess2);
56
57 otwProcess.init(file);
58 var params = new Array();
59 params = cmd.split(' ');
60
61 otwNextCallback = aCallback;
62 otwObserver = new otwHelperProcess();
63 otwProcess.runAsync(params, params.length, otwObserver, false);
64 }
As you can see, all this function does is run an external EXE helper file (located by a registry key) with some command line parameters and sets up an Observer to asynchronously wait for a response and process the Exit code.
The offending line implies that Components.interfaces.nsIProcess2 is no longer defined in FF3.6. Where did it go? I can't find anything in the Mozilla documentation indicating that it has been changed in the latest release.
The method on nsIProcess2 was moved to nsIProcess. For your code to work in both versions, change this line:
otwProcess = Components.classes["#mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess2);
to this:
otwProcess = Components.classes["#mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess2 || Components.interfaces.nsIProcess);
You will still get the warning, but the error will go away, and your code will work just fine in both versions. You could also store the interface iid in a variable and use the variable:
let iid = ("nsIProcess2" in Components.interfaces) ?
Components.interfaces.nsIProcess2 :
Components.interfaces.nsIProcess;
otwProcess = Components.classes["#mozilla.org/process/util;1"]
.createInstance(iid);

Resources