after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def doPostPluginsInit(self):
"""Create a Leo window for each file in the lm.files list."""
# Clear g.app.initing _before_ creating commanders.
lm = self
g.app.initing = False # "idle" hooks may now call g.app.forceShutdown.
# Create the main frame. Show it and all queued messages.
c = c1 = fn = None
if lm.files:
try: # #1403.
for n, fn in enumerate(lm.files):
lm.more_cmdline_files = n < len(lm.files) - 1
c = lm.loadLocalFile(fn, gui=g.app.gui, old_c=None)
# Returns None if the file is open in another instance of Leo.
except Exception:
g.es_print(f"Unexpected exception reading {fn!r}")
g.es_exception()
c = None
if c and not c1:
c1 = c
g.app.loaded_session = not lm.files
# Load (and save later) a session only no files were given on the command line.
if g.app.sessionManager and g.app.loaded_session:
try: # #1403.
aList = g.app.sessionManager.load_snapshot()
if aList:
g.app.sessionManager.load_session(c1, aList)
# tag:#659.
if g.app.windowList:
c = c1 = g.app.windowList[0].c
else:
c = c1 = None
except Exception:
g.es_print("unexpected exception loading session")
g.es_exception()
# Enable redraws.
g.app.disable_redraw = False
if not c1 or not g.app.windowList:
try: # #1403.
c1 = lm.openEmptyWorkBook()
# Calls LM.loadLocalFile.
except Exception:
g.es_print("unexpected exception reading empty workbook")
g.es_exception()
# Fix bug #199.
g.app.runAlreadyOpenDialog(c1)
# Put the focus in the first-opened file.
fileName = lm.files[0] if lm.files else None
c = c1
# For qt gui, select the first-loaded tab.
if g.app.use_global_docks:
pass
else:
if hasattr(g.app.gui, "frameFactory"):
factory = g.app.gui.frameFactory
if factory and hasattr(factory, "setTabForCommander"):
factory.setTabForCommander(c)
if not c:
return False # Force an immediate exit.
# Fix bug 844953: tell Unity which menu to use.
# if c: c.enableMenuBar()
# Do the final inits.
g.app.logInited = True
g.app.initComplete = True
if c:
c.setLog()
c.redraw()
p = c.p if c else None
g.doHook("start2", c=c, p=p, fileName=fileName)
if c:
c.initialFocusHelper()
screenshot_fn = lm.options.get("screenshot_fn")
if screenshot_fn:
lm.make_screen_shot(screenshot_fn)
return False # Force an immediate exit.
return True
|
def doPostPluginsInit(self):
"""Create a Leo window for each file in the lm.files list."""
# Clear g.app.initing _before_ creating commanders.
lm = self
g.app.initing = False # "idle" hooks may now call g.app.forceShutdown.
# Create the main frame. Show it and all queued messages.
c = c1 = fn = None
if lm.files:
try: # #1403.
for n, fn in enumerate(lm.files):
lm.more_cmdline_files = n < len(lm.files) - 1
c = lm.loadLocalFile(fn, gui=g.app.gui, old_c=None)
# Returns None if the file is open in another instance of Leo.
except Exception:
g.es_print(f"Unexpected exception reading {fn!r}")
g.es_exception()
c = None
if c and not c1:
c1 = c
g.app.loaded_session = not lm.files
# Load (and save later) a session only no files were given on the command line.
if g.app.sessionManager and g.app.loaded_session:
try: # #1403.
aList = g.app.sessionManager.load_snapshot()
if aList:
g.app.sessionManager.load_session(c1, aList)
# tag:#659.
if g.app.windowList:
c = c1 = g.app.windowList[0].c
else:
c = c1 = None
except Exception:
g.es_print("unexpected exception loading session")
g.es_exception()
# Enable redraws.
g.app.disable_redraw = False
if not c1 or not g.app.windowList:
try: # #1403.
c1 = lm.openEmptyWorkBook()
# Calls LM.loadLocalFile.
except Exception:
g.es_print("unexpected reading empty workbook")
g.es_exception()
# Fix bug #199.
g.app.runAlreadyOpenDialog(c1)
# Put the focus in the first-opened file.
fileName = lm.files[0] if lm.files else None
c = c1
# For qt gui, select the first-loaded tab.
if g.app.use_global_docks:
pass
else:
if hasattr(g.app.gui, "frameFactory"):
factory = g.app.gui.frameFactory
if factory and hasattr(factory, "setTabForCommander"):
factory.setTabForCommander(c)
if not c:
return False # Force an immediate exit.
# Fix bug 844953: tell Unity which menu to use.
# if c: c.enableMenuBar()
# Do the final inits.
g.app.logInited = True
g.app.initComplete = True
if c:
c.setLog()
c.redraw()
p = c.p if c else None
g.doHook("start2", c=c, p=p, fileName=fileName)
if c:
c.initialFocusHelper()
screenshot_fn = lm.options.get("screenshot_fn")
if screenshot_fn:
lm.make_screen_shot(screenshot_fn)
return False # Force an immediate exit.
return True
|
https://github.com/leo-editor/leo-editor/issues/1415
|
unexpected exception loading session
Traceback (most recent call last):
File "c:\users\viktor\pyve\github\leo-dev-opt-b\devel\leo-editor-devel\leo\core\leoApp.py", line 2601, in doPostPluginsInit
g.app.sessionManager.load_session(c1, aList)
[...]
File "c:\users\viktor\pyve\github\leo-dev-opt-b\devel\leo-editor-devel\leo\core\leoApp.py", line 1478, in <listcomp>
if [x for x in aList if os.path.samefile(x, fn)]:
File "C:\EE\Python\lib\genericpath.py", line 96, in samefile
s1 = os.stat(f1)
FileNotFoundError: [WinError 3] Das System kann den angegebenen Pfad nicht finden: 'C:/users/viktor/pyve/ve4ileo/lib/site-packages/leo/doc/quickstart.leo'
|
FileNotFoundError
|
def openEmptyWorkBook(self):
"""Open an empty frame and paste the contents of CheatSheet.leo into it."""
lm = self
# Create an empty frame.
fn = lm.computeWorkbookFileName()
if not fn:
return None # #1415
c = lm.loadLocalFile(fn, gui=g.app.gui, old_c=None)
if not c:
return None # #1201: AttributeError below.
# Open the cheatsheet, but not in batch mode.
if not g.app.batchMode and not g.os_path_exists(fn):
# #933: Save clipboard.
old_clipboard = g.app.gui.getTextFromClipboard()
# Paste the contents of CheetSheet.leo into c.
c2 = c.openCheatSheet(redraw=False)
if c2:
for p2 in c2.rootPosition().self_and_siblings():
c2.setCurrentPosition(p2) # 1380
c2.copyOutline()
p = c.pasteOutline()
# #1380 & #1381: Add guard & use vnode methods to prevent redraw.
if p:
c.setCurrentPosition(p) # 1380
p.v.contract()
p.v.clearDirty()
c2.close(new_c=c)
# Delete the dummy first node.
root = c.rootPosition()
root.doDelete(newNode=root.next())
c.target_language = "rest"
# Settings not parsed the first time.
c.setChanged(False)
c.redraw(c.rootPosition()) # # 1380: Select the root.
# #933: Restore clipboard
g.app.gui.replaceClipboardWith(old_clipboard)
return c
|
def openEmptyWorkBook(self):
"""Open an empty frame and paste the contents of CheatSheet.leo into it."""
lm = self
# Create an empty frame.
fn = lm.computeWorkbookFileName()
c = lm.loadLocalFile(fn, gui=g.app.gui, old_c=None)
if not c:
return None # #1201: AttributeError below.
# Open the cheatsheet, but not in batch mode.
if not g.app.batchMode and not g.os_path_exists(fn):
# #933: Save clipboard.
old_clipboard = g.app.gui.getTextFromClipboard()
# Paste the contents of CheetSheet.leo into c.
c2 = c.openCheatSheet(redraw=False)
if c2:
for p2 in c2.rootPosition().self_and_siblings():
c2.setCurrentPosition(p2) # 1380
c2.copyOutline()
p = c.pasteOutline()
# #1380 & #1381: Add guard & use vnode methods to prevent redraw.
if p:
c.setCurrentPosition(p) # 1380
p.v.contract()
p.v.clearDirty()
c2.close(new_c=c)
# Delete the dummy first node.
root = c.rootPosition()
root.doDelete(newNode=root.next())
c.target_language = "rest"
# Settings not parsed the first time.
c.setChanged(False)
c.redraw(c.rootPosition()) # # 1380: Select the root.
# #933: Restore clipboard
g.app.gui.replaceClipboardWith(old_clipboard)
return c
|
https://github.com/leo-editor/leo-editor/issues/1415
|
unexpected exception loading session
Traceback (most recent call last):
File "c:\users\viktor\pyve\github\leo-dev-opt-b\devel\leo-editor-devel\leo\core\leoApp.py", line 2601, in doPostPluginsInit
g.app.sessionManager.load_session(c1, aList)
[...]
File "c:\users\viktor\pyve\github\leo-dev-opt-b\devel\leo-editor-devel\leo\core\leoApp.py", line 1478, in <listcomp>
if [x for x in aList if os.path.samefile(x, fn)]:
File "C:\EE\Python\lib\genericpath.py", line 96, in samefile
s1 = os.stat(f1)
FileNotFoundError: [WinError 3] Das System kann den angegebenen Pfad nicht finden: 'C:/users/viktor/pyve/ve4ileo/lib/site-packages/leo/doc/quickstart.leo'
|
FileNotFoundError
|
def blacken_node(self, root, diff_flag, check_flag=False):
"""Run black on all Python @<file> nodes in root's tree."""
c = self.c
if not black or not root:
return
t1 = time.process_time()
self.changed, self.errors, self.total = 0, 0, 0
self.undo_type = "blacken-node"
self.blacken_node_helper(root, check_flag, diff_flag)
t2 = time.process_time()
if not g.unitTesting:
print(
f"{root.h}: scanned {self.total} node{g.plural(self.total)}, "
f"changed {self.changed} node{g.plural(self.changed)}, "
f"{self.errors} error{g.plural(self.errors)} "
f"in {t2 - t1:5.2f} sec."
)
if self.changed or self.errors:
c.redraw()
|
def blacken_node(self, root, diff_flag, check_flag=False):
"""Run black on all Python @<file> nodes in root's tree."""
c = self.c
if not black or not root:
return
t1 = time.clock()
self.changed, self.errors, self.total = 0, 0, 0
self.undo_type = "blacken-node"
self.blacken_node_helper(root, check_flag, diff_flag)
t2 = time.clock()
if not g.unitTesting:
print(
f"{root.h}: scanned {self.total} node{g.plural(self.total)}, "
f"changed {self.changed} node{g.plural(self.changed)}, "
f"{self.errors} error{g.plural(self.errors)} "
f"in {t2 - t1:5.2f} sec."
)
if self.changed or self.errors:
c.redraw()
|
https://github.com/leo-editor/leo-editor/issues/1400
|
Traceback (most recent call last):
File "C:\leo-editor\launchLeo.py", line 8, in <module>
leo.core.runLeo.run()
File "C:\leo-editor\leo\core\runLeo.py", line 73, in run
g.app.loadManager.load(fileName, pymacs)
File "C:\leo-editor\leo\core\leoApp.py", line 2392, in load
t1 = time.clock()
AttributeError: module 'time' has no attribute 'clock'
|
AttributeError
|
def blacken_tree(self, root, diff_flag, check_flag=False):
"""Run black on all Python @<file> nodes in root's tree."""
c = self.c
if not black or not root:
return
t1 = time.process_time()
self.changed, self.errors, self.total = 0, 0, 0
undo_type = "blacken-tree"
bunch = c.undoer.beforeChangeTree(root)
# Blacken *only* the selected tree.
changed = False
for p in root.self_and_subtree():
if self.blacken_node_helper(p, check_flag, diff_flag):
changed = True
if changed:
c.setChanged(True)
c.undoer.afterChangeTree(root, undo_type, bunch)
t2 = time.process_time()
if not g.unitTesting:
print(
f"{root.h}: scanned {self.total} node{g.plural(self.total)}, "
f"changed {self.changed} node{g.plural(self.changed)}, "
f"{self.errors} error{g.plural(self.errors)} "
f"in {t2 - t1:5.2f} sec."
)
if self.changed and not c.changed:
c.setChanged(True)
if self.changed or self.errors:
c.redraw()
|
def blacken_tree(self, root, diff_flag, check_flag=False):
"""Run black on all Python @<file> nodes in root's tree."""
c = self.c
if not black or not root:
return
t1 = time.clock()
self.changed, self.errors, self.total = 0, 0, 0
undo_type = "blacken-tree"
bunch = c.undoer.beforeChangeTree(root)
# Blacken *only* the selected tree.
changed = False
for p in root.self_and_subtree():
if self.blacken_node_helper(p, check_flag, diff_flag):
changed = True
if changed:
c.setChanged(True)
c.undoer.afterChangeTree(root, undo_type, bunch)
t2 = time.clock()
if not g.unitTesting:
print(
f"{root.h}: scanned {self.total} node{g.plural(self.total)}, "
f"changed {self.changed} node{g.plural(self.changed)}, "
f"{self.errors} error{g.plural(self.errors)} "
f"in {t2 - t1:5.2f} sec."
)
if self.changed and not c.changed:
c.setChanged(True)
if self.changed or self.errors:
c.redraw()
|
https://github.com/leo-editor/leo-editor/issues/1400
|
Traceback (most recent call last):
File "C:\leo-editor\launchLeo.py", line 8, in <module>
leo.core.runLeo.run()
File "C:\leo-editor\leo\core\runLeo.py", line 73, in run
g.app.loadManager.load(fileName, pymacs)
File "C:\leo-editor\leo\core\leoApp.py", line 2392, in load
t1 = time.clock()
AttributeError: module 'time' has no attribute 'clock'
|
AttributeError
|
def createActualFile(self, fileName, toOPML, toZip):
if toZip:
self.toString = True
theActualFile = None
else:
try:
# 2010/01/21: always write in binary mode.
theActualFile = open(fileName, "wb")
except Exception:
g.es(f"can not create {fileName}")
g.es_exception()
theActualFile = None
return fileName, theActualFile
|
def createActualFile(self, fileName, toOPML, toZip):
if toZip:
self.toString = True
theActualFile = None
else:
try:
# 2010/01/21: always write in binary mode.
theActualFile = open(fileName, "wb")
except IOError:
g.es(f"can not open {fileName}")
g.es_exception()
theActualFile = None
return fileName, theActualFile
|
https://github.com/leo-editor/leo-editor/issues/1378
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 1599, in createActualFile
theActualFile = open(fileName, 'wb')
FileNotFoundError: [Errno 2] No such file or directory: 'c:/leo.repo/leo-editor/~/.leo/workbook.leo'
|
FileNotFoundError
|
def os_path_finalize(path):
"""
Expand '~', then return os.path.normpath, os.path.abspath of the path.
There is no corresponding os.path method
"""
path = path.replace("\x00", "") # Fix Pytyon 3 bug on Windows 10.
path = os.path.expanduser(path) # #
path = os.path.abspath(path)
path = os.path.normpath(path)
if g.isWindows:
path = path.replace("\\", "/")
# calling os.path.realpath here would cause problems in some situations.
return path
|
def os_path_finalize(path, **keys):
"""
Expand '~', then return os.path.normpath, os.path.abspath of the path.
There is no corresponding os.path method
"""
path = path.replace("\x00", "") # Fix Pytyon 3 bug on Windows 10.
path = os.path.abspath(path)
path = os.path.normpath(path)
if g.isWindows:
path = path.replace("\\", "/")
# calling os.path.realpath here would cause problems in some situations.
return path
|
https://github.com/leo-editor/leo-editor/issues/1378
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 1599, in createActualFile
theActualFile = open(fileName, 'wb')
FileNotFoundError: [Errno 2] No such file or directory: 'c:/leo.repo/leo-editor/~/.leo/workbook.leo'
|
FileNotFoundError
|
def openEmptyWorkBook(self):
"""Open an empty frame and paste the contents of CheatSheet.leo into it."""
lm = self
# Create an empty frame.
fn = lm.computeWorkbookFileName()
c = lm.loadLocalFile(fn, gui=g.app.gui, old_c=None)
if not c:
return None # #1201: AttributeError below.
# Open the cheatsheet, but not in batch mode.
if not g.app.batchMode and not g.os_path_exists(fn):
# #933: Save clipboard.
old_clipboard = g.app.gui.getTextFromClipboard()
# Paste the contents of CheetSheet.leo into c.
c2 = c.openCheatSheet(redraw=False)
if c2:
for p2 in c2.rootPosition().self_and_siblings():
c2.selectPosition(p2)
c2.copyOutline()
p = c.pasteOutline()
c.selectPosition(p)
p.contract()
p.clearDirty()
c2.close(new_c=c)
root = c.rootPosition()
if root.h == g.shortFileName(fn):
root.doDelete(newNode=root.next())
p = g.findNodeAnywhere(c, "Leo's cheat sheet")
if p:
c.selectPosition(p)
p.expand()
c.target_language = "rest"
# Settings not parsed the first time.
c.setChanged(False)
c.redraw()
# #933: Restore clipboard
g.app.gui.replaceClipboardWith(old_clipboard)
return c
|
def openEmptyWorkBook(self):
"""Open an empty frame and paste the contents of CheatSheet.leo into it."""
lm = self
# Create an empty frame.
fn = lm.computeWorkbookFileName()
c = lm.loadLocalFile(fn, gui=g.app.gui, old_c=None)
# Open the cheatsheet, but not in batch mode.
if not g.app.batchMode and not g.os_path_exists(fn):
# #933: Save clipboard.
old_clipboard = g.app.gui.getTextFromClipboard()
# Paste the contents of CheetSheet.leo into c.
c2 = c.openCheatSheet(redraw=False)
if c2:
for p2 in c2.rootPosition().self_and_siblings():
c2.selectPosition(p2)
c2.copyOutline()
p = c.pasteOutline()
c.selectPosition(p)
p.contract()
p.clearDirty()
c2.close(new_c=c)
root = c.rootPosition()
if root.h == g.shortFileName(fn):
root.doDelete(newNode=root.next())
p = g.findNodeAnywhere(c, "Leo's cheat sheet")
if p:
c.selectPosition(p)
p.expand()
c.target_language = "rest"
# Settings not parsed the first time.
c.setChanged(False)
c.redraw()
# #933: Restore clipboard
g.app.gui.replaceClipboardWith(old_clipboard)
return c
|
https://github.com/leo-editor/leo-editor/issues/1201
|
(leo-dev) matt@SURFACE C:\Users\mattw\t
leo-m
Leo 6.0-devel, devel branch, build e86b1c87b6
2019-06-13 17:47:36 -0500
Using default leo file name:
C:/Users/mattw/t/.leo/workbook.leo
OleSetClipboard: Failed to set mime data (text/plain) on clipboard: COM error 0xffffffff800401d0 (Unknown error 0x0800401d0) (The parameter is incorrect.) selectPosition Warning: no p run,load,doPostPluginsInit,openEmptyWorkBook
Traceback (most recent call last):
File "c:\apps\miniconda3\envs\leo-dev\Scripts\leo-m-script.py", line 11, in <module>
load_entry_point('leo', 'console_scripts', 'leo-m')()
File "c:\users\mattw\code\leo-editor\leo\core\runLeo.py", line 73, in run
g.app.loadManager.load(fileName, pymacs)
File "c:\users\mattw\code\leo-editor\leo\core\leoApp.py", line 2375, in load
ok = lm.doPostPluginsInit()
File "c:\users\mattw\code\leo-editor\leo\core\leoApp.py", line 2433, in doPostPluginsInit
c1 = lm.openEmptyWorkBook()
File "c:\users\mattw\code\leo-editor\leo\core\leoApp.py", line 2488, in openEmptyWorkBook
p.contract()
AttributeError: 'NoneType' object has no attribute 'contract'
|
AttributeError
|
def make_at_clean_outline(self, fn, root, s, rev):
"""
Create a hidden temp outline from lines without sentinels.
root is the @<file> node for fn.
s is the contents of the (public) file, without sentinels.
"""
# A specialized version of at.readOneAtCleanNode.
hidden_c = leoCommands.Commands(fn, gui=g.app.nullGui)
at = hidden_c.atFileCommands
x = hidden_c.shadowController
hidden_c.frame.createFirstTreeNode()
hidden_root = hidden_c.rootPosition()
# copy root to hidden root, including gnxs.
root.copyTreeFromSelfTo(hidden_root, copyGnxs=True)
hidden_root.h = fn + ":" + rev if rev else fn
# Set at.encoding first.
at.initReadIvars(hidden_root, fn)
# Must be called before at.scanAllDirectives.
at.scanAllDirectives(hidden_root)
# Sets at.startSentinelComment/endSentinelComment.
new_public_lines = g.splitLines(s)
old_private_lines = at.write_at_clean_sentinels(hidden_root)
marker = x.markerFromFileLines(old_private_lines, fn)
old_public_lines, junk = x.separate_sentinels(old_private_lines, marker)
if old_public_lines:
# Fix #1136: The old lines might not exist.
new_private_lines = x.propagate_changed_lines(
new_public_lines, old_private_lines, marker, p=hidden_root
)
at.fast_read_into_root(
c=hidden_c,
contents="".join(new_private_lines),
gnx2vnode={},
path=fn,
root=hidden_root,
)
return hidden_c
|
def make_at_clean_outline(self, fn, root, s, rev):
"""
Create a hidden temp outline from lines without sentinels.
root is the @<file> node for fn.
s is the contents of the (public) file, without sentinels.
"""
# A specialized version of at.readOneAtCleanNode.
hidden_c = leoCommands.Commands(fn, gui=g.app.nullGui)
at = hidden_c.atFileCommands
x = hidden_c.shadowController
hidden_c.frame.createFirstTreeNode()
hidden_root = hidden_c.rootPosition()
# copy root to hidden root, including gnxs.
root.copyTreeFromSelfTo(hidden_root, copyGnxs=True)
hidden_root.h = fn + ":" + rev if rev else fn
# Set at.encoding first.
at.initReadIvars(hidden_root, fn)
# Must be called before at.scanAllDirectives.
at.scanAllDirectives(hidden_root)
# Sets at.startSentinelComment/endSentinelComment.
new_public_lines = g.splitLines(s)
old_private_lines = at.write_at_clean_sentinels(hidden_root)
marker = x.markerFromFileLines(old_private_lines, fn)
old_public_lines, junk = x.separate_sentinels(old_private_lines, marker)
assert old_public_lines
new_private_lines = x.propagate_changed_lines(
new_public_lines, old_private_lines, marker, p=hidden_root
)
at.fast_read_into_root(
c=hidden_c,
contents="".join(new_private_lines),
gnx2vnode={},
path=fn,
root=hidden_root,
)
return hidden_c
|
https://github.com/leo-editor/leo-editor/issues/1136
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 320, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 342, in gitDiff
GitDiffController(c=self.c).git_diff(rev1='HEAD')
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 584, in git_diff
ok = self.diff_revs(rev1, rev2)
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 604, in diff_revs
self.diff_file(fn=fn, rev1=rev1, rev2=rev2)
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 634, in diff_file
c1 = self.make_at_clean_outline(fn, root, s1, rev1)
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 807, in make_at_clean_outline
assert old_public_lines
AssertionError
|
AssertionError
|
def find_git_working_directory(self, directory):
"""Return the git working directory, starting at directory."""
while directory:
if g.os_path_exists(g.os_path_finalize_join(directory, ".git")):
return directory
path2 = g.os_path_finalize_join(directory, "..")
if path2 == directory:
break
directory = path2
return None
|
def find_git_working_directory(self, directory):
"""Return the git working directory, starting at directory."""
assert directory
while directory:
if g.os_path_exists(g.os_path_finalize_join(directory, ".git")):
return directory
path2 = g.os_path_finalize_join(directory, "..")
if path2 == directory:
break
directory = path2
return None
|
https://github.com/leo-editor/leo-editor/issues/1136
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 320, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 342, in gitDiff
GitDiffController(c=self.c).git_diff(rev1='HEAD')
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 584, in git_diff
ok = self.diff_revs(rev1, rev2)
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 604, in diff_revs
self.diff_file(fn=fn, rev1=rev1, rev2=rev2)
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 634, in diff_file
c1 = self.make_at_clean_outline(fn, root, s1, rev1)
File "c:\leo.repo\leo-editor\leo\commands\editFileCommands.py", line 807, in make_at_clean_outline
assert old_public_lines
AssertionError
|
AssertionError
|
def scan(self, s, parent):
"""Create an outline from a MindMap (.csv) file."""
# pylint: disable=no-member
# pylint confuses this module with the stdlib json module
c, d, self.gnx_dict = self.c, json.loads(s), {}
try:
for d2 in d.get("nodes", []):
gnx = d2.get("gnx")
self.gnx_dict[gnx] = d2
top_d = d.get("top")
if top_d:
# Don't set parent.h or parent.gnx or parent.v.u.
parent.b = top_d.get("b") or ""
self.create_nodes(parent, top_d)
c.redraw()
except AttributeError:
# Partial fix for #1098: issue advice.
g.error("Can not import %s" % parent.h)
g.es("Leo can only read .json files that Leo itself wrote")
g.es("Workaround: copy your .json text into @auto x.json.")
g.es("Leo will read the file correctly when you reload your outline.")
return bool(top_d)
|
def scan(self, s, parent):
"""Create an outline from a MindMap (.csv) file."""
# pylint: disable=no-member
# pylint confuses this module with the stdlib json module
c, d, self.gnx_dict = self.c, json.loads(s), {}
for d2 in d.get("nodes", []):
gnx = d2.get("gnx")
self.gnx_dict[gnx] = d2
top_d = d.get("top")
if top_d:
# Don't set parent.h or parent.gnx or parent.v.u.
parent.b = top_d.get("b") or ""
self.create_nodes(parent, top_d)
c.redraw()
return bool(top_d)
|
https://github.com/leo-editor/leo-editor/issues/1098
|
Exception running JSON_Scanner
Traceback (most recent call last):
File "/home/dalcolmo/bin/leo-editor/leo/core/leoApp.py", line 1530, in scanner_for_ext_cb
return scanner.run(s, parent)
File "/home/dalcolmo/bin/leo-editor/leo/plugins/importers/leo_json.py", line 61, in run
ok = self.scan(s, parent)
File "/home/dalcolmo/bin/leo-editor/leo/plugins/importers/leo_json.py", line 130, in scan
for d2 in d.get('nodes', []):
AttributeError: 'list' object has no attribute 'get'
|
AttributeError
|
def scan(self, s, parent):
"""Create an outline from a MindMap (.csv) file."""
# pylint: disable=no-member
# pylint confuses this module with the stdlib json module
c, d, self.gnx_dict = self.c, json.loads(s), {}
try:
for d2 in d.get("nodes", []):
gnx = d2.get("gnx")
self.gnx_dict[gnx] = d2
top_d = d.get("top")
if top_d:
# Don't set parent.h or parent.gnx or parent.v.u.
parent.b = top_d.get("b") or ""
self.create_nodes(parent, top_d)
c.redraw()
return bool(top_d)
except AttributeError:
# Fix #1098
c = self.c
parent.b = repr(d)
c.redraw()
return True
|
def scan(self, s, parent):
"""Create an outline from a MindMap (.csv) file."""
# pylint: disable=no-member
# pylint confuses this module with the stdlib json module
c, d, self.gnx_dict = self.c, json.loads(s), {}
try:
for d2 in d.get("nodes", []):
gnx = d2.get("gnx")
self.gnx_dict[gnx] = d2
top_d = d.get("top")
if top_d:
# Don't set parent.h or parent.gnx or parent.v.u.
parent.b = top_d.get("b") or ""
self.create_nodes(parent, top_d)
c.redraw()
except AttributeError:
# Partial fix for #1098: issue advice.
g.error("Can not import %s" % parent.h)
g.es("Leo can only read .json files that Leo itself wrote")
g.es("Workaround: copy your .json text into @auto x.json.")
g.es("Leo will read the file correctly when you reload your outline.")
return bool(top_d)
|
https://github.com/leo-editor/leo-editor/issues/1098
|
Exception running JSON_Scanner
Traceback (most recent call last):
File "/home/dalcolmo/bin/leo-editor/leo/core/leoApp.py", line 1530, in scanner_for_ext_cb
return scanner.run(s, parent)
File "/home/dalcolmo/bin/leo-editor/leo/plugins/importers/leo_json.py", line 61, in run
ok = self.scan(s, parent)
File "/home/dalcolmo/bin/leo-editor/leo/plugins/importers/leo_json.py", line 130, in scan
for d2 in d.get('nodes', []):
AttributeError: 'list' object has no attribute 'get'
|
AttributeError
|
def getTextFromClipboard(self):
"""Get a unicode string from the clipboard."""
# Fix #971.
if not Tk:
return g.u("")
root = Tk()
root.withdraw()
try:
s = root.clipboard_get()
except Exception: # _tkinter.TclError:
s = ""
root.destroy()
return g.toUnicode(s)
|
def getTextFromClipboard(self):
"""Get a unicode string from the clipboard."""
root = Tk()
root.withdraw()
try:
s = root.clipboard_get()
except Exception: # _tkinter.TclError:
s = ""
root.destroy()
return g.toUnicode(s)
|
https://github.com/leo-editor/leo-editor/issues/971
|
./launchLeo-console.py
import-jupyter-notebook requires nbformat package
setting leoID from os.getenv('USER'): 'benoit'
reading settings in /home/benoit/opt/leo-editor/leo/config/leoSettings.leo
loading npyscreen
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Git repo info: branch = master, commit = 6a9b1c0d2909
Python 2.7.15, LeoGui: dummy version
linux2
** isPython3: False
Traceback (most recent call last):
File "./launchLeo-console.py", line 8, in <module>
leo.core.runLeo.run_console()
File "/home/benoit/opt/leo-editor/leo/core/runLeo.py", line 78, in run_console
run(*args, **keywords)
File "/home/benoit/opt/leo-editor/leo/core/runLeo.py", line 72, in run
g.app.loadManager.load(fileName, pymacs)
File "/home/benoit/opt/leo-editor/leo/core/leoApp.py", line 2246, in load
ok = lm.doPostPluginsInit()
File "/home/benoit/opt/leo-editor/leo/core/leoApp.py", line 2300, in doPostPluginsInit
c1 = lm.openEmptyWorkBook()
File "/home/benoit/opt/leo-editor/leo/core/leoApp.py", line 2347, in openEmptyWorkBook
old_clipboard = g.app.gui.getTextFromClipboard()
File "/home/benoit/opt/leo-editor/leo/plugins/cursesGui2.py", line 1608, in getTextFromClipboard
root = Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1822, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
|
_tkinter.TclError
|
def replaceClipboardWith(self, s):
"""Replace the clipboard with the string s."""
if not Tk:
return
root = Tk()
root.withdraw()
root.clipboard_clear()
root.clipboard_append(s)
root.destroy()
|
def replaceClipboardWith(self, s):
"""Replace the clipboard with the string s."""
root = Tk()
root.withdraw()
root.clipboard_clear()
root.clipboard_append(s)
root.destroy()
|
https://github.com/leo-editor/leo-editor/issues/971
|
./launchLeo-console.py
import-jupyter-notebook requires nbformat package
setting leoID from os.getenv('USER'): 'benoit'
reading settings in /home/benoit/opt/leo-editor/leo/config/leoSettings.leo
loading npyscreen
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Git repo info: branch = master, commit = 6a9b1c0d2909
Python 2.7.15, LeoGui: dummy version
linux2
** isPython3: False
Traceback (most recent call last):
File "./launchLeo-console.py", line 8, in <module>
leo.core.runLeo.run_console()
File "/home/benoit/opt/leo-editor/leo/core/runLeo.py", line 78, in run_console
run(*args, **keywords)
File "/home/benoit/opt/leo-editor/leo/core/runLeo.py", line 72, in run
g.app.loadManager.load(fileName, pymacs)
File "/home/benoit/opt/leo-editor/leo/core/leoApp.py", line 2246, in load
ok = lm.doPostPluginsInit()
File "/home/benoit/opt/leo-editor/leo/core/leoApp.py", line 2300, in doPostPluginsInit
c1 = lm.openEmptyWorkBook()
File "/home/benoit/opt/leo-editor/leo/core/leoApp.py", line 2347, in openEmptyWorkBook
old_clipboard = g.app.gui.getTextFromClipboard()
File "/home/benoit/opt/leo-editor/leo/plugins/cursesGui2.py", line 1608, in getTextFromClipboard
root = Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1822, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
|
_tkinter.TclError
|
def configuredcommands_rclick(c, p, menu):
"""Provide "edit in EDITOR" context menu item"""
config = c.config.getData("contextmenu_commands")
if config:
cmds = [el.split(None, 1) for el in config]
for data in cmds:
# Fix #1084
try:
cmd, desc = data
except ValueError:
g.es_print("Invalid @data contextmenu_commands")
continue
desc = desc.strip()
action = menu.addAction(desc)
# action.setToolTip(cmd)
def create_callback(cm):
return lambda: c.k.simulateCommand(cm)
configcmd_rclick_cb = create_callback(cmd)
action.triggered.connect(configcmd_rclick_cb)
|
def configuredcommands_rclick(c, p, menu):
"""Provide "edit in EDITOR" context menu item"""
config = c.config.getData("contextmenu_commands")
if config:
cmds = [el.split(None, 1) for el in config]
for cmd, desc in cmds:
desc = desc.strip()
action = menu.addAction(desc)
# action.setToolTip(cmd)
def create_callback(cm):
return lambda: c.k.simulateCommand(cm)
configcmd_rclick_cb = create_callback(cmd)
action.triggered.connect(configcmd_rclick_cb)
|
https://github.com/leo-editor/leo-editor/issues/1084
|
Traceback (most recent call last):
File "/home/jnicoll/leo-editor/leo/plugins/qt_tree.py", line 732, in onContextMenu
h(c, p, menu)
File "/home/jnicoll/leo-editor/leo/plugins/contextmenu.py", line 109, in configuredcommands_rclick
for cmd, desc in cmds:
ValueError: need more than 1 value to unpack
Aborted (core dumped)
|
ValueError
|
def onContextMenu(self, point):
c = self.c
w = self.treeWidget
handlers = g.tree_popup_handlers
menu = QtWidgets.QMenu()
menuPos = w.mapToGlobal(point)
if not handlers:
menu.addAction("No popup handlers")
p = c.p.copy()
done = set()
for handler in handlers:
# every handler has to add it's QActions by itself
if handler in done:
# do not run the same handler twice
continue
try:
handler(c, p, menu)
except Exception:
g.es_print("Exception executing right-click handler")
g.es_exception()
menu.popup(menuPos)
self._contextmenu = menu
|
def onContextMenu(self, point):
c = self.c
w = self.treeWidget
handlers = g.tree_popup_handlers
menu = QtWidgets.QMenu()
menuPos = w.mapToGlobal(point)
if not handlers:
menu.addAction("No popup handlers")
p = c.p.copy()
done = set()
for h in handlers:
# every handler has to add it's QActions by itself
if h in done:
# do not run the same handler twice
continue
h(c, p, menu)
menu.popup(menuPos)
self._contextmenu = menu
|
https://github.com/leo-editor/leo-editor/issues/1084
|
Traceback (most recent call last):
File "/home/jnicoll/leo-editor/leo/plugins/qt_tree.py", line 732, in onContextMenu
h(c, p, menu)
File "/home/jnicoll/leo-editor/leo/plugins/contextmenu.py", line 109, in configuredcommands_rclick
for cmd, desc in cmds:
ValueError: need more than 1 value to unpack
Aborted (core dumped)
|
ValueError
|
def readFile(self, path=None, s=None):
if not s:
with open(path, "rb") as f:
s = f.read()
s = s.replace(b"\x0c", b"")
# Fix #1036.
return self.readWithElementTree(path, s)
|
def readFile(self, path=None, s=None):
if not s:
with open(path, "rb") as f:
s = f.read()
return self.readWithElementTree(path, s)
|
https://github.com/leo-editor/leo-editor/issues/1036
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\launchLeo.py", line 8, in <module>
leo.core.runLeo.run()
File "c:\leo.repo\leo-editor\leo\core\runLeo.py", line 72, in run
g.app.loadManager.load(fileName, pymacs)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2262, in load
lm.doPrePluginsInit(fileName, pymacs)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2432, in doPrePluginsInit
lm.readGlobalSettingsFiles()
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2202, in readGlobalSettingsFiles
theme_path = lm.computeThemeFilePath()
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 1845, in computeThemeFilePath
theme_c = lm.openSettingsFile(path)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2171, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 653, in openLeoFile
silent=silent,
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 516, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(path, s)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 91, in readWithElementTree
hidden_v = self.scanVnodes(gnx2body, self.gnx2vnode, gnx2ua, v_elements)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 312, in scanVnodes
v_element_visitor(v_elements, hidden_v)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 302, in v_element_visitor
v_element_visitor(e, v)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 302, in v_element_visitor
v_element_visitor(e, v)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 246, in v_element_visitor
gnx = e.attrib['t']
KeyError: 't'
|
KeyError
|
def readFile(self, path=None, s=None):
if not s:
with open(path, "rb") as f:
s = f.read()
# s = s.replace(b'\x0c', b'').replace(b'0x00', b'')
s = s.translate(None, self.translate_table)
# Fix #1036 and #1046.
return self.readWithElementTree(path, s)
|
def readFile(self, path=None, s=None):
if not s:
with open(path, "rb") as f:
s = f.read()
s = s.replace(b"\x0c", b"")
# Fix #1036.
return self.readWithElementTree(path, s)
|
https://github.com/leo-editor/leo-editor/issues/1036
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\launchLeo.py", line 8, in <module>
leo.core.runLeo.run()
File "c:\leo.repo\leo-editor\leo\core\runLeo.py", line 72, in run
g.app.loadManager.load(fileName, pymacs)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2262, in load
lm.doPrePluginsInit(fileName, pymacs)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2432, in doPrePluginsInit
lm.readGlobalSettingsFiles()
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2202, in readGlobalSettingsFiles
theme_path = lm.computeThemeFilePath()
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 1845, in computeThemeFilePath
theme_c = lm.openSettingsFile(path)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2171, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 653, in openLeoFile
silent=silent,
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 516, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(path, s)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 91, in readWithElementTree
hidden_v = self.scanVnodes(gnx2body, self.gnx2vnode, gnx2ua, v_elements)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 312, in scanVnodes
v_element_visitor(v_elements, hidden_v)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 302, in v_element_visitor
v_element_visitor(e, v)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 302, in v_element_visitor
v_element_visitor(e, v)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 246, in v_element_visitor
gnx = e.attrib['t']
KeyError: 't'
|
KeyError
|
def scanVnodes(self, gnx2body, gnx2vnode, gnx2ua, v_elements):
c, fc = self.c, self.c.fileCommands
# @+<< define v_element_visitor >>
# @+node:ekr.20180605102822.1: *6* << define v_element_visitor >>
def v_element_visitor(parent_e, parent_v):
"""Visit the given element, creating or updating the parent vnode."""
for e in parent_e:
assert e.tag in ("v", "vh"), e.tag
if e.tag == "vh":
parent_v._headString = g.toUnicode(e.text or "")
continue
gnx = e.attrib["t"]
v = gnx2vnode.get(gnx)
if v:
# A clone
parent_v.children.append(v)
v.parents.append(parent_v)
# The body overrides any previous body text.
body = g.toUnicode(gnx2body.get(gnx) or "")
assert g.isUnicode(body), body.__class__.__name__
v._bodyString = body
else:
# @+<< Make a new vnode, linked to the parent >>
# @+node:ekr.20180605075042.1: *7* << Make a new vnode, linked to the parent >>
v = leoNodes.VNode(context=c, gnx=gnx)
gnx2vnode[gnx] = v
parent_v.children.append(v)
v.parents.append(parent_v)
body = g.toUnicode(gnx2body.get(gnx) or "")
assert g.isUnicode(body), body.__class__.__name__
v._bodyString = body
v._headString = "PLACE HOLDER"
# @-<< Make a new vnode, linked to the parent >>
# @+<< handle all other v attributes >>
# @+node:ekr.20180605075113.1: *7* << handle all other v attributes >>
# Like fc.handleVnodeSaxAttrutes.
#
# The native attributes of <v> elements are a, t, vtag, tnodeList,
# marks, expanded, and descendentTnode/VnodeUnknownAttributes.
d = e.attrib
s = d.get("tnodeList", "")
tnodeList = s and s.split(",")
if tnodeList:
# This tnodeList will be resolved later.
v.tempTnodeList = tnodeList
s = d.get("descendentTnodeUnknownAttributes")
if s:
aDict = fc.getDescendentUnknownAttributes(s, v=v)
if aDict:
fc.descendentTnodeUaDictList.append(aDict)
s = d.get("descendentVnodeUnknownAttributes")
if s:
aDict = fc.getDescendentUnknownAttributes(s, v=v)
if aDict:
fc.descendentVnodeUaDictList.append(
(v, aDict),
)
#
# Handle vnode uA's
uaDict = gnx2ua[gnx]
# gnx2ua is a defaultdict(dict)
# It might already exists because of tnode uA's.
for key, val in d.items():
if key not in self.nativeVnodeAttributes:
uaDict[key] = self.resolveUa(key, val)
if uaDict:
v.unknownAttributes = uaDict
# @-<< handle all other v attributes >>
# Handle all inner elements.
v_element_visitor(e, v)
# @-<< define v_element_visitor >>
#
# Create the hidden root vnode.
gnx = "hidden-root-vnode-gnx"
hidden_v = leoNodes.VNode(context=c, gnx=gnx)
hidden_v._headString = g.u("<hidden root vnode>")
gnx2vnode[gnx] = hidden_v
#
# Traverse the tree of v elements.
v_element_visitor(v_elements, hidden_v)
return hidden_v
|
def scanVnodes(self, gnx2body, gnx2vnode, gnx2ua, v_elements):
c, fc = self.c, self.c.fileCommands
# @+<< define v_element_visitor >>
# @+node:ekr.20180605102822.1: *6* << define v_element_visitor >>
def v_element_visitor(parent_e, parent_v):
"""Visit the given element, creating or updating the parent vnode."""
for e in parent_e:
assert e.tag in ("v", "vh"), e.tag
if e.tag == "vh":
parent_v._headString = g.toUnicode(e.text or "")
continue
gnx = e.attrib["t"]
v = gnx2vnode.get(gnx)
if v:
# A clone
parent_v.children.append(v)
v.parents.append(parent_v)
# The body overrides any previous body text.
body = g.toUnicode(gnx2body.get(gnx) or "")
assert g.isUnicode(body), body.__class__.__name__
v._bodyString = body
else:
# @+<< Make a new vnode, linked to the parent >>
# @+node:ekr.20180605075042.1: *7* << Make a new vnode, linked to the parent >>
v = leoNodes.VNode(context=c, gnx=gnx)
gnx2vnode[gnx] = v
parent_v.children.append(v)
v.parents.append(parent_v)
body = g.toUnicode(gnx2body.get(gnx) or "")
assert g.isUnicode(body), body.__class__.__name__
v._bodyString = body
v._headString = "PLACE HOLDER"
# @-<< Make a new vnode, linked to the parent >>
# @+<< handle all other v attributes >>
# @+node:ekr.20180605075113.1: *7* << handle all other v attributes >>
# Like fc.handleVnodeSaxAttrutes.
#
# The native attributes of <v> elements are a, t, vtag, tnodeList,
# marks, expanded, and descendentTnode/VnodeUnknownAttributes.
d = e.attrib
s = d.get("tnodeList", "")
tnodeList = s and s.split(",")
if tnodeList:
# This tnodeList will be resolved later.
v.tempTnodeList = tnodeList
s = d.get("descendentTnodeUnknownAttributes")
if s:
aDict = fc.getDescendentUnknownAttributes(s, v=v)
if aDict:
fc.descendentTnodeUaDictList.append(aDict)
s = d.get("descendentVnodeUnknownAttributes")
if s:
aDict = fc.getDescendentUnknownAttributes(s, v=v)
if aDict:
fc.descendentVnodeUaDictList.append(
(v, aDict),
)
#
# Handle vnode uA's
uaDict = gnx2ua.get(gnx)
# gnx2ua is a defaultdict(dict)
# It might already exists because of tnode uA's.
for key, val in d.items():
if key not in self.nativeVnodeAttributes:
uaDict[key] = self.resolveUa(key, val)
if uaDict:
v.unknownAttributes = uaDict
# @-<< handle all other v attributes >>
# Handle all inner elements.
v_element_visitor(e, v)
# @-<< define v_element_visitor >>
#
# Create the hidden root vnode.
gnx = "hidden-root-vnode-gnx"
hidden_v = leoNodes.VNode(context=c, gnx=gnx)
hidden_v._headString = g.u("<hidden root vnode>")
gnx2vnode[gnx] = hidden_v
#
# Traverse the tree of v elements.
v_element_visitor(v_elements, hidden_v)
return hidden_v
|
https://github.com/leo-editor/leo-editor/issues/1017
|
$ leogrep earthquake *.leo
Traceback (most recent call last):
File "/pri/bin/leogrep", line 151, in <module>
main()
File "/pri/bin/leogrep", line 135, in main
cmdr = bridge.openLeoFile(fpn)
File "/pri/git/leo-editor/leo/core/leoBridge.py", line 262, in openLeoFile
c = self.createFrame(fileName)
File "/pri/git/leo-editor/leo/core/leoBridge.py", line 293, in createFrame
c = g.openWithFileName(fileName)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 3694, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 3093, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 1999, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 2164, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 652, in openLeoFile
silent=silent,
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 515, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(path, s)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 91, in readWithElementTree
hidden_v = self.scanVnodes(gnx2body, self.gnx2vnode, gnx2ua, v_elements)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 312, in scanVnodes
v_element_visitor(v_elements, hidden_v)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 297, in v_element_visitor
uaDict[key] = self.resolveUa(key, val)
TypeError: 'NoneType' object does not support item assignment
[leogrep.zip](https://github.com/leo-editor/leo-editor/files/2593365/leogrep.zip)
|
TypeError
|
def v_element_visitor(parent_e, parent_v):
"""Visit the given element, creating or updating the parent vnode."""
for e in parent_e:
assert e.tag in ("v", "vh"), e.tag
if e.tag == "vh":
parent_v._headString = g.toUnicode(e.text or "")
continue
gnx = e.attrib["t"]
v = gnx2vnode.get(gnx)
if v:
# A clone
parent_v.children.append(v)
v.parents.append(parent_v)
# The body overrides any previous body text.
body = g.toUnicode(gnx2body.get(gnx) or "")
assert g.isUnicode(body), body.__class__.__name__
v._bodyString = body
else:
# @+<< Make a new vnode, linked to the parent >>
# @+node:ekr.20180605075042.1: *7* << Make a new vnode, linked to the parent >>
v = leoNodes.VNode(context=c, gnx=gnx)
gnx2vnode[gnx] = v
parent_v.children.append(v)
v.parents.append(parent_v)
body = g.toUnicode(gnx2body.get(gnx) or "")
assert g.isUnicode(body), body.__class__.__name__
v._bodyString = body
v._headString = "PLACE HOLDER"
# @-<< Make a new vnode, linked to the parent >>
# @+<< handle all other v attributes >>
# @+node:ekr.20180605075113.1: *7* << handle all other v attributes >>
# Like fc.handleVnodeSaxAttrutes.
#
# The native attributes of <v> elements are a, t, vtag, tnodeList,
# marks, expanded, and descendentTnode/VnodeUnknownAttributes.
d = e.attrib
s = d.get("tnodeList", "")
tnodeList = s and s.split(",")
if tnodeList:
# This tnodeList will be resolved later.
v.tempTnodeList = tnodeList
s = d.get("descendentTnodeUnknownAttributes")
if s:
aDict = fc.getDescendentUnknownAttributes(s, v=v)
if aDict:
fc.descendentTnodeUaDictList.append(aDict)
s = d.get("descendentVnodeUnknownAttributes")
if s:
aDict = fc.getDescendentUnknownAttributes(s, v=v)
if aDict:
fc.descendentVnodeUaDictList.append(
(v, aDict),
)
#
# Handle vnode uA's
uaDict = gnx2ua[gnx]
# gnx2ua is a defaultdict(dict)
# It might already exists because of tnode uA's.
for key, val in d.items():
if key not in self.nativeVnodeAttributes:
uaDict[key] = self.resolveUa(key, val)
if uaDict:
v.unknownAttributes = uaDict
# @-<< handle all other v attributes >>
# Handle all inner elements.
v_element_visitor(e, v)
|
def v_element_visitor(parent_e, parent_v):
"""Visit the given element, creating or updating the parent vnode."""
for e in parent_e:
assert e.tag in ("v", "vh"), e.tag
if e.tag == "vh":
parent_v._headString = g.toUnicode(e.text or "")
continue
gnx = e.attrib["t"]
v = gnx2vnode.get(gnx)
if v:
# A clone
parent_v.children.append(v)
v.parents.append(parent_v)
# The body overrides any previous body text.
body = g.toUnicode(gnx2body.get(gnx) or "")
assert g.isUnicode(body), body.__class__.__name__
v._bodyString = body
else:
# @+<< Make a new vnode, linked to the parent >>
# @+node:ekr.20180605075042.1: *7* << Make a new vnode, linked to the parent >>
v = leoNodes.VNode(context=c, gnx=gnx)
gnx2vnode[gnx] = v
parent_v.children.append(v)
v.parents.append(parent_v)
body = g.toUnicode(gnx2body.get(gnx) or "")
assert g.isUnicode(body), body.__class__.__name__
v._bodyString = body
v._headString = "PLACE HOLDER"
# @-<< Make a new vnode, linked to the parent >>
# @+<< handle all other v attributes >>
# @+node:ekr.20180605075113.1: *7* << handle all other v attributes >>
# Like fc.handleVnodeSaxAttrutes.
#
# The native attributes of <v> elements are a, t, vtag, tnodeList,
# marks, expanded, and descendentTnode/VnodeUnknownAttributes.
d = e.attrib
s = d.get("tnodeList", "")
tnodeList = s and s.split(",")
if tnodeList:
# This tnodeList will be resolved later.
v.tempTnodeList = tnodeList
s = d.get("descendentTnodeUnknownAttributes")
if s:
aDict = fc.getDescendentUnknownAttributes(s, v=v)
if aDict:
fc.descendentTnodeUaDictList.append(aDict)
s = d.get("descendentVnodeUnknownAttributes")
if s:
aDict = fc.getDescendentUnknownAttributes(s, v=v)
if aDict:
fc.descendentVnodeUaDictList.append(
(v, aDict),
)
#
# Handle vnode uA's
uaDict = gnx2ua.get(gnx)
# gnx2ua is a defaultdict(dict)
# It might already exists because of tnode uA's.
for key, val in d.items():
if key not in self.nativeVnodeAttributes:
uaDict[key] = self.resolveUa(key, val)
if uaDict:
v.unknownAttributes = uaDict
# @-<< handle all other v attributes >>
# Handle all inner elements.
v_element_visitor(e, v)
|
https://github.com/leo-editor/leo-editor/issues/1017
|
$ leogrep earthquake *.leo
Traceback (most recent call last):
File "/pri/bin/leogrep", line 151, in <module>
main()
File "/pri/bin/leogrep", line 135, in main
cmdr = bridge.openLeoFile(fpn)
File "/pri/git/leo-editor/leo/core/leoBridge.py", line 262, in openLeoFile
c = self.createFrame(fileName)
File "/pri/git/leo-editor/leo/core/leoBridge.py", line 293, in createFrame
c = g.openWithFileName(fileName)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 3694, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 3093, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 1999, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 2164, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 652, in openLeoFile
silent=silent,
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 515, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(path, s)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 91, in readWithElementTree
hidden_v = self.scanVnodes(gnx2body, self.gnx2vnode, gnx2ua, v_elements)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 312, in scanVnodes
v_element_visitor(v_elements, hidden_v)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 297, in v_element_visitor
uaDict[key] = self.resolveUa(key, val)
TypeError: 'NoneType' object does not support item assignment
[leogrep.zip](https://github.com/leo-editor/leo-editor/files/2593365/leogrep.zip)
|
TypeError
|
def git_version(file, version=None):
"""Fetch from Git: {tag} {distance-from-tag} {current commit hash}
Return as semantic version string compliant with PEP440"""
root = os.path.dirname(os.path.realpath(file))
try:
tag, distance, commit = g.gitDescribe(root)
# 5.6b2, 55, e1129da
ctag = clean_git_tag(tag)
# version = get_semver(ctag)
version = ctag
if int(distance) > 0:
version = "{}-dev{}".format(version, distance)
except IndexError:
print("Attempt to `git describe` failed with IndexError")
except FileNotFoundError:
print("Attempt to `git describe` failed with FileNotFoundError")
return version
|
def git_version(file):
"""Fetch from Git: {tag} {distance-from-tag} {current commit hash}
Return as semantic version string compliant with PEP440"""
root = os.path.dirname(os.path.realpath(file))
try:
tag, distance, commit = g.gitDescribe(root)
# 5.6b2, 55, e1129da
ctag = clean_git_tag(tag)
# version = get_semver(ctag)
version = ctag
if int(distance) > 0:
version = "{}-dev{}".format(version, distance)
except IndexError:
version = None
return version
|
https://github.com/leo-editor/leo-editor/issues/1019
|
pip install .
Processing d:\matt\code\leo-build
Installing build dependencies ... done
Complete output from command python setup.py egg_info:
Removing build, dist and egg directories
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Matt\AppData\Local\Temp\pip-req-build-vau006t6\setup.py", line 166, in <module>
version=get_version(__file__),
File "C:\Users\Matt\AppData\Local\Temp\pip-req-build-vau006t6\setup.py", line 32, in get_version
version = git_version(file)
File "C:\Users\Matt\AppData\Local\Temp\pip-req-build-vau006t6\setup.py", line 42, in git_version
tag, distance, commit = g.gitDescribe(root)
File "C:\Users\Matt\AppData\Local\Temp\pip-req-build-vau006t6\leo\core\leoGlobals.py", line 4887, in gitDescribe
describe = g.execGitCommand('git describe --tags --long', path)
File "C:\Users\Matt\AppData\Local\Temp\pip-req-build-vau006t6\leo\core\leoGlobals.py", line 4690, in execGitCommand
shell=False,
File "c:\apps\Miniconda3\envs\leo-build\lib\subprocess.py", line 769, in __init__
restore_signals, start_new_session)
File "c:\apps\Miniconda3\envs\leo-build\lib\subprocess.py", line 1172, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Matt\AppData\Local\Temp\pip-req-build-vau006t6\
|
FileNotFoundError
|
def computeThemeFilePath(self):
"""Return the absolute path to the theme .leo file."""
lm = self
resolve = self.resolve_theme_path
#
# Step 1: Use the --theme file if it exists
path = resolve(lm.options.get("theme_path"), tag="--theme")
if path:
return path
#
# Step 2: look for the @string theme-name setting in the first loaded file.
# This is a hack, but especially useful for test*.leo files in leo/themes.
path = lm.files and lm.files[0]
if path and g.os_path_exists(path):
# Tricky: we must call lm.computeLocalSettings *here*.
theme_c = lm.openSettingsFile(path)
if theme_c:
settings_d, junk_shortcuts_d = lm.computeLocalSettings(
c=theme_c,
settings_d=lm.globalSettingsDict,
bindings_d=lm.globalBindingsDict,
localFlag=False,
)
setting = settings_d.get_string_setting("theme-name")
if setting:
tag = theme_c.shortFileName()
path = resolve(setting, tag=tag)
if path:
return path
#
# Finally, use the setting in myLeoSettings.leo.
setting = lm.globalSettingsDict.get_string_setting("theme-name")
tag = "myLeoSettings.leo"
return resolve(setting, tag=tag)
|
def computeThemeFilePath(self):
"""Return the absolute path to the theme .leo file."""
lm = self
resolve = self.resolve_theme_path
# Step 1: Use the --theme file if it exists
path = resolve(lm.options.get("theme_path"), tag="--theme")
if path:
return path
# Step 2: look for the @string theme-name setting in the first loaded file.
# This is a hack, but especially useful for test*.leo files in leo/themes.
path = lm.files and lm.files[0]
if path and g.os_path_exists(path):
# Tricky: we must call lm.computeLocalSettings *here*.
theme_c = lm.openSettingsFile(path)
if not theme_c:
return None # Fix #843.
settings_d, junk_shortcuts_d = lm.computeLocalSettings(
c=theme_c,
settings_d=lm.globalSettingsDict,
bindings_d=lm.globalBindingsDict,
localFlag=False,
)
setting = settings_d.get_string_setting("theme-name")
if setting:
tag = theme_c.shortFileName()
path = resolve(setting, tag=tag)
if path:
return path
# Finally, use the setting in myLeoSettings.leo.
setting = lm.globalSettingsDict.get_string_setting("theme-name")
tag = "myLeoSettings.leo"
return resolve(setting, tag=tag)
|
https://github.com/leo-editor/leo-editor/issues/970
|
setting leoID from os.getenv('USER'): 'matt'
reading settings in /home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/config/leoSettings.leo
reading settings in /home/matt/.leo/myLeoSettings.leo
QApplication: invalid style override passed, ignoring it.
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Not running from a git repo
Python 3.6.6, PyQt version 5.11.1
linux
** isPython3: True
reading settings in /home/matt/.leo/workbook.leo
loadOnePlugin: leo.plugins.livecode.init() returned False
reading settings in /home/matt/code/leo-editor/leo/dist/leoDist.leo
Traceback (most recent call last):
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoCommands.py", line 2072, in executeAnyCommand
return command(event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 269, in commander_command_wrapper
method(event=event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/commands/commanderFileCommands.py", line 214, in open
c2 = g.openWithFileName(fileName, old_c=c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 3682, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 3059, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 1973, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 2139, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 631, in openLeoFile
silent=silent,
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 494, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(s)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 73, in readWithElementTree
xroot = ElementTree.fromstring(contents)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML
parser.feed(text)
File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 189, column 1
|
xml.etree.ElementTree.ParseError
|
def createSettingsDicts(self, c, localFlag, theme=False):
import leo.core.leoConfig as leoConfig
if c:
parser = leoConfig.SettingsTreeParser(c, localFlag)
# returns the *raw* shortcutsDict, not a *merged* shortcuts dict.
shortcutsDict, settingsDict = parser.traverse(theme=theme)
return shortcutsDict, settingsDict
return None, None
|
def createSettingsDicts(self, c, localFlag, theme=False):
import leo.core.leoConfig as leoConfig
parser = leoConfig.SettingsTreeParser(c, localFlag)
# returns the *raw* shortcutsDict, not a *merged* shortcuts dict.
shortcutsDict, settingsDict = parser.traverse(theme=theme)
return shortcutsDict, settingsDict
|
https://github.com/leo-editor/leo-editor/issues/970
|
setting leoID from os.getenv('USER'): 'matt'
reading settings in /home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/config/leoSettings.leo
reading settings in /home/matt/.leo/myLeoSettings.leo
QApplication: invalid style override passed, ignoring it.
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Not running from a git repo
Python 3.6.6, PyQt version 5.11.1
linux
** isPython3: True
reading settings in /home/matt/.leo/workbook.leo
loadOnePlugin: leo.plugins.livecode.init() returned False
reading settings in /home/matt/code/leo-editor/leo/dist/leoDist.leo
Traceback (most recent call last):
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoCommands.py", line 2072, in executeAnyCommand
return command(event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 269, in commander_command_wrapper
method(event=event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/commands/commanderFileCommands.py", line 214, in open
c2 = g.openWithFileName(fileName, old_c=c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 3682, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 3059, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 1973, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 2139, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 631, in openLeoFile
silent=silent,
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 494, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(s)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 73, in readWithElementTree
xroot = ElementTree.fromstring(contents)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML
parser.feed(text)
File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 189, column 1
|
xml.etree.ElementTree.ParseError
|
def getPreviousSettings(self, fn):
"""
Return the settings in effect for fn. Typically, this involves
pre-reading fn.
"""
lm = self
settingsName = "settings dict for %s" % g.shortFileName(fn)
shortcutsName = "shortcuts dict for %s" % g.shortFileName(fn)
# A special case: settings in leoSettings.leo do *not* override
# the global settings, that is, settings in myLeoSettings.leo.
isLeoSettings = g.shortFileName(fn).lower() == "leosettings.leo"
exists = g.os_path_exists(fn)
if fn and exists and lm.isLeoFile(fn) and not isLeoSettings:
# Open the file usinging a null gui.
try:
g.app.preReadFlag = True
c = lm.openSettingsFile(fn)
finally:
g.app.preReadFlag = False
# Merge the settings from c into *copies* of the global dicts.
d1, d2 = lm.computeLocalSettings(
c, lm.globalSettingsDict, lm.globalBindingsDict, localFlag=True
)
# d1 and d2 are copies.
d1.setName(settingsName)
d2.setName(shortcutsName)
return PreviousSettings(d1, d2)
#
# The file does not exist, or is not valid.
# Get the settings from the globals settings dicts.
d1 = lm.globalSettingsDict.copy(settingsName)
d2 = lm.globalBindingsDict.copy(shortcutsName)
return PreviousSettings(d1, d2)
|
def getPreviousSettings(self, fn):
"""
Return the settings in effect for fn. Typically, this involves
pre-reading fn.
"""
lm = self
settingsName = "settings dict for %s" % g.shortFileName(fn)
shortcutsName = "shortcuts dict for %s" % g.shortFileName(fn)
# A special case: settings in leoSettings.leo do *not* override
# the global settings, that is, settings in myLeoSettings.leo.
isLeoSettings = g.shortFileName(fn).lower() == "leosettings.leo"
exists = g.os_path_exists(fn)
if fn and exists and lm.isLeoFile(fn) and not isLeoSettings:
# Open the file usinging a null gui.
try:
g.app.preReadFlag = True
c = lm.openSettingsFile(fn)
finally:
g.app.preReadFlag = False
# Merge the settings from c into *copies* of the global dicts.
d1, d2 = lm.computeLocalSettings(
c, lm.globalSettingsDict, lm.globalBindingsDict, localFlag=True
)
# d1 and d2 are copies.
d1.setName(settingsName)
d2.setName(shortcutsName)
else:
# Get the settings from the globals settings dicts.
d1 = lm.globalSettingsDict.copy(settingsName)
d2 = lm.globalBindingsDict.copy(shortcutsName)
return PreviousSettings(d1, d2)
|
https://github.com/leo-editor/leo-editor/issues/970
|
setting leoID from os.getenv('USER'): 'matt'
reading settings in /home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/config/leoSettings.leo
reading settings in /home/matt/.leo/myLeoSettings.leo
QApplication: invalid style override passed, ignoring it.
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Not running from a git repo
Python 3.6.6, PyQt version 5.11.1
linux
** isPython3: True
reading settings in /home/matt/.leo/workbook.leo
loadOnePlugin: leo.plugins.livecode.init() returned False
reading settings in /home/matt/code/leo-editor/leo/dist/leoDist.leo
Traceback (most recent call last):
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoCommands.py", line 2072, in executeAnyCommand
return command(event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 269, in commander_command_wrapper
method(event=event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/commands/commanderFileCommands.py", line 214, in open
c2 = g.openWithFileName(fileName, old_c=c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 3682, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 3059, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 1973, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 2139, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 631, in openLeoFile
silent=silent,
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 494, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(s)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 73, in readWithElementTree
xroot = ElementTree.fromstring(contents)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML
parser.feed(text)
File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 189, column 1
|
xml.etree.ElementTree.ParseError
|
def openFileByName(self, fn, gui, old_c, previousSettings):
"""Read the local file whose full path is fn using the given gui.
fn may be a Leo file (including .leo or zipped file) or an external file.
This is not a pre-read: the previousSettings always exist and
the commander created here persists until the user closes the outline.
Reads the entire outline if fn exists and is a .leo file or zipped file.
Creates an empty outline if fn is a non-existent Leo file.
Creates an wrapper outline if fn is an external file, existing or not.
"""
lm = self
# Disable the log.
g.app.setLog(None)
g.app.lockLog()
# Create the a commander for the .leo file.
# Important. The settings don't matter for pre-reads!
# For second read, the settings for the file are *exactly* previousSettings.
c = g.app.newCommander(fileName=fn, gui=gui, previousSettings=previousSettings)
# Open the file, if possible.
g.doHook("open0")
theFile = lm.openLeoOrZipFile(fn)
if isinstance(theFile, sqlite3.Connection):
# this commander is associated with sqlite db
c.sqlite_connection = theFile
# Enable the log.
g.app.unlockLog()
c.frame.log.enable(True)
# Phase 2: Create the outline.
g.doHook("open1", old_c=None, c=c, new_c=c, fileName=fn)
if theFile:
readAtFileNodesFlag = bool(previousSettings)
# The log is not set properly here.
ok = lm.readOpenedLeoFile(c, fn, readAtFileNodesFlag, theFile)
# Call c.fileCommands.openLeoFile to read the .leo file.
if not ok:
return None
else:
# Create a wrapper .leo file if:
# a) fn is a .leo file that does not exist or
# b) fn is an external file, existing or not.
lm.initWrapperLeoFile(c, fn)
g.doHook("open2", old_c=None, c=c, new_c=c, fileName=fn)
# Phase 3: Complete the initialization.
g.app.writeWaitingLog(c)
c.setLog()
lm.createMenu(c, fn)
lm.finishOpen(c)
return c
|
def openFileByName(self, fn, gui, old_c, previousSettings):
"""Read the local file whose full path is fn using the given gui.
fn may be a Leo file (including .leo or zipped file) or an external file.
This is not a pre-read: the previousSettings always exist and
the commander created here persists until the user closes the outline.
Reads the entire outline if fn exists and is a .leo file or zipped file.
Creates an empty outline if fn is a non-existent Leo file.
Creates an wrapper outline if fn is an external file, existing or not.
"""
lm = self
# Disable the log.
g.app.setLog(None)
g.app.lockLog()
# Create the a commander for the .leo file.
# Important. The settings don't matter for pre-reads!
# For second read, the settings for the file are *exactly* previousSettings.
c = g.app.newCommander(fileName=fn, gui=gui, previousSettings=previousSettings)
assert c
# Open the file, if possible.
g.doHook("open0")
theFile = lm.openLeoOrZipFile(fn)
if isinstance(theFile, sqlite3.Connection):
# this commander is associated with sqlite db
c.sqlite_connection = theFile
# Enable the log.
g.app.unlockLog()
c.frame.log.enable(True)
# Phase 2: Create the outline.
g.doHook("open1", old_c=None, c=c, new_c=c, fileName=fn)
if theFile:
readAtFileNodesFlag = bool(previousSettings)
# The log is not set properly here.
ok = lm.readOpenedLeoFile(c, fn, readAtFileNodesFlag, theFile)
# Call c.fileCommands.openLeoFile to read the .leo file.
if not ok:
return None
else:
# Create a wrapper .leo file if:
# a) fn is a .leo file that does not exist or
# b) fn is an external file, existing or not.
lm.initWrapperLeoFile(c, fn)
g.doHook("open2", old_c=None, c=c, new_c=c, fileName=fn)
# Phase 3: Complete the initialization.
g.app.writeWaitingLog(c)
c.setLog()
lm.createMenu(c, fn)
lm.finishOpen(c)
return c
|
https://github.com/leo-editor/leo-editor/issues/970
|
setting leoID from os.getenv('USER'): 'matt'
reading settings in /home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/config/leoSettings.leo
reading settings in /home/matt/.leo/myLeoSettings.leo
QApplication: invalid style override passed, ignoring it.
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Not running from a git repo
Python 3.6.6, PyQt version 5.11.1
linux
** isPython3: True
reading settings in /home/matt/.leo/workbook.leo
loadOnePlugin: leo.plugins.livecode.init() returned False
reading settings in /home/matt/code/leo-editor/leo/dist/leoDist.leo
Traceback (most recent call last):
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoCommands.py", line 2072, in executeAnyCommand
return command(event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 269, in commander_command_wrapper
method(event=event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/commands/commanderFileCommands.py", line 214, in open
c2 = g.openWithFileName(fileName, old_c=c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 3682, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 3059, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 1973, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 2139, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 631, in openLeoFile
silent=silent,
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 494, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(s)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 73, in readWithElementTree
xroot = ElementTree.fromstring(contents)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML
parser.feed(text)
File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 189, column 1
|
xml.etree.ElementTree.ParseError
|
def readOpenedLeoFile(self, c, fn, readAtFileNodesFlag, theFile):
# New in Leo 4.10: The open1 event does not allow an override of the init logic.
assert theFile
# lm = self
ok = c.fileCommands.openLeoFile(
theFile, fn, readAtFileNodesFlag=readAtFileNodesFlag
)
# closes file.
if ok:
if not c.openDirectory:
theDir = c.os_path_finalize(g.os_path_dirname(fn))
c.openDirectory = c.frame.openDirectory = theDir
else:
g.app.closeLeoWindow(c.frame, finish_quit=False)
# #970: Never close Leo here.
return ok
|
def readOpenedLeoFile(self, c, fn, readAtFileNodesFlag, theFile):
# New in Leo 4.10: The open1 event does not allow an override of the init logic.
assert theFile
# lm = self
ok = c.fileCommands.openLeoFile(
theFile, fn, readAtFileNodesFlag=readAtFileNodesFlag
)
# closes file.
if ok:
if not c.openDirectory:
theDir = c.os_path_finalize(g.os_path_dirname(fn))
c.openDirectory = c.frame.openDirectory = theDir
else:
g.app.closeLeoWindow(c.frame, finish_quit=self.more_cmdline_files is False)
return ok
|
https://github.com/leo-editor/leo-editor/issues/970
|
setting leoID from os.getenv('USER'): 'matt'
reading settings in /home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/config/leoSettings.leo
reading settings in /home/matt/.leo/myLeoSettings.leo
QApplication: invalid style override passed, ignoring it.
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Not running from a git repo
Python 3.6.6, PyQt version 5.11.1
linux
** isPython3: True
reading settings in /home/matt/.leo/workbook.leo
loadOnePlugin: leo.plugins.livecode.init() returned False
reading settings in /home/matt/code/leo-editor/leo/dist/leoDist.leo
Traceback (most recent call last):
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoCommands.py", line 2072, in executeAnyCommand
return command(event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 269, in commander_command_wrapper
method(event=event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/commands/commanderFileCommands.py", line 214, in open
c2 = g.openWithFileName(fileName, old_c=c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 3682, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 3059, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 1973, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 2139, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 631, in openLeoFile
silent=silent,
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 494, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(s)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 73, in readWithElementTree
xroot = ElementTree.fromstring(contents)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML
parser.feed(text)
File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 189, column 1
|
xml.etree.ElementTree.ParseError
|
def readWithElementTree(self, path, s):
contents = g.toUnicode(s) if g.isPython3 else s
try:
xroot = ElementTree.fromstring(contents)
except Exception as e:
if path:
message = "bad .leo file: %s" % g.shortFileName(path)
else:
message = "The clipboard is not a vaild .leo file"
print("")
g.es_print(message, color="red")
g.es_print(g.toUnicode(e))
print("")
# #970: Just report failure here.
return None
g_element = xroot.find("globals")
v_elements = xroot.find("vnodes")
t_elements = xroot.find("tnodes")
self.scanGlobals(g_element)
gnx2body, gnx2ua = self.scanTnodes(t_elements)
hidden_v = self.scanVnodes(gnx2body, self.gnx2vnode, gnx2ua, v_elements)
self.handleBits()
return hidden_v
|
def readWithElementTree(self, path, s):
contents = g.toUnicode(s) if g.isPython3 else s
try:
xroot = ElementTree.fromstring(contents)
except Exception as e:
if path:
message = "bad .leo file: %s" % g.shortFileName(path)
else:
message = "The clipboard is not a vaild .leo file"
g.es_print(message, color="red")
g.es_print(g.toUnicode(e))
# Parse a minimal file for the rest of Leo.
xroot = ElementTree.fromstring(self.minimal_leo_file)
g_element = xroot.find("globals")
v_elements = xroot.find("vnodes")
t_elements = xroot.find("tnodes")
self.scanGlobals(g_element)
gnx2body, gnx2ua = self.scanTnodes(t_elements)
hidden_v = self.scanVnodes(gnx2body, self.gnx2vnode, gnx2ua, v_elements)
self.handleBits()
return hidden_v
|
https://github.com/leo-editor/leo-editor/issues/970
|
setting leoID from os.getenv('USER'): 'matt'
reading settings in /home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/config/leoSettings.leo
reading settings in /home/matt/.leo/myLeoSettings.leo
QApplication: invalid style override passed, ignoring it.
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Not running from a git repo
Python 3.6.6, PyQt version 5.11.1
linux
** isPython3: True
reading settings in /home/matt/.leo/workbook.leo
loadOnePlugin: leo.plugins.livecode.init() returned False
reading settings in /home/matt/code/leo-editor/leo/dist/leoDist.leo
Traceback (most recent call last):
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoCommands.py", line 2072, in executeAnyCommand
return command(event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 269, in commander_command_wrapper
method(event=event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/commands/commanderFileCommands.py", line 214, in open
c2 = g.openWithFileName(fileName, old_c=c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 3682, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 3059, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 1973, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 2139, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 631, in openLeoFile
silent=silent,
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 494, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(s)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 73, in readWithElementTree
xroot = ElementTree.fromstring(contents)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML
parser.feed(text)
File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 189, column 1
|
xml.etree.ElementTree.ParseError
|
def getGlobalData(self):
"""Return a dict containing all global data."""
c = self.c
try:
window_pos = c.db.get("window_position")
r1 = float(c.db.get("body_outline_ratio", "0.5"))
r2 = float(c.db.get("body_secondary_ratio", "0.5"))
top, left, height, width = window_pos
return {
"top": int(top),
"left": int(left),
"height": int(height),
"width": int(width),
"r1": r1,
"r2": r2,
}
except Exception:
pass
# Use reasonable defaults.
return {
"top": 50,
"left": 50,
"height": 500,
"width": 800,
"r1": 0.5,
"r2": 0.5,
}
|
def getGlobalData(self):
"""Return a dict containing all global data."""
c = self.c
data = c.db.get("window_position")
if data:
# pylint: disable=unpacking-non-sequence
top, left, height, width = data
d = {
"top": int(top),
"left": int(left),
"height": int(height),
"width": int(width),
}
else:
# Use reasonable defaults.
d = {"top": 50, "left": 50, "height": 500, "width": 800}
d["r1"] = float(c.db.get("body_outline_ratio", "0.5"))
d["r2"] = float(c.db.get("body_secondary_ratio", "0.5"))
return d
|
https://github.com/leo-editor/leo-editor/issues/970
|
setting leoID from os.getenv('USER'): 'matt'
reading settings in /home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/config/leoSettings.leo
reading settings in /home/matt/.leo/myLeoSettings.leo
QApplication: invalid style override passed, ignoring it.
Leo 5.8 b1, build 20180815095610, Wed, Aug 15, 2018 9:56:10 AM
Not running from a git repo
Python 3.6.6, PyQt version 5.11.1
linux
** isPython3: True
reading settings in /home/matt/.leo/workbook.leo
loadOnePlugin: leo.plugins.livecode.init() returned False
reading settings in /home/matt/code/leo-editor/leo/dist/leoDist.leo
Traceback (most recent call last):
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoCommands.py", line 2072, in executeAnyCommand
return command(event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 269, in commander_command_wrapper
method(event=event)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/commands/commanderFileCommands.py", line 214, in open
c2 = g.openWithFileName(fileName, old_c=c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoGlobals.py", line 3682, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 3059, in loadLocalFile
previousSettings = lm.getPreviousSettings(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 1973, in getPreviousSettings
c = lm.openSettingsFile(fn)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoApp.py", line 2139, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 631, in openLeoFile
silent=silent,
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 494, in getLeoFile
v = FastRead(c, self.gnxDict).readFile(fileName)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 68, in readFile
return self.readWithElementTree(s)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/site-packages/leo/core/leoFileCommands.py", line 73, in readWithElementTree
xroot = ElementTree.fromstring(contents)
File "/home/matt/miniconda3/envs/leo/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML
parser.feed(text)
File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 189, column 1
|
xml.etree.ElementTree.ParseError
|
def get_version(file, version=None):
"""Determine current Leo version. Use git if in checkout, else internal Leo"""
root = os.path.dirname(os.path.realpath(file))
if os.path.exists(os.path.join(root, ".git")):
version = git_version(file)
else:
version = get_semver(leoVersion.version)
if not version:
version = leoVersion.version
return version
|
def get_version(file, version=None):
"""Determine current Leo version. Use git if in checkout, else internal Leo"""
root = os.path.dirname(os.path.realpath(file))
if os.path.exists(os.path.join(root, ".git")):
version = git_version(file)
else:
version = get_semver(leoVersion.version)
return version
|
https://github.com/leo-editor/leo-editor/issues/847
|
(leo-next) PS C:\Users\Viktor\leo-next> pip install https://github.com/leo-editor/leo-editor/archive/master.zip
Collecting https://github.com/leo-editor/leo-editor/archive/master.zip
Downloading https://github.com/leo-editor/leo-editor/archive/master.zip
- 11.5MB 1.3MB/s
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Viktor\AppData\Local\Temp\pip-9ceji4i6-build\setup.py", line 10, in <module>
import semantic_version
ModuleNotFoundError: No module named 'semantic_version'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Viktor\AppData\Local\Temp\pip-9ceji4i6-build\
(leo-next) PS C:\Users\Viktor\leo-next>
|
ModuleNotFoundError
|
def get_semver(tag):
"""Return 'Semantic Version' from tag string"""
try:
import semantic_version
version = str(semantic_version.Version.coerce(tag, partial=True))
# tuple of major, minor, build, pre-release, patch
# 5.6b2 --> 5.6-b2
except ImportError or ValueError:
print(
"""*** Failed to parse Semantic Version from git tag '{0}'.
Expecting tag name like '5.7b2', 'leo-4.9.12', 'v4.3' for releases.
This version can't be uploaded to PyPi.org.""".format(tag)
)
version = tag
return version
|
def get_semver(tag):
"""Return 'Semantic Version' from tag string"""
try:
version = str(semantic_version.Version.coerce(tag, partial=True))
# tuple of major, minor, build, pre-release, patch
# 5.6b2 --> 5.6-b2
except ValueError:
print(
"""*** Failed to parse Semantic Version from git tag '{0}'.
Expecting tag name like '5.7b2', 'leo-4.9.12', 'v4.3' for releases.
This version can't be uploaded to PyPi.org.""".format(tag)
)
version = tag
return version
|
https://github.com/leo-editor/leo-editor/issues/847
|
(leo-next) PS C:\Users\Viktor\leo-next> pip install https://github.com/leo-editor/leo-editor/archive/master.zip
Collecting https://github.com/leo-editor/leo-editor/archive/master.zip
Downloading https://github.com/leo-editor/leo-editor/archive/master.zip
- 11.5MB 1.3MB/s
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Viktor\AppData\Local\Temp\pip-9ceji4i6-build\setup.py", line 10, in <module>
import semantic_version
ModuleNotFoundError: No module named 'semantic_version'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Viktor\AppData\Local\Temp\pip-9ceji4i6-build\
(leo-next) PS C:\Users\Viktor\leo-next>
|
ModuleNotFoundError
|
def get_semver(tag):
"""Return 'Semantic Version' from tag string"""
try:
import semantic_version
version = str(semantic_version.Version.coerce(tag, partial=True))
# tuple of major, minor, build, pre-release, patch
# 5.6b2 --> 5.6-b2
except ImportError or ValueError as err:
print("\n", err)
print(
"""*** Failed to parse Semantic Version from git tag '{0}'.
Expecting tag name like '5.7b2', 'leo-4.9.12', 'v4.3' for releases.
This version can't be uploaded to PyPi.org.""".format(tag)
)
version = tag
return version
|
def get_semver(tag):
"""Return 'Semantic Version' from tag string"""
try:
import semantic_version
version = str(semantic_version.Version.coerce(tag, partial=True))
# tuple of major, minor, build, pre-release, patch
# 5.6b2 --> 5.6-b2
except ImportError or ValueError:
print(
"""*** Failed to parse Semantic Version from git tag '{0}'.
Expecting tag name like '5.7b2', 'leo-4.9.12', 'v4.3' for releases.
This version can't be uploaded to PyPi.org.""".format(tag)
)
version = tag
return version
|
https://github.com/leo-editor/leo-editor/issues/847
|
(leo-next) PS C:\Users\Viktor\leo-next> pip install https://github.com/leo-editor/leo-editor/archive/master.zip
Collecting https://github.com/leo-editor/leo-editor/archive/master.zip
Downloading https://github.com/leo-editor/leo-editor/archive/master.zip
- 11.5MB 1.3MB/s
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Viktor\AppData\Local\Temp\pip-9ceji4i6-build\setup.py", line 10, in <module>
import semantic_version
ModuleNotFoundError: No module named 'semantic_version'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Viktor\AppData\Local\Temp\pip-9ceji4i6-build\
(leo-next) PS C:\Users\Viktor\leo-next>
|
ModuleNotFoundError
|
def clean():
print("\nRemoving build, dist and egg directories")
root = os.path.dirname(os.path.realpath(__file__))
for d in ["build", "dist", "leo.egg-info", ".eggs"]:
dpath = os.path.join(root, d)
if os.path.isdir(dpath):
rmtree(dpath)
|
def clean():
print("Removing build and dist directories")
root = os.path.dirname(os.path.realpath(__file__))
for d in ["build", "dist", "leo.egg-info"]:
dpath = os.path.join(root, d)
if os.path.isdir(dpath):
rmtree(dpath)
|
https://github.com/leo-editor/leo-editor/issues/847
|
(leo-next) PS C:\Users\Viktor\leo-next> pip install https://github.com/leo-editor/leo-editor/archive/master.zip
Collecting https://github.com/leo-editor/leo-editor/archive/master.zip
Downloading https://github.com/leo-editor/leo-editor/archive/master.zip
- 11.5MB 1.3MB/s
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Viktor\AppData\Local\Temp\pip-9ceji4i6-build\setup.py", line 10, in <module>
import semantic_version
ModuleNotFoundError: No module named 'semantic_version'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Viktor\AppData\Local\Temp\pip-9ceji4i6-build\
(leo-next) PS C:\Users\Viktor\leo-next>
|
ModuleNotFoundError
|
def readFile(self, fileName, root):
"""
Read the file from the cache if possible.
Return (s,ok,key)
"""
trace = False and not g.unitTesting
showHits = False
showLines = False
showList = False
sfn = g.shortFileName(fileName)
if not g.enableDB:
if trace:
g.trace("g.enableDB is False", fileName)
return "", False, None
if trace:
g.trace("=====", root.v.gnx, "children", root.numberOfChildren(), fileName)
s = g.readFileIntoEncodedString(fileName, silent=True)
if s is None:
if trace:
g.trace("empty file contents", fileName)
return s, False, None
assert not g.isUnicode(s)
if trace and showLines:
for i, line in enumerate(g.splitLines(s)):
print("%3d %s" % (i, repr(line)))
# There will be a bug if s is not already an encoded string.
key = self.fileKey(fileName, s, requireEncodedString=True)
# Fix bug #385: use the full fileName, not root.h.
ok = self.db and key in self.db
if ok:
if trace and showHits:
g.trace("cache hit", key[-6:], sfn)
# Delete the previous tree, regardless of the @<file> type.
while root.hasChildren():
root.firstChild().doDelete()
# Recreate the file from the cache.
aList = self.db.get(key)
if trace and showList:
g.printList(list(g.flatten_list(aList)))
self.collectChangedNodes(root.v, aList, fileName)
self.createOutlineFromCacheList2(root.v, aList)
# self.createOutlineFromCacheList(root.v, aList, fileName=fileName)
elif trace:
g.trace("cache miss", key[-6:], sfn)
return s, ok, key
|
def readFile(self, fileName, root):
"""
Read the file from the cache if possible.
Return (s,ok,key)
"""
trace = False and not g.unitTesting
showHits = False
showLines = False
showList = False
sfn = g.shortFileName(fileName)
if not g.enableDB:
if trace:
g.trace("g.enableDB is False", fileName)
return "", False, None
if trace:
g.trace("=====", root.v.gnx, "children", root.numberOfChildren(), fileName)
s = g.readFileIntoEncodedString(fileName, silent=True)
if s is None:
if trace:
g.trace("empty file contents", fileName)
return s, False, None
assert not g.isUnicode(s)
if trace and showLines:
for i, line in enumerate(g.splitLines(s)):
print("%3d %s" % (i, repr(line)))
# There will be a bug if s is not already an encoded string.
key = self.fileKey(fileName, s, requireEncodedString=True)
# Fix bug #385: use the full fileName, not root.h.
ok = self.db and key in self.db
if ok:
if trace and showHits:
g.trace("cache hit", key[-6:], sfn)
# Delete the previous tree, regardless of the @<file> type.
while root.hasChildren():
root.firstChild().doDelete()
# Recreate the file from the cache.
aList = self.db.get(key)
if trace and showList:
g.printList(list(g.flatten_list(aList)))
self.createOutlineFromCacheList(root.v, aList, fileName=fileName)
elif trace:
g.trace("cache miss", key[-6:], sfn)
return s, ok, key
|
https://github.com/leo-editor/leo-editor/issues/892
|
[a64] c:\leo.repo\leo-editor>rem leo.bat
[a64] c:\leo.repo\leo-editor>python c:\leo.repo\leo-editor\launchLeo.py --gui=qttabs --gui=qttabs leo\core\leoPy.leo leo\plugins\leoPlugins.leo c:\Users\edreamleo\ekr-projects.leo leo\doc\LeoDocs.leo
reading settings in C:/leo.repo/leo-editor/leo/config/leoSettings.leo
reading settings in C:/Users/edreamleo/.leo/myLeoSettings.leo
reading settings in c:/leo.repo/leo-editor/leo/core/leoPy.leo
reading settings in C:/leo.repo/leo-editor/leo/themes/EKRDark.leo
Leo 5.7.2 devel, build 20180423091843, Mon, Apr 23, 2018 9:18:43 AM
Git repo info: branch = devel, commit = cb0abffb9c28
Python 3.6.3, PyQt version 5.6.2
Windows 10 AMD64 (build 10.0.16299) SP0
** isPython3: True
** caching enabled
reading settings in c:/leo.repo/leo-editor/leo/core/leoPy.leo
creating recovered node: g.execGitCommand
creating recovered node: gdc.__init__ & helper
creating recovered node: gdc.find_git_working_directory
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\launchLeo.py", line 8, in <module>
leo.core.runLeo.run()
File "c:\leo.repo\leo-editor\leo\core\runLeo.py", line 74, in run
g.app.loadManager.load(fileName, pymacs)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2285, in load
ok = lm.doPostPluginsInit()
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 2325, in doPostPluginsInit
c = lm.loadLocalFile(fn, gui=g.app.gui, old_c=None)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 3159, in loadLocalFile
c = lm.openFileByName(fn, gui, old_c, previousSettings)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 3200, in openFileByName
ok = lm.readOpenedLeoFile(c, fn, readAtFileNodesFlag, theFile)
File "c:\leo.repo\leo-editor\leo\core\leoApp.py", line 3375, in readOpenedLeoFile
readAtFileNodesFlag=readAtFileNodesFlag)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 884, in openLeoFile
silent=silent,
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 710, in getLeoFile
recoveryNode = fc.readExternalFiles(fileName)
File "c:\leo.repo\leo-editor\leo\core\leoFileCommands.py", line 844, in readExternalFiles
c.atFileCommands.readAll(c.rootVnode(), force=False)
File "c:\leo.repo\leo-editor\leo\core\leoAtFile.py", line 758, in readAll
at.read(p, force=force)
File "c:\leo.repo\leo-editor\leo\core\leoAtFile.py", line 505, in read
s, loaded, fileKey = c.cacher.readFile(fileName, root)
File "c:\leo.repo\leo-editor\leo\core\leoCache.py", line 393, in readFile
self.createOutlineFromCacheList(root.v, aList, fileName=fileName)
File "c:\leo.repo\leo-editor\leo\core\leoCache.py", line 172, in createOutlineFromCacheList
self.checkForChangedNodes(child_tuple, fileName, parent_v)
File "c:\leo.repo\leo-editor\leo\core\leoCache.py", line 199, in checkForChangedNodes
child_v.children[i] = self.c.fileCommands.gnxDict.get(gnx)
IndexError: list assignment index out of range
|
IndexError
|
def find_parent(self, level, h):
"""
Return the parent at the indicated level, allocating
place-holder nodes as necessary.
"""
trace = False and not g.unitTesting
assert level >= 0
if trace:
print("")
g.trace("===== level: %s, len(stack): %s h: %s" % (level, len(self.stack), h))
while level < len(self.stack):
p = self.stack.pop()
if trace:
g.trace("POP", len(self.get_lines(p)), p.h)
# self.print_list(self.get_lines(p))
top = self.stack[-1]
if trace:
g.trace("TOP", top.h)
if 1: # Experimental fix for #877.
if level > len(self.stack):
print("")
g.trace("Unexpected markdown level for: %s" % h)
print("")
while level > len(self.stack):
child = self.create_child_node(
parent=top, body=None, headline="INSERTED NODE"
)
self.stack.append(child)
assert level == len(self.stack), (level, len(self.stack))
child = self.create_child_node(
parent=top,
body=None,
headline=h, # Leave the headline alone
)
self.stack.append(child)
if trace:
g.trace("level", level)
self.print_stack(self.stack)
assert self.stack
assert 0 <= level < len(self.stack), (level, len(self.stack))
return self.stack[level]
|
def find_parent(self, level, h):
"""
Return the parent at the indicated level, allocating
place-holder nodes as necessary.
"""
trace = False and g.unitTesting
trace_stack = False
assert level >= 0
if trace:
g.trace("=====", level, len(self.stack), h)
while level < len(self.stack):
p = self.stack.pop()
if trace:
g.trace("POP", len(self.get_lines(p)), p.h)
if trace and trace_stack:
self.print_list(self.get_lines(p))
top = self.stack[-1]
if trace:
g.trace("TOP", top.h)
child = self.create_child_node(
parent=top,
body=None,
headline=h, # Leave the headline alone
)
self.stack.append(child)
if trace and trace_stack:
self.print_stack(self.stack)
return self.stack[level]
|
https://github.com/leo-editor/leo-editor/issues/877
|
reading: @auto-md Software.md
Exception running Markdown_Importer
Traceback (most recent call last):
File "D:\Synced\github repos\leo\leo\core\leoApp.py", line 1468, in scanner_for_at_auto_cb
return scanner.run(s, parent)
File "D:\Synced\github repos\leo\leo\plugins\importers\linescanner.py", line 463, in run
self.generate_nodes(s, parent)
File "D:\Synced\github repos\leo\leo\plugins\importers\linescanner.py", line 530, in generate_nodes
self.gen_lines(s, parent)
File "D:\Synced\github repos\leo\leo\plugins\importers\markdown.py", line 48, in gen_lines
self.make_node(level, name)
File "D:\Synced\github repos\leo\leo\plugins\importers\markdown.py", line 146, in make_node
self.find_parent(level=level, h=name)
File "D:\Synced\github repos\leo\leo\plugins\importers\markdown.py", line 85, in find_parent
return self.stack[level]
IndexError: list index out of range
read 21 files in 1.10 seconds
read outline in 1.14 seconds
|
IndexError
|
def checkLinks(self):
"""Check the consistency of all links in the outline."""
c = self
t1 = time.time()
count, errors = 0, 0
for p in c.safe_all_positions():
count += 1
# try:
if not c.checkThreadLinks(p):
errors += 1
break
if not c.checkSiblings(p):
errors += 1
break
if not c.checkParentAndChildren(p):
errors += 1
break
# except AssertionError:
# errors += 1
# junk, value, junk = sys.exc_info()
# g.error("test failed at position %s\n%s" % (repr(p), value))
t2 = time.time()
g.es_print(
"check-links: %4.2f sec. %s %s nodes" % (t2 - t1, c.shortFileName(), count),
color="blue",
)
return errors
|
def checkLinks(self):
"""Check the consistency of all links in the outline."""
c = self
t1 = time.time()
count, errors = 0, 0
for p in c.safe_all_positions():
count += 1
try:
c.checkThreadLinks(p)
c.checkSiblings(p)
c.checkParentAndChildren(p)
except AssertionError:
errors += 1
junk, value, junk = sys.exc_info()
g.error("test failed at position %s\n%s" % (repr(p), value))
t2 = time.time()
g.es_print(
"check-links: %4.2f sec. %s %s nodes" % (t2 - t1, c.shortFileName(), count),
color="blue",
)
return errors
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def checkParentAndChildren(self, p):
"""Check consistency of parent and child data structures."""
c = self
def _assert(condition):
return g._assert(condition, show_callers=False)
def dump(p):
if p and p.v:
p.v.dump()
elif p:
print("<no p.v>")
else:
print("<no p>")
if g.unitTesting:
assert False, g.callers()
if p.hasParent():
n = p.childIndex()
if not _assert(p == p.parent().moveToNthChild(n)):
g.trace("p != parent().moveToNthChild(%s)" % (n))
dump(p)
dump(p.parent())
return False
if p.level() > 0 and not _assert(p.v.parents):
g.trace("no parents")
dump(p)
return False
for child in p.children():
if not c.checkParentAndChildren(child):
return False
if not _assert(p == child.parent()):
g.trace("p != child.parent()")
dump(p)
dump(child.parent())
return False
if p.hasNext():
if not _assert(p.next().parent() == p.parent()):
g.trace("p.next().parent() != p.parent()")
dump(p.next().parent())
dump(p.parent())
return False
if p.hasBack():
if not _assert(p.back().parent() == p.parent()):
g.trace("p.back().parent() != parent()")
dump(p.back().parent())
dump(p.parent())
return False
# Check consistency of parent and children arrays.
# Every nodes gets visited, so a strong test need only check consistency
# between p and its parent, not between p and its children.
parent_v = p._parentVnode()
n = p.childIndex()
if not _assert(parent_v.children[n] == p.v):
g.trace("parent_v.children[n] != p.v")
parent_v.dump()
p.v.dump()
return False
return True
|
def checkParentAndChildren(self, p):
"""Check consistency of parent and child data structures."""
# Check consistency of parent and child links.
if p.hasParent():
n = p.childIndex()
assert p == p.parent().moveToNthChild(n), "p!=parent.moveToNthChild"
for child in p.children():
assert p == child.parent(), "p!=child.parent"
if p.hasNext():
assert p.next().parent() == p.parent(), "next.parent!=parent"
if p.hasBack():
assert p.back().parent() == p.parent(), "back.parent!=parent"
# Check consistency of parent and children arrays.
# Every nodes gets visited, so a strong test need only check consistency
# between p and its parent, not between p and its children.
parent_v = p._parentVnode()
n = p.childIndex()
assert parent_v.children[n] == p.v, "fail 1"
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def checkSiblings(self, p):
"""Check the consistency of next and back links."""
back = p.back()
next = p.next()
if back:
if not g._assert(p == back.next()):
g.trace(
"p!=p.back().next(), back: %s\nback.next: %s" % (back, back.next())
)
return False
if next:
if not g._assert(p == next.back()):
g.trace("p!=p.next().back, next: %s\nnext.back: %s" % (next, next.back()))
return False
return True
|
def checkSiblings(self, p):
"""Check the consistency of next and back links."""
back = p.back()
next = p.next()
if back:
assert p == back.next(), "p!=p.back().next(), back: %s\nback.next: %s" % (
back,
back.next(),
)
if next:
assert p == next.back(), "p!=p.next().back, next: %s\nnext.back: %s" % (
next,
next.back(),
)
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def checkThreadLinks(self, p):
"""Check consistency of threadNext & threadBack links."""
threadBack = p.threadBack()
threadNext = p.threadNext()
if threadBack:
if not g._assert(p == threadBack.threadNext()):
g.trace("p!=p.threadBack().threadNext()")
return False
if threadNext:
if not g._assert(p == threadNext.threadBack()):
g.trace("p!=p.threadNext().threadBack()")
return False
return True
|
def checkThreadLinks(self, p):
"""Check consistency of threadNext & threadBack links."""
threadBack = p.threadBack()
threadNext = p.threadNext()
if threadBack:
assert p == threadBack.threadNext(), "p!=p.threadBack().threadNext()"
if threadNext:
assert p == threadNext.threadBack(), "p!=p.threadNext().threadBack()"
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def getLeoOutlineFromClipboard(self, s, reassignIndices=True): ###, tempOutline=False):
"""Read a Leo outline from string s in clipboard format."""
###
# if tempOutline:
# g.trace('===== tempOutline is True', g.callers())
# if g.unitTesting: assert False
c = self.c
current = c.p
if not current:
g.trace("no c.p")
return None
check = not reassignIndices
self.initReadIvars()
# Save the hidden root's children.
children = c.hiddenRootNode.children
# 2011/12/12: save and clear gnxDict.
# This ensures that new indices will be used for all nodes.
if reassignIndices: ### or tempOutline:
oldGnxDict = self.gnxDict
self.gnxDict = {}
else:
# All pasted nodes should already have unique gnx's.
ni = g.app.nodeIndices
for v in c.all_unique_nodes():
ni.check_gnx(c, v.fileIndex, v)
self.usingClipboard = True
try:
# This encoding must match the encoding used in putLeoOutline.
s = g.toEncodedString(s, self.leo_file_encoding, reportErrors=True)
# readSaxFile modifies the hidden root.
v = self.readSaxFile(
theFile=None,
fileName="<clipboard>",
silent=True, # don't tell about stylesheet elements.
inClipboard=True,
reassignIndices=reassignIndices,
s=s,
)
if not v:
return g.es("the clipboard is not valid ", color="blue")
finally:
self.usingClipboard = False
# Restore the hidden root's children
c.hiddenRootNode.children = children
# Unlink v from the hidden root.
v.parents.remove(c.hiddenRootNode)
p = leoNodes.Position(v)
# Important: we must not adjust links when linking v
# into the outline. The read code has already done that.
if current.hasChildren() and current.isExpanded():
if check and not self.checkPaste(current, p):
return None
p._linkAsNthChild(current, 0, adjust=False)
else:
if check and not self.checkPaste(current.parent(), p):
return None
p._linkAfter(current, adjust=False)
###
### c.dumpOutline()
###
# if tempOutline:
# self.gnxDict = oldGnxDict
# elif reassignIndices:
if reassignIndices:
self.gnxDict = oldGnxDict
ni = g.app.nodeIndices
for p2 in p.self_and_subtree():
v = p2.v
index = ni.getNewIndex(v)
if g.trace_gnxDict:
g.trace(c.shortFileName(), "**restoring**", index, v)
c.selectPosition(p)
self.initReadIvars()
return p
|
def getLeoOutlineFromClipboard(self, s, reassignIndices=True): ###, tempOutline=False):
"""Read a Leo outline from string s in clipboard format."""
###
# if tempOutline:
# g.trace('===== tempOutline is True', g.callers())
# if g.unitTesting: assert False
c = self.c
current = c.p
if not current:
g.trace("no c.p")
return None
check = not reassignIndices
self.initReadIvars()
# Save the hidden root's children.
children = c.hiddenRootNode.children
# 2011/12/12: save and clear gnxDict.
# This ensures that new indices will be used for all nodes.
if reassignIndices: ### or tempOutline:
oldGnxDict = self.gnxDict
self.gnxDict = {}
else:
# All pasted nodes should already have unique gnx's.
ni = g.app.nodeIndices
for v in c.all_unique_nodes():
ni.check_gnx(c, v.fileIndex, v)
self.usingClipboard = True
try:
# This encoding must match the encoding used in putLeoOutline.
s = g.toEncodedString(s, self.leo_file_encoding, reportErrors=True)
# readSaxFile modifies the hidden root.
v = self.readSaxFile(
theFile=None,
fileName="<clipboard>",
silent=True, # don't tell about stylesheet elements.
inClipboard=True,
reassignIndices=reassignIndices,
s=s,
)
if not v:
return g.es("the clipboard is not valid ", color="blue")
finally:
self.usingClipboard = False
# Restore the hidden root's children
c.hiddenRootNode.children = children
# Unlink v from the hidden root.
v.parents.remove(c.hiddenRootNode)
p = leoNodes.Position(v)
# Important: we must not adjust links when linking v
# into the outline. The read code has already done that.
if current.hasChildren() and current.isExpanded():
if check and not self.checkPaste(current, p):
return None
p._linkAsNthChild(current, 0, adjust=False)
else:
if check and not self.checkPaste(current.parent(), p):
return None
p._linkAfter(current, adjust=False)
###
c.dumpOutline()
###
# if tempOutline:
# self.gnxDict = oldGnxDict
# elif reassignIndices:
if reassignIndices:
self.gnxDict = oldGnxDict
ni = g.app.nodeIndices
for p2 in p.self_and_subtree():
v = p2.v
index = ni.getNewIndex(v)
if g.trace_gnxDict:
g.trace(c.shortFileName(), "**restoring**", index, v)
c.selectPosition(p)
self.initReadIvars()
return p
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def _assert(condition, show_callers=True):
"""A safer alternative to a bare assert."""
if g.unitTesting:
assert condition
return
ok = bool(condition)
if ok:
return True
print("")
g.es_print("===== g._assert failed =====")
print("")
if show_callers:
g.es_print(g.callers())
return False
|
def _assert(condition):
"""A safer alternative to a bare assert."""
if g.unitTesting:
assert condition
return
ok = bool(condition)
if ok:
return True
g.es_print("g._assert failed")
g.es_print(g.callers())
return False
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def getLeoOutlineFromClipboard(self, s, reassignIndices=True):
"""Read a Leo outline from string s in clipboard format."""
c = self.c
current = c.p
if not current:
g.trace("no c.p")
return None
check = not reassignIndices
self.initReadIvars()
# Save the hidden root's children.
children = c.hiddenRootNode.children
#
# Save and clear gnxDict.
# This ensures that new indices will be used for all nodes.
if reassignIndices:
oldGnxDict = self.gnxDict
self.gnxDict = {}
else:
# All pasted nodes should already have unique gnx's.
ni = g.app.nodeIndices
for v in c.all_unique_nodes():
ni.check_gnx(c, v.fileIndex, v)
self.usingClipboard = True
try:
# This encoding must match the encoding used in putLeoOutline.
s = g.toEncodedString(s, self.leo_file_encoding, reportErrors=True)
# readSaxFile modifies the hidden root.
v = self.readSaxFile(
theFile=None,
fileName="<clipboard>",
silent=True, # don't tell about stylesheet elements.
inClipboard=True,
reassignIndices=reassignIndices,
s=s,
)
if not v:
return g.es("the clipboard is not valid ", color="blue")
finally:
self.usingClipboard = False
# Restore the hidden root's children
c.hiddenRootNode.children = children
# Unlink v from the hidden root.
v.parents.remove(c.hiddenRootNode)
p = leoNodes.Position(v)
#
# Important: we must not adjust links when linking v
# into the outline. The read code has already done that.
if current.hasChildren() and current.isExpanded():
if check and not self.checkPaste(current, p):
return None
p._linkAsNthChild(current, 0, adjust=False)
else:
if check and not self.checkPaste(current.parent(), p):
return None
p._linkAfter(current, adjust=False)
if reassignIndices:
self.gnxDict = oldGnxDict
self.reassignAllIndices(p)
else:
# Fix #862: paste-retaining-clones can corrupt the outline.
self.linkChildrenToParents(p)
c.selectPosition(p)
self.initReadIvars()
return p
|
def getLeoOutlineFromClipboard(self, s, reassignIndices=True):
"""Read a Leo outline from string s in clipboard format."""
c = self.c
current = c.p
if not current:
g.trace("no c.p")
return None
check = not reassignIndices
self.initReadIvars()
# Save the hidden root's children.
children = c.hiddenRootNode.children
#
# Save and clear gnxDict.
# This ensures that new indices will be used for all nodes.
if reassignIndices:
oldGnxDict = self.gnxDict
self.gnxDict = {}
else:
# All pasted nodes should already have unique gnx's.
ni = g.app.nodeIndices
for v in c.all_unique_nodes():
ni.check_gnx(c, v.fileIndex, v)
self.usingClipboard = True
try:
# This encoding must match the encoding used in putLeoOutline.
s = g.toEncodedString(s, self.leo_file_encoding, reportErrors=True)
# readSaxFile modifies the hidden root.
v = self.readSaxFile(
theFile=None,
fileName="<clipboard>",
silent=True, # don't tell about stylesheet elements.
inClipboard=True,
reassignIndices=reassignIndices,
s=s,
)
if not v:
return g.es("the clipboard is not valid ", color="blue")
finally:
self.usingClipboard = False
# Restore the hidden root's children
c.hiddenRootNode.children = children
# Unlink v from the hidden root.
v.parents.remove(c.hiddenRootNode)
p = leoNodes.Position(v)
#
# Important: we must not adjust links when linking v
# into the outline. The read code has already done that.
if current.hasChildren() and current.isExpanded():
if check and not self.checkPaste(current, p):
return None
p._linkAsNthChild(current, 0, adjust=False)
else:
if check and not self.checkPaste(current.parent(), p):
return None
p._linkAfter(current, adjust=False)
if reassignIndices:
self.gnxDict = oldGnxDict
ni = g.app.nodeIndices
for p2 in p.self_and_subtree():
v = p2.v
index = ni.getNewIndex(v)
if g.trace_gnxDict:
g.trace(c.shortFileName(), "**restoring**", index, v)
c.selectPosition(p)
self.initReadIvars()
return p
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def createSaxChildren(self, sax_node, parent_v):
"""Create vnodes for all children in sax_node.children."""
children = []
for sax_child in sax_node.children:
tnx = sax_child.tnx
v = self.gnxDict.get(tnx)
if v: # A clone. Don't look at the children.
self.updateSaxClone(sax_child, parent_v, v)
else:
v = self.createSaxVnode(sax_child, parent_v)
self.createSaxChildren(sax_child, v)
children.append(v)
parent_v.children = children
for child in children:
child.parents.append(parent_v)
return children
|
def createSaxChildren(self, sax_node, parent_v):
"""Create vnodes for all children in sax_node.children."""
children = []
for sax_child in sax_node.children:
tnx = sax_child.tnx
v = self.gnxDict.get(tnx)
if v: # A clone. Don't look at the children.
### v = self.createSaxVnode(sax_child, parent_v, v=v)
self.updateSaxClone(sax_child, parent_v, v)
else:
v = self.createSaxVnode(sax_child, parent_v)
self.createSaxChildren(sax_child, v)
children.append(v)
parent_v.children = children
for child in children:
child.parents.append(parent_v)
return children
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def updateSaxClone(self, sax_node, parent_v, v):
"""
Update the body text of v. It overrides any previous body text.
"""
at = self.c.atFileCommands
b = sax_node.bodyString
if v.b != b:
v.setBodyString(b)
at.bodySetInited(v)
|
def updateSaxClone(self, sax_node, parent_v, v):
"""
Update the body text of v. It overrides any previous body text.
"""
c = self.c
at = c.atFileCommands
b = sax_node.bodyString
if v.b != b:
v.setBodyString(b)
at.bodySetInited(v)
|
https://github.com/leo-editor/leo-editor/issues/862
|
Traceback (most recent call last):
File "/pri/git/leo-editor/leo/core/leoCommands.py", line 2016, in executeAnyCommand
return command(event)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 2445, in commander_command_wrapper
method(event=event)
File "/pri/git/leo-editor/leo/commands/commanderOutlineCommands.py", line 1390, in promote
p.promote()
File "/pri/git/leo-editor/leo/core/leoNodes.py", line 1596, in promote
child.parents.remove(p.v)
ValueError: list.remove(x): x not in list
|
ValueError
|
def get_semver(tag):
"""Return 'Semantic Version' from tag string"""
try:
version = str(semantic_version.Version.coerce(tag, partial=True))
# tuple of major, minor, build, pre-release, patch
# 5.6b2 --> 5.6-b2
except ValueError:
print(
"""*** Failed to parse Semantic Version from git tag '{0}'.
Expecting tag name like '5.7b2', 'leo-4.9.12', 'v4.3' for releases.
This version can't be uploaded to PyPi.org.""".format(tag)
)
version = tag
return version
|
def get_semver(tag):
"""Return 'Semantic Version' from tag string"""
try:
version = semantic_version.Version.coerce(tag, partial=True)
# tuple of major, minor, build, pre-release, patch
# 5.6b2 --> 5.6-b2
except ValueError:
print(
"""*** Failed to parse Semantic Version from git tag '{0}'.
Expecting tag name like '5.7b2', 'leo-4.9.12', 'v4.3' for releases.
This version can't be uploaded to PyPi.org.""".format(tag)
)
version = tag
return version
|
https://github.com/leo-editor/leo-editor/issues/720
|
pip install --upgrade https://github.com/leo-editor/leo-editor/archive/5.7b2.zip
Collecting https://github.com/leo-editor/leo-editor/archive/5.7b2.zip
Downloading https://github.com/leo-editor/leo-editor/archive/5.7b2.zip
\ 11.4MB 4.9MB/s
Complete output from command python setup.py egg_info:
Removing build and dist directories
execGitCommand not found: C:\Users\mattw\AppData\Local\Temp\pip-usj2xnee-build\.git
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\mattw\AppData\Local\Temp\pip-usj2xnee-build\setup.py", line 115, in <module>
version=git_version(__file__),
File "C:\Users\mattw\AppData\Local\Temp\pip-usj2xnee-build\setup.py", line 30, in git_version
tag, distance, commit = g.gitDescribe(root)
File "C:\Users\mattw\AppData\Local\Temp\pip-usj2xnee-build\leo\core\leoGlobals.py", line 4468, in gitDescribe
tag, distance, commit = describe[0].rsplit('-',2)
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def git_version(file):
"""Fetch from Git: {tag} {distance-from-tag} {current commit hash}
Return as semantic version string compliant with PEP440"""
root = os.path.dirname(os.path.realpath(file))
tag, distance, commit = g.gitDescribe(root)
# 5.6b2, 55, e1129da
ctag = clean_git_tag(tag)
version = get_semver(ctag)
if int(distance) > 0:
version = "{}-dev{}".format(version, distance)
return version
|
def git_version(file):
"""Fetch from Git: {tag} {distance-from-tag} {current commit hash}
Return as semantic version string compliant with PEP440"""
root = os.path.dirname(os.path.realpath(file))
tag, distance, commit = g.gitDescribe(root)
# 5.6b2, 55, e1129da
ctag = clean_git_tag(tag)
try:
version = semantic_version.Version.coerce(ctag, partial=True)
# tuple of major, minor, build, pre-release, patch
# 5.6b2 --> 5.6-b2
except ValueError:
print(
"""*** Failed to parse Semantic Version from git tag '{0}'.
Expecting tag name like '5.7b2', 'leo-4.9.12', 'v4.3' for releases.
This version can't be uploaded to PyPi.org.""".format(tag)
)
version = tag
if int(distance) > 0:
version = "{}-dev{}".format(version, distance)
return version
|
https://github.com/leo-editor/leo-editor/issues/720
|
pip install --upgrade https://github.com/leo-editor/leo-editor/archive/5.7b2.zip
Collecting https://github.com/leo-editor/leo-editor/archive/5.7b2.zip
Downloading https://github.com/leo-editor/leo-editor/archive/5.7b2.zip
\ 11.4MB 4.9MB/s
Complete output from command python setup.py egg_info:
Removing build and dist directories
execGitCommand not found: C:\Users\mattw\AppData\Local\Temp\pip-usj2xnee-build\.git
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\mattw\AppData\Local\Temp\pip-usj2xnee-build\setup.py", line 115, in <module>
version=git_version(__file__),
File "C:\Users\mattw\AppData\Local\Temp\pip-usj2xnee-build\setup.py", line 30, in git_version
tag, distance, commit = g.gitDescribe(root)
File "C:\Users\mattw\AppData\Local\Temp\pip-usj2xnee-build\leo\core\leoGlobals.py", line 4468, in gitDescribe
tag, distance, commit = describe[0].rsplit('-',2)
TypeError: 'NoneType' object is not subscriptable
|
TypeError
|
def put_help(self, c, s, short_title=""):
"""Put the help command."""
trace = False and not g.unitTesting
s = g.adjustTripleString(s.rstrip(), c.tab_width)
if s.startswith("<") and not s.startswith("<<"):
pass # how to do selective replace??
pc = g.app.pluginsController
table = (
"viewrendered3.py",
"viewrendered2.py",
"viewrendered.py",
)
for name in table:
if pc.isLoaded(name):
if trace:
g.trace("already loaded", name)
vr = pc.loadOnePlugin(name)
break
else:
if trace:
g.trace("auto-loading viewrendered.py")
vr = pc.loadOnePlugin("viewrendered.py")
if vr:
kw = {
"c": c,
"flags": "rst",
"kind": "rst",
"label": "",
"msg": s,
"name": "Apropos",
"short_title": short_title,
"title": "",
}
vr.show_scrolled_message(tag="Apropos", kw=kw)
c.bodyWantsFocus()
if g.unitTesting:
vr.close_rendering_pane(event={"c": c})
elif g.unitTesting:
pass
else:
g.es(s)
return vr # For unit tests
|
def put_help(self, c, s, short_title=""):
"""Put the help command."""
s = g.adjustTripleString(s.rstrip(), c.tab_width)
if s.startswith("<") and not s.startswith("<<"):
pass # how to do selective replace??
pc = g.app.pluginsController
table = (
"viewrendered3.py",
"viewrendered2.py",
"viewrendered.py",
)
for name in table:
if pc.isLoaded(name):
vr = pc.loadOnePlugin(name)
break
else:
vr = pc.loadOnePlugin("viewrendered.py")
if vr:
kw = {
"c": c,
"flags": "rst",
"kind": "rst",
"label": "",
"msg": s,
"name": "Apropos",
"short_title": short_title,
"title": "",
}
vr.show_scrolled_message(tag="Apropos", kw=kw)
c.bodyWantsFocus()
if g.unitTesting:
vr.close_rendering_pane(event={"c": c})
elif g.unitTesting:
pass
else:
g.es(s)
return vr # For unit tests
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def init():
"""Return True if the plugin has loaded successfully."""
if import_ok: # Fix #734.
global got_docutils
if not got_docutils:
g.es_print("Warning: viewrendered2.py running without docutils.")
g.plugin_signon(__name__)
g.registerHandler("after-create-leo-frame", onCreate)
g.registerHandler("scrolledMessage", show_scrolled_message)
return True
return False
|
def init():
"""Return True if the plugin has loaded successfully."""
global got_docutils
if not got_docutils:
g.es_print("Warning: viewrendered2.py running without docutils.")
g.plugin_signon(__name__)
g.registerHandler("after-create-leo-frame", onCreate)
g.registerHandler("scrolledMessage", show_scrolled_message)
return True
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def init():
"""Return True if the plugin has loaded successfully."""
global got_docutils
if import_ok: # Fix #734.
if not got_docutils:
g.es_print("Warning: viewrendered2.py running without docutils.")
g.plugin_signon(__name__)
g.registerHandler("after-create-leo-frame", onCreate)
g.registerHandler("scrolledMessage", show_scrolled_message)
return True
return False
|
def init():
"""Return True if the plugin has loaded successfully."""
if import_ok: # Fix #734.
global got_docutils
if not got_docutils:
g.es_print("Warning: viewrendered2.py running without docutils.")
g.plugin_signon(__name__)
g.registerHandler("after-create-leo-frame", onCreate)
g.registerHandler("scrolledMessage", show_scrolled_message)
return True
return False
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def init_view(self):
"""Init the vr pane."""
# QWebView parts, including progress bar
view = QtWebKitWidgets.QWebView()
try:
# PyQt4
mf = view.page().mainFrame()
mf.contentsSizeChanged.connect(self.restore_scroll_position)
except AttributeError:
# PyQt5
pass
# ToolBar parts
self.export_button = QtWidgets.QPushButton("Export")
self.export_button.clicked.connect(self.export)
self.toolbar = QtWidgets.QToolBar()
self.toolbar.setIconSize(QtCore.QSize(16, 16))
for a in (QtWebKitWidgets.QWebPage.Back, QtWebKitWidgets.QWebPage.Forward):
self.toolbar.addAction(view.pageAction(a))
self.toolbar.setToolTip(
self.tooltip_text(
"""
Toolbar:
- Navigation buttons (like a normal browser),
- Reload button which is used to "update" this rendering pane
- Options tool-button to control the way rendering is done
- Export button to export to the standard browser
Keyboard shortcuts:
<b>Ctl-C</b> Copy html/text from the pane
Ctl-+ Zoom in
Ctl-- Zoom out
Ctl-= Zoom to original size"""
)
)
# Handle reload separately since this is used to re-render everything
self.reload_action = view.pageAction(QtWebKitWidgets.QWebPage.Reload)
self.reload_action.triggered.connect(self.render_delegate)
self.toolbar.addAction(self.reload_action)
# self.reload_action.clicked.connect(self.render)
# Create the "Mode" toolbutton
self.toolbutton = QtWidgets.QToolButton()
self.toolbutton.setText("Options")
self.toolbutton.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.toolbutton.setToolTip(
self.tooltip_text(
"""
Options:
Whole tree - Check this to render the whole tree rather than the node.
Verbose logging - Provide more verbose logging of the rendering process.
Auto-update - Check to automatically rerender when changes are made.
Lock to node - Lock the rendered node/tree while another node is editted.
Show as slideshow - Show a tree as an s5 slideshow (requires s5 support files).
Visible code - Show the code designated by '@language' directives
Execute code - Execute '@language' code blocks and show the output.
Code output reST - Assume code execution text output is reStructuredText."""
)
)
self.toolbar.addWidget(self.toolbutton)
# Add a progress bar
self.pbar = QtWidgets.QProgressBar()
self.pbar.setMaximumWidth(120)
menu = QtWidgets.QMenu()
def action(label):
action = QtWidgets.QAction(
label, self, checkable=True, triggered=self.state_change
)
menu.addAction(action)
return action
self.tree_mode_action = action("Whole tree")
self.verbose_mode_action = action("Verbose logging")
self.auto_mode_action = action("Auto-update")
self.lock_mode_action = action("Lock to node")
# Add an s5 option
self.slideshow_mode_action = action("Show as slideshow")
# self.s5_mode_action = action('s5 slideshow')
menu.addSeparator() # Separate render mode and code options
self.visible_code_action = action("Visible code")
self.code_only_action = action("Code Only")
self.execute_code_action = action("Execute code")
self.reST_code_action = action("Code outputs reST/md")
# radio button checkables example at
# http://stackoverflow.com/questions/10368947/how-to-make-qmenu-item-checkable-pyqt4-python
self.toolbutton.setMenu(menu)
# Remaining toolbar items
# self.toolbar.addSeparator()
# self.toolbar.addWidget(self.export_button)
# Create the 'Export' toolbutton
self.export_button = QtWidgets.QToolButton()
self.export_button.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.export_button.setToolTip(
self.tooltip_text(
"""
Show this in the default web-browser.
If the default browser is not already open it will be started. Exporting
is useful for full-screen slideshows and also for using the printing and
saving functions of the browser."""
)
)
self.toolbar.addWidget(self.export_button)
self.export_button.clicked.connect(self.export)
self.export_button.setText("Export")
# self.toolbar.addSeparator()
# Setting visibility in toolbar is tricky, must be done throug QAction
# http://www.qtcentre.org/threads/32437-remove-Widget-from-QToolBar
self.pbar_action = self.toolbar.addWidget(self.pbar)
self.pbar_action.setVisible(False)
# Document title in toolbar
# self.toolbar.addSeparator()
# spacer = QtWidgets.QWidget()
# spacer.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
# self.toolbar.addWidget(spacer)
self.title = QtWidgets.QLabel()
self.title.setSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
)
self.title.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.title.setTextFormat(1) # Set to rich text interpretation
# None of this font stuff works! - instead I've gone for rich text above
# font = QtGui.QFont("Sans Serif", 12, QtGui.QFont.Bold)
# font = QtGui.QFont("Arial", 8)
# font = QtGui.QFont()
# font.setBold(True)
# font.setWeight(75)
self.toolbar.addWidget(self.title) # if needed, use 'title_action ='
# title_action.setFont(font) # Set font of 'QAction' rather than widget
spacer = QtWidgets.QWidget()
spacer.setMinimumWidth(5)
self.toolbar.addWidget(spacer)
# Layouts
vlayout = QtWidgets.QVBoxLayout()
vlayout.setContentsMargins(0, 0, 0, 0) # Remove the default 11px margins
vlayout.addWidget(self.toolbar)
vlayout.addWidget(view)
self.setLayout(vlayout)
# Key shortcuts - zoom
view.setZoomFactor(1.0) # smallish panes demand small zoom
self.zoomIn = QtWidgets.QShortcut(
"Ctrl++", self, activated=lambda: view.setZoomFactor(view.zoomFactor() + 0.2)
)
self.zoomOut = QtWidgets.QShortcut(
"Ctrl+-", self, activated=lambda: view.setZoomFactor(view.zoomFactor() - 0.2)
)
self.zoomOne = QtWidgets.QShortcut(
"Ctrl+0", self, activated=lambda: view.setZoomFactor(0.8)
)
# Some QWebView settings
# setMaximumPagesInCache setting prevents caching of images etc.
# pylint:disable=no-member
if isQt5:
pass # not ready yet.
else:
view.settings().setAttribute(QtWebKitWidgets.QWebSettings.PluginsEnabled, True)
# Prevent caching, especially of images
try:
# PyQt4
view.settings().setMaximumPagesInCache(0)
view.settings().setObjectCacheCapacities(0, 0, 0)
except AttributeError:
# PyQt5
pass
# self.toolbar.setToolButtonStyle(Qt.ToolButtonTextOnly)
# Set up other widget states
return view
|
def init_view(self):
"""Init the vr pane."""
# QWebView parts, including progress bar
view = QtWebKitWidgets.QWebView()
try:
# PyQt4
mf = view.page().mainFrame()
mf.contentsSizeChanged.connect(self.restore_scroll_position)
except AttributeError:
# PyQt5
pass
# ToolBar parts
self.export_button = QtWidgets.QPushButton("Export")
self.export_button.clicked.connect(self.export)
self.toolbar = QtWidgets.QToolBar()
self.toolbar.setIconSize(QtCore.QSize(16, 16))
for a in (QtWebKitWidgets.QWebPage.Back, QtWebKitWidgets.QWebPage.Forward):
self.toolbar.addAction(view.pageAction(a))
self.toolbar.setToolTip(
self.tooltip_text(
"""
Toolbar:
- Navigation buttons (like a normal browser),
- Reload button which is used to "update" this rendering pane
- Options tool-button to control the way rendering is done
- Export button to export to the standard browser
Keyboard shortcuts:
<b>Ctl-C</b> Copy html/text from the pane
Ctl-+ Zoom in
Ctl-- Zoom out
Ctl-= Zoom to original size"""
)
)
# Handle reload separately since this is used to re-render everything
self.reload_action = view.pageAction(QtWebKitWidgets.QWebPage.Reload)
self.reload_action.triggered.connect(self.render_delegate)
self.toolbar.addAction(self.reload_action)
# self.reload_action.clicked.connect(self.render)
# Create the "Mode" toolbutton
self.toolbutton = QtWidgets.QToolButton()
self.toolbutton.setText("Options")
self.toolbutton.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.toolbutton.setToolTip(
self.tooltip_text(
"""
Options:
Whole tree - Check this to render the whole tree rather than the node.
Verbose logging - Provide more verbose logging of the rendering process.
Auto-update - Check to automatically rerender when changes are made.
Lock to node - Lock the rendered node/tree while another node is editted.
Show as slideshow - Show a tree as an s5 slideshow (requires s5 support files).
Visible code - Show the code designated by '@language' directives
Execute code - Execute '@language' code blocks and show the output.
Code output reST - Assume code execution text output is reStructuredText."""
)
)
self.toolbar.addWidget(self.toolbutton)
# Add a progress bar
self.pbar = QtWidgets.QProgressBar()
self.pbar.setMaximumWidth(120)
menu = QtWidgets.QMenu()
def action(label):
action = QtWidgets.QAction(
label, self, checkable=True, triggered=self.state_change
)
menu.addAction(action)
return action
self.tree_mode_action = action("Whole tree")
self.verbose_mode_action = action("Verbose logging")
self.auto_mode_action = action("Auto-update")
self.lock_mode_action = action("Lock to node")
# Add an s5 option
self.slideshow_mode_action = action("Show as slideshow")
# self.s5_mode_action = action('s5 slideshow')
menu.addSeparator() # Separate render mode and code options
self.visible_code_action = action("Visible code")
self.execute_code_action = action("Execute code")
self.reST_code_action = action("Code outputs reST/md")
# radio button checkables example at
# http://stackoverflow.com/questions/10368947/how-to-make-qmenu-item-checkable-pyqt4-python
self.toolbutton.setMenu(menu)
# Remaining toolbar items
# self.toolbar.addSeparator()
# self.toolbar.addWidget(self.export_button)
# Create the 'Export' toolbutton
self.export_button = QtWidgets.QToolButton()
self.export_button.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.export_button.setToolTip(
self.tooltip_text(
"""
Show this in the default web-browser.
If the default browser is not already open it will be started. Exporting
is useful for full-screen slideshows and also for using the printing and
saving functions of the browser."""
)
)
self.toolbar.addWidget(self.export_button)
self.export_button.clicked.connect(self.export)
self.export_button.setText("Export")
# self.toolbar.addSeparator()
# Setting visibility in toolbar is tricky, must be done throug QAction
# http://www.qtcentre.org/threads/32437-remove-Widget-from-QToolBar
self.pbar_action = self.toolbar.addWidget(self.pbar)
self.pbar_action.setVisible(False)
# Document title in toolbar
# self.toolbar.addSeparator()
# spacer = QtWidgets.QWidget()
# spacer.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
# self.toolbar.addWidget(spacer)
self.title = QtWidgets.QLabel()
self.title.setSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
)
self.title.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.title.setTextFormat(1) # Set to rich text interpretation
# None of this font stuff works! - instead I've gone for rich text above
# font = QtGui.QFont("Sans Serif", 12, QtGui.QFont.Bold)
# font = QtGui.QFont("Arial", 8)
# font = QtGui.QFont()
# font.setBold(True)
# font.setWeight(75)
self.toolbar.addWidget(self.title) # if needed, use 'title_action ='
# title_action.setFont(font) # Set font of 'QAction' rather than widget
spacer = QtWidgets.QWidget()
spacer.setMinimumWidth(5)
self.toolbar.addWidget(spacer)
# Layouts
vlayout = QtWidgets.QVBoxLayout()
vlayout.setContentsMargins(0, 0, 0, 0) # Remove the default 11px margins
vlayout.addWidget(self.toolbar)
vlayout.addWidget(view)
self.setLayout(vlayout)
# Key shortcuts - zoom
view.setZoomFactor(1.0) # smallish panes demand small zoom
self.zoomIn = QtWidgets.QShortcut(
"Ctrl++", self, activated=lambda: view.setZoomFactor(view.zoomFactor() + 0.2)
)
self.zoomOut = QtWidgets.QShortcut(
"Ctrl+-", self, activated=lambda: view.setZoomFactor(view.zoomFactor() - 0.2)
)
self.zoomOne = QtWidgets.QShortcut(
"Ctrl+0", self, activated=lambda: view.setZoomFactor(0.8)
)
# Some QWebView settings
# setMaximumPagesInCache setting prevents caching of images etc.
# pylint:disable=no-member
if isQt5:
pass # not ready yet.
else:
view.settings().setAttribute(QtWebKitWidgets.QWebSettings.PluginsEnabled, True)
# Prevent caching, especially of images
try:
# PyQt4
view.settings().setMaximumPagesInCache(0)
view.settings().setObjectCacheCapacities(0, 0, 0)
except AttributeError:
# PyQt5
pass
# self.toolbar.setToolButtonStyle(Qt.ToolButtonTextOnly)
# Set up other widget states
return view
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def init_config(self):
"""Init docutils settings."""
ds = {}
gc = self.c.config
def getConfig(getfun, name, default, setfun=None, setvar=None):
"""Make a shorthand way to get and store a setting with defaults"""
r = getfun("vr_" + name) # keep docutils name but prefix
if setfun: # settings are held in Qactions
if r:
setfun(r)
else:
setfun(default)
elif setvar: # Just setting a variable
if r:
setvar = r
else:
setvar = default
else: # settings held in dict (for docutils use)
if r:
ds[name] = r
else:
ds[name] = default
# Do docutils config (note that the vr_ prefix is omitted)
getConfig(gc.getString, "stylesheet_path", "")
getConfig(gc.getInt, "halt_level", 6)
getConfig(gc.getInt, "report_level", 5)
getConfig(gc.getString, "math-output", "mathjax")
getConfig(gc.getBool, "smart_quotes", True)
getConfig(gc.getBool, "embed_stylesheet", True)
getConfig(gc.getBool, "xml_declaration", False)
# Additional docutils values suggested by T P <wingusr@gmail.com>
getConfig(gc.getString, "syntax_highlight", "long")
getConfig(gc.getBool, "no_compact_lists", False)
getConfig(gc.getBool, "no_compact_field_lists", False)
# Markdown values: tbp
# This is a bit of a kludge, but getConfig() does not
# know about "self", and this way is easier than figuring out
# how to get a reference to the WenViewPlus instance.
def set_bg_color(color):
global MD_RENDERING_BG_COLOR
MD_RENDERING_BG_COLOR = color
getConfig(gc.getString, "md-rendering-pane-background-color", "black", set_bg_color)
# Do VR2 init values
getConfig(gc.getBool, "verbose", False, self.verbose_mode_action.setChecked)
getConfig(gc.getBool, "tree_mode", False, self.tree_mode_action.setChecked)
getConfig(gc.getBool, "auto_update", True, self.auto_mode_action.setChecked)
getConfig(gc.getBool, "lock_node", False, self.lock_mode_action.setChecked)
getConfig(gc.getBool, "slideshow", False, self.slideshow_mode_action.setChecked)
getConfig(gc.getBool, "visible_code", True, self.visible_code_action.setChecked)
getConfig(gc.getBool, "code_only", False, self.code_only_action.setChecked)
getConfig(gc.getBool, "execute_code", False, self.execute_code_action.setChecked)
getConfig(gc.getBool, "rest_code_output", False, self.reST_code_action.setChecked)
# Misc other internal settings
# Mark of the Web (for IE) to allow sensible security options
# getConfig(gc.getBool, 'include_MOTW', True, setvar=self.MOTW)
return ds
|
def init_config(self):
"""Init docutils settings."""
ds = {}
gc = self.c.config
def getConfig(getfun, name, default, setfun=None, setvar=None):
"""Make a shorthand way to get and store a setting with defaults"""
r = getfun("vr_" + name) # keep docutils name but prefix
if setfun: # settings are held in Qactions
if r:
setfun(r)
else:
setfun(default)
elif setvar: # Just setting a variable
if r:
setvar = r
else:
setvar = default
else: # settings held in dict (for docutils use)
if r:
ds[name] = r
else:
ds[name] = default
# Do docutils config (note that the vr_ prefix is omitted)
getConfig(gc.getString, "stylesheet_path", "")
getConfig(gc.getInt, "halt_level", 6)
getConfig(gc.getInt, "report_level", 5)
getConfig(gc.getString, "math_output", "mathjax")
getConfig(gc.getBool, "smart_quotes", True)
getConfig(gc.getBool, "embed_stylesheet", True)
getConfig(gc.getBool, "xml_declaration", False)
# Additional docutils values suggested by T P <wingusr@gmail.com>
getConfig(gc.getString, "syntax_highlight", "long")
getConfig(gc.getBool, "no_compact_lists", False)
getConfig(gc.getBool, "no_compact_field_lists", False)
# Do VR2 init values
getConfig(gc.getBool, "verbose", False, self.verbose_mode_action.setChecked)
getConfig(gc.getBool, "tree_mode", False, self.tree_mode_action.setChecked)
getConfig(gc.getBool, "auto_update", True, self.auto_mode_action.setChecked)
getConfig(gc.getBool, "lock_node", False, self.lock_mode_action.setChecked)
getConfig(gc.getBool, "slideshow", False, self.slideshow_mode_action.setChecked)
getConfig(gc.getBool, "visible_code", True, self.visible_code_action.setChecked)
getConfig(gc.getBool, "execute_code", False, self.execute_code_action.setChecked)
getConfig(gc.getBool, "rest_code_output", False, self.reST_code_action.setChecked)
# Misc other internal settings
# Mark of the Web (for IE) to allow sensible security options
# getConfig(gc.getBool, 'include_MOTW', True, setvar=self.MOTW)
return ds
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def getUIconfig(self):
"""Get the rendering configuration from the GUI controls."""
# Pull internal configuration options from GUI
self.verbose = self.verbose_mode_action.isChecked()
# self.output = 'html'
self.tree = self.tree_mode_action.isChecked()
self.execcode = self.execute_code_action.isChecked()
# If executing code, don't allow auto-mode otherwise navigation
# can lead to getting stuck doing many recalculations
if self.execcode:
self.auto_mode_action.setChecked(False)
self.auto = self.auto_mode_action.isChecked()
self.lock_mode = self.lock_mode_action.isChecked()
self.slideshow = self.slideshow_mode_action.isChecked()
self.showcode = self.visible_code_action.isChecked()
self.restoutput = self.reST_code_action.isChecked()
self.code_only = self.code_only_action.isChecked()
if self.code_only and not self.showcode:
self.visible_code_action.setChecked(True)
self.showcode = True
|
def getUIconfig(self):
"""Get the rendering configuration from the GUI controls."""
# Pull internal configuration options from GUI
self.verbose = self.verbose_mode_action.isChecked()
# self.output = 'html'
self.tree = self.tree_mode_action.isChecked()
self.execcode = self.execute_code_action.isChecked()
# If executing code, don't allow auto-mode otherwise navigation
# can lead to getting stuck doing many recalculations
if self.execcode:
self.auto_mode_action.setChecked(False)
self.auto = self.auto_mode_action.isChecked()
self.lock_mode = self.lock_mode_action.isChecked()
self.slideshow = self.slideshow_mode_action.isChecked()
self.showcode = self.visible_code_action.isChecked()
self.restoutput = self.reST_code_action.isChecked()
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def process_one_node(self, p, result, environment):
"""Handle one node."""
c = self.c
if not self.code_only:
result.append(self.underline2(p))
d = c.scanAllDirectives(p)
if self.verbose:
g.trace(d.get("language") or "None", ":", p.h)
s, code = self.process_directives(p.b, d)
result.append(s)
result.append("\n\n")
# Add an empty line so bullet lists display properly.
if code and self.execcode:
s, err = self.exec_code(code, environment)
# execute code found in a node, append to reST
if not self.restoutput and s.strip():
s = self.format_output(s) # if some non-reST to print
result.append(s) # append, whether plain or reST output
if err:
err = self.format_output(err, prefix="**Error**::")
result.append(err)
|
def process_one_node(self, p, result, environment):
"""Handle one node."""
c = self.c
result.append(self.underline2(p))
d = c.scanAllDirectives(p)
if self.verbose:
g.trace(d.get("language") or "None", ":", p.h)
s, code = self.process_directives(p.b, d)
result.append(s)
result.append("\n\n")
# Add an empty line so bullet lists display properly.
if code and self.execcode:
s, err = self.exec_code(code, environment)
# execute code found in a node, append to reST
if not self.restoutput and s.strip():
s = self.format_output(s) # if some non-reST to print
result.append(s) # append, whether plain or reST output
if err:
err = self.format_output(err, prefix="**Error**::")
result.append(err)
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def process_directives(self, s, d):
"""s is string to process, d is dictionary of directives at the node."""
trace = False and not g.unitTesting
lang = d.get("language") or "python" # EKR.
codeflag = lang != "rest" # EKR
lines = g.splitLines(s)
result = []
code = ""
if codeflag and self.showcode:
result.append(self.code_directive(lang)) # EKR
for s in lines:
if s.startswith("@"):
i = g.skip_id(s, 1)
word = s[1:i]
# Add capability to detect mid-node language directives (not really that useful).
# Probably better to just use a code directive. "execute-script" is not possible.
# If removing, ensure "if word in g.globalDirectiveList: continue" is retained
# to stop directive being put into the reST output.
if word == "language" and not codeflag: # only if not already code
lang = s[i:].strip()
codeflag = lang in [
"python",
]
if codeflag:
if self.verbose:
g.es("New code section within node:", lang)
if self.showcode:
result.append(self.code_directive(lang)) # EKR
else:
result.append("\n\n")
continue
elif word in g.globalDirectiveList:
continue
if codeflag:
emit_line = (
not (s.startswith("@") or s.startswith("<<"))
if self.code_only
else True
)
if self.showcode and emit_line:
result.append(" " + s) # 4 space indent on each line
code += s # accumulate code lines for execution
else:
if not self.code_only:
result.append(s)
result = "".join(result)
if trace:
g.trace("result:\n", result) # ,'\ncode:',code)
return result, code
|
def process_directives(self, s, d):
"""s is string to process, d is dictionary of directives at the node."""
trace = False and not g.unitTesting
lang = d.get("language") or "python" # EKR.
codeflag = lang != "rest" # EKR
lines = g.splitLines(s)
result = []
code = ""
if codeflag and self.showcode:
result.append(self.code_directive(lang)) # EKR
for s in lines:
if s.startswith("@"):
i = g.skip_id(s, 1)
word = s[1:i]
# Add capability to detect mid-node language directives (not really that useful).
# Probably better to just use a code directive. "execute-script" is not possible.
# If removing, ensure "if word in g.globalDirectiveList: continue" is retained
# to stop directive being put into the reST output.
if word == "language" and not codeflag: # only if not already code
lang = s[i:].strip()
codeflag = lang in [
"python",
]
if codeflag:
if self.verbose:
g.es("New code section within node:", lang)
if self.showcode:
result.append(self.code_directive(lang)) # EKR
else:
result.append("\n\n")
continue
elif word in g.globalDirectiveList:
continue
if codeflag:
if self.showcode:
result.append(" " + s) # 4 space indent on each line
code += s # accumulate code lines for execution
else:
result.append(s)
result = "".join(result)
if trace:
g.trace("result:\n", result) # ,'\ncode:',code)
return result, code
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def md_to_html(self, p):
"""Convert p.b to html using markdown."""
c, pc = self.c, self.pc
mf = self.view.page().mainFrame()
path = g.scanAllAtPathDirectives(c, p) or c.getNodePath(p)
if not os.path.isdir(path):
path = os.path.dirname(path)
if os.path.isdir(path):
os.chdir(path)
# Need to save position of last node before rendering
ps = mf.scrollBarValue(QtCore.Qt.Vertical)
pc.scrollbar_pos_dict[self.last_node.v] = ps
# Which node should be rendered?
if self.lock_mode:
# use locked node for position to be rendered.
self.pr = self.plock
else:
# use new current node, whether changed or not.
self.pr = c.p # use current node
self.last_node = self.pr.copy()
# Store this node as last node rendered
# Set the node header in the toolbar.
self.title.setText("" if self.s else "<b>" + self.pr.h + "</b>")
if not self.auto:
self.pbar.setValue(0)
self.pbar_action.setVisible(True)
# Handle all the nodes in the tree.
html = self.md_process_nodes(self.pr, tree=self.tree)
if not self.auto:
self.pbar.setValue(50)
self.app.processEvents()
# Apparently this can't be done in docutils.
try:
# Call markdown to get the string.
mdext = c.config.getString("view-rendered-md-extensions") or "extra"
mdext = [x.strip() for x in mdext.split(",")]
if pygments:
mdext.append("codehilite")
html = markdown(html, mdext)
# tbp: this is a kludge to change the background color
# of the rendering pane. Markdown does not emit
# a css style sheet, but the browser will apply
# a style element at the top of the page to the
# whole page. MD_RENDERING_BG_COLOR is a global
# variable set during the config process.
html = (
'<style type="text/css">body{background-color:%s;}</style>\n'
% (MD_RENDERING_BG_COLOR)
+ html
)
return g.toUnicode(html)
except Exception as e:
print(e)
return "Markdown error... %s" % e
|
def md_to_html(self, p):
"""Convert p.b to html using markdown."""
c, pc = self.c, self.pc
mf = self.view.page().mainFrame()
path = g.scanAllAtPathDirectives(c, p) or c.getNodePath(p)
if not os.path.isdir(path):
path = os.path.dirname(path)
if os.path.isdir(path):
os.chdir(path)
# Need to save position of last node before rendering
ps = mf.scrollBarValue(QtCore.Qt.Vertical)
pc.scrollbar_pos_dict[self.last_node.v] = ps
# Which node should be rendered?
if self.lock_mode:
# use locked node for position to be rendered.
self.pr = self.plock
else:
# use new current node, whether changed or not.
self.pr = c.p # use current node
self.last_node = self.pr.copy()
# Store this node as last node rendered
# Set the node header in the toolbar.
self.title.setText("" if self.s else "<b>" + self.pr.h + "</b>")
if not self.auto:
self.pbar.setValue(0)
self.pbar_action.setVisible(True)
# Handle all the nodes in the tree.
html = self.md_process_nodes(self.pr, tree=self.tree)
if not self.auto:
self.pbar.setValue(50)
self.app.processEvents()
# Apparently this can't be done in docutils.
try:
# Call markdown to get the string.
mdext = c.config.getString("view-rendered-md-extensions") or "extra"
mdext = [x.strip() for x in mdext.split(",")]
if pygments:
mdext.append("codehilite")
html = markdown(html, mdext)
return g.toUnicode(html)
except Exception as e:
print(e)
return "Markdown error... %s" % e
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def md_process_one_node(self, p, result, environment):
"""Handle one node."""
c = self.c
if not self.code_only:
result.append(self.md_underline2(p))
d = c.scanAllDirectives(p)
if self.verbose:
g.trace(d.get("language") or "None", ":", p.h)
s, code = self.md_process_directives(p.b, d)
result.append(s)
result.append("\n\n")
# Add an empty line so bullet lists display properly.
if code and self.execcode:
s, err = self.md_exec_code(code, environment)
# execute code found in a node, append to md
if not self.restoutput and s.strip():
s = self.md_format_output(s) # if some non-md to print
result.append(s) # append, whether plain or md output
if err:
err = self.md_format_output(err, prefix="**Error**:")
result.append(err)
|
def md_process_one_node(self, p, result, environment):
"""Handle one node."""
c = self.c
result.append(self.md_underline2(p))
d = c.scanAllDirectives(p)
if self.verbose:
g.trace(d.get("language") or "None", ":", p.h)
s, code = self.md_process_directives(p.b, d)
result.append(s)
result.append("\n\n")
# Add an empty line so bullet lists display properly.
if code and self.execcode:
s, err = self.md_exec_code(code, environment)
# execute code found in a node, append to md
if not self.restoutput and s.strip():
s = self.md_format_output(s) # if some non-md to print
result.append(s) # append, whether plain or md output
if err:
err = self.md_format_output(err, prefix="**Error**:")
result.append(err)
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def md_process_directives(self, s, d):
"""s is string to process, d is dictionary of directives at the node."""
trace = False and not g.unitTesting
lang = d.get("language") or "python" # EKR.
codeflag = lang != "md" # EKR
lines = g.splitLines(s)
result = []
code = ""
if codeflag and self.showcode:
result.append(self.md_code_directive(lang)) # EKR
for s in lines:
if s.startswith("@"):
i = g.skip_id(s, 1)
word = s[1:i]
# Add capability to detect mid-node language directives (not really that useful).
# Probably better to just use a code directive. "execute-script" is not possible.
# If removing, ensure "if word in g.globalDirectiveList: continue" is retained
# to stop directive being put into the reST output.
if word == "language" and not codeflag: # only if not already code
lang = s[i:].strip()
codeflag = lang in [
"python",
]
if codeflag:
if self.verbose:
g.es("New code section within node:", lang)
if self.showcode:
result.append(self.md_code_directive(lang)) # EKR
else:
result.append("\n\n")
continue
elif word in g.globalDirectiveList:
continue
if codeflag:
emit_line = (
not (s.startswith("@") or s.startswith("<<"))
if self.code_only
else True
)
if self.showcode and emit_line:
result.append(" " + s) # 4 space indent on each line
code += s # accumulate code lines for execution
else:
if not self.code_only:
result.append(s)
result = "".join(result)
if trace:
g.trace("result:\n", result) # ,'\ncode:',code)
return result, code
|
def md_process_directives(self, s, d):
"""s is string to process, d is dictionary of directives at the node."""
trace = False and not g.unitTesting
lang = d.get("language") or "python" # EKR.
codeflag = lang != "md" # EKR
lines = g.splitLines(s)
result = []
code = ""
if codeflag and self.showcode:
result.append(self.md_code_directive(lang)) # EKR
for s in lines:
if s.startswith("@"):
i = g.skip_id(s, 1)
word = s[1:i]
# Add capability to detect mid-node language directives (not really that useful).
# Probably better to just use a code directive. "execute-script" is not possible.
# If removing, ensure "if word in g.globalDirectiveList: continue" is retained
# to stop directive being put into the reST output.
if word == "language" and not codeflag: # only if not already code
lang = s[i:].strip()
codeflag = lang in [
"python",
]
if codeflag:
if self.verbose:
g.es("New code section within node:", lang)
if self.showcode:
result.append(self.md_code_directive(lang)) # EKR
else:
result.append("\n\n")
continue
elif word in g.globalDirectiveList:
continue
if codeflag:
if self.showcode:
result.append(" " + s) # 4 space indent on each line
code += s # accumulate code lines for execution
else:
result.append(s)
result = "".join(result)
if trace:
g.trace("result:\n", result) # ,'\ncode:',code)
return result, code
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def __init__(self, c, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setObjectName("viewrendered_pane")
self.setLayout(QtWidgets.QVBoxLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self.active = False
self.c = c
self.badColors = []
self.delete_callback = None
self.gnx = None
self.inited = False
self.gs = None # For @graphics-script: a QGraphicsScene
self.gv = None # For @graphics-script: a QGraphicsView
# self.kind = 'rst' # in self.dispatch_dict.keys()
self.length = 0 # The length of previous p.b.
self.locked = False
self.scrollbar_pos_dict = {} # Keys are vnodes, values are positions.
self.sizes = [] # Saved splitter sizes.
self.splitter_index = None # The index of the rendering pane in the splitter.
self.svg_class = QtSvg.QSvgWidget
self.text_class = QtWidgets.QTextBrowser # QtWidgets.QTextEdit
self.html_class = WebViewPlus # QtWebKitWidgets.QWebView
self.graphics_class = QtWidgets.QGraphicsWidget
self.vp = None # The present video player.
self.w = None # The present widget in the rendering pane.
self.title = None
# User-options
self.reloadSettings()
self.node_changed = True
# Init.
self.create_dispatch_dict()
self.activate()
# ---------------PMM additional elements for WebView additions for reST
self.reflevel = 0
# Special-mode rendering settings
self.verbose = False
self.output = "html"
self.tree = True
self.showcode = True
self.code_only = False
self.execcode = False
self.restoutput = False
|
def __init__(self, c, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setObjectName("viewrendered_pane")
self.setLayout(QtWidgets.QVBoxLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self.active = False
self.c = c
self.badColors = []
self.delete_callback = None
self.gnx = None
self.inited = False
self.gs = None # For @graphics-script: a QGraphicsScene
self.gv = None # For @graphics-script: a QGraphicsView
# self.kind = 'rst' # in self.dispatch_dict.keys()
self.length = 0 # The length of previous p.b.
self.locked = False
self.scrollbar_pos_dict = {} # Keys are vnodes, values are positions.
self.sizes = [] # Saved splitter sizes.
self.splitter_index = None # The index of the rendering pane in the splitter.
self.svg_class = QtSvg.QSvgWidget
self.text_class = QtWidgets.QTextBrowser # QtWidgets.QTextEdit
self.html_class = WebViewPlus # QtWebKitWidgets.QWebView
self.graphics_class = QtWidgets.QGraphicsWidget
self.vp = None # The present video player.
self.w = None # The present widget in the rendering pane.
self.title = None
# User-options
self.reloadSettings()
self.node_changed = True
# Init.
self.create_dispatch_dict()
self.activate()
# ---------------PMM additional elements for WebView additions for reST
self.reflevel = 0
# Special-mode rendering settings
self.verbose = False
self.output = "html"
self.tree = True
self.showcode = True
self.execcode = False
self.restoutput = False
|
https://github.com/leo-editor/leo-editor/issues/734
|
Traceback (most recent call last):
File "c:\leo.repo\leo-editor\leo\core\leoGlobals.py", line 2385, in new_cmd_wrapper
func(self, event=event)
File "c:\leo.repo\leo-editor\leo\commands\helpCommands.py", line 62, in help
self.c.putHelpFor(rst_s)
File "c:\leo.repo\leo-editor\leo\core\leoCommands.py", line 2322, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "c:\leo.repo\leo-editor\leo\plugins\qt_gui.py", line 1055, in put_help
vr.show_scrolled_message(tag='Apropos', kw=kw)
File "c:\leo.repo\leo-editor\leo\plugins\viewrendered2.py", line 299, in show_scrolled_message
vr = viewrendered(event=kw)
NameError: name 'viewrendered' is not defined
|
NameError
|
def compute_last_index(self, c):
"""Scan the entire leo outline to compute ni.last_index."""
trace = False and not g.unitTesting
verbose = True # Report only if lastIndex was changed.
if trace:
t1 = time.time()
ni = self
old_lastIndex = self.lastIndex
# Partial, experimental, fix for #658.
# Do not change self.lastIndex here!
# self.lastIndex = 0
for v in c.all_unique_nodes():
gnx = v.fileIndex
if trace and verbose:
g.trace(gnx)
if gnx:
id_, t, n = self.scanGnx(gnx)
if t == ni.timeString and n is not None:
try:
n = int(n)
self.lastIndex = max(self.lastIndex, n)
if trace and verbose:
g.trace(n, gnx)
except Exception:
g.es_exception()
self.lastIndex += 1
if trace:
changed = self.lastIndex > old_lastIndex
t2 = time.time()
if verbose:
g.trace(
"========== time %4.2f changed: %5s lastIndex: old: %s new: %s"
% (t2 - t1, changed, old_lastIndex, self.lastIndex)
)
elif changed:
g.trace(
"========== time %4.2f lastIndex: old: %s new: %s"
% (t2 - t1, old_lastIndex, self.lastIndex)
)
|
def compute_last_index(self, c):
"""Scan the entire leo outline to compute ni.last_index."""
trace = False and not g.unitTesting
verbose = False # Report only if lastIndex was changed.
if trace:
t1 = time.time()
ni = self
old_lastIndex = self.lastIndex
self.lastIndex = 0
for v in c.all_unique_nodes():
gnx = v.fileIndex
if gnx:
id_, t, n = self.scanGnx(gnx)
if t == ni.timeString and n is not None:
try:
n = int(n)
self.lastIndex = max(self.lastIndex, n)
except Exception:
g.es_exception()
self.lastIndex += 1
if trace:
changed = self.lastIndex > old_lastIndex
t2 = time.time()
if verbose:
g.trace(
"========== time %4.2f changed: %5s lastIndex: old: %s new: %s"
% (t2 - t1, changed, old_lastIndex, self.lastIndex)
)
elif changed:
g.trace(
"========== time %4.2f lastIndex: old: %s new: %s"
% (t2 - t1, old_lastIndex, self.lastIndex)
)
|
https://github.com/leo-editor/leo-editor/issues/658
|
2018-01-25 14:32:51 /pri/git/leo_bug_demos/2018-01-25-leoBridge-Closed-sqlite3
$ python3 opOnClosedSqlite3.py
Traceback (most recent call last):
File "opOnClosedSqlite3.py", line 23, in <module>
main()
File "opOnClosedSqlite3.py", line 20, in main
cmdrX.close()
File "/pri/git/leo-editor/leo/commands/commanderFileCommands.py", line 51, in close
g.app.closeLeoWindow(self.frame, new_c=new_c)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 1277, in closeLeoWindow
g.app.forgetOpenFile(fn=c.fileName(), force=True)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 1398, in forgetOpenFile
aList = d.get(tag) or []
File "/pri/git/leo-editor/leo/core/leoCache.py", line 934, in get
if not self.has_key(key):return default
File "/pri/git/leo-editor/leo/core/leoCache.py", line 945, in has_key
for row in self.conn.execute(sql, (key,)):
sqlite3.ProgrammingError: Cannot operate on a closed database.
2018-01-25 14:39:08 /pri/git/leo_bug_demos/2018-01-25-leoBridge-Closed-sqlite3
$ python3 opOnClosedSqlite3.py
Internal Leo error in check_gnx
getNewIndex: gnx clash bob.20180125143918.2: v: <VNode 7f99af4160f0 newHeadline> v2: <VNode 7f99af40f710 NewHeadline>
Called from <module>, main, insertAfter, __init__, new_vnode_helper, getNewIndex
Please report this error to Leo's developers
Traceback (most recent call last):
File "opOnClosedSqlite3.py", line 23, in <module>
main()
File "opOnClosedSqlite3.py", line 13, in main
cmdrX = bridge.openLeoFile('bugdemo{0:02d}.leo'.format(fidx))
File "/pri/git/leo-editor/leo/core/leoBridge.py", line 259, in openLeoFile
c = self.createFrame(fileName)
File "/pri/git/leo-editor/leo/core/leoBridge.py", line 293, in createFrame
c = g.openWithFileName(fileName)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 3318, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 3058, in loadLocalFile
c = lm.openFileByName(fn, gui, old_c, previousSettings)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 3099, in openFileByName
ok = lm.readOpenedLeoFile(c, fn, readAtFileNodesFlag, theFile)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 3274, in readOpenedLeoFile
readAtFileNodesFlag=readAtFileNodesFlag)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 843, in openLeoFile
silent=silent,
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 658, in getLeoFile
g.app.checkForOpenFile(c, fileName)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 1376, in checkForOpenFile
aList = g.app.db.get(tag) or []
File "/pri/git/leo-editor/leo/core/leoCache.py", line 934, in get
if not self.has_key(key):return default
File "/pri/git/leo-editor/leo/core/leoCache.py", line 945, in has_key
for row in self.conn.execute(sql, (key,)):
sqlite3.ProgrammingError: Cannot operate on a closed database.
2018-01-25 14:39:18 /pri/git/leo_bug_demos/2018-01-25-leoBridge-Closed-sqlite3
|
sqlite3.ProgrammingError
|
def openLeoFile(self, fileName):
"""Open a .leo file, or create a new Leo frame if no fileName is given."""
g = self.g
g.app.silentMode = self.silentMode
useLog = False
if self.isOpen():
self.reopen_cachers()
fileName = self.completeFileName(fileName)
c = self.createFrame(fileName)
g.app.nodeIndices.compute_last_index(c)
# New in Leo 5.1. An alternate fix for bug #130.
# When using a bridge Leo might open a file, modify it,
# close it, reopen it and change it all within one second.
# In that case, this code must properly compute the next
# available gnx by scanning the entire outline.
if useLog:
g.app.gui.log = log = c.frame.log
log.isNull = False
log.enabled = True
return c
return None
|
def openLeoFile(self, fileName):
"""Open a .leo file, or create a new Leo frame if no fileName is given."""
g = self.g
g.app.silentMode = self.silentMode
useLog = False
if self.isOpen():
fileName = self.completeFileName(fileName)
c = self.createFrame(fileName)
g.app.nodeIndices.compute_last_index(c)
# New in Leo 5.1. An alternate fix for bug #130.
# When using a bridge Leo might open a file, modify it,
# close it, reopen it and change it all within one second.
# In that case, this code must properly compute the next
# available gnx by scanning the entire outline.
if useLog:
g.app.gui.log = log = c.frame.log
log.isNull = False
log.enabled = True
return c
return None
|
https://github.com/leo-editor/leo-editor/issues/658
|
2018-01-25 14:32:51 /pri/git/leo_bug_demos/2018-01-25-leoBridge-Closed-sqlite3
$ python3 opOnClosedSqlite3.py
Traceback (most recent call last):
File "opOnClosedSqlite3.py", line 23, in <module>
main()
File "opOnClosedSqlite3.py", line 20, in main
cmdrX.close()
File "/pri/git/leo-editor/leo/commands/commanderFileCommands.py", line 51, in close
g.app.closeLeoWindow(self.frame, new_c=new_c)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 1277, in closeLeoWindow
g.app.forgetOpenFile(fn=c.fileName(), force=True)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 1398, in forgetOpenFile
aList = d.get(tag) or []
File "/pri/git/leo-editor/leo/core/leoCache.py", line 934, in get
if not self.has_key(key):return default
File "/pri/git/leo-editor/leo/core/leoCache.py", line 945, in has_key
for row in self.conn.execute(sql, (key,)):
sqlite3.ProgrammingError: Cannot operate on a closed database.
2018-01-25 14:39:08 /pri/git/leo_bug_demos/2018-01-25-leoBridge-Closed-sqlite3
$ python3 opOnClosedSqlite3.py
Internal Leo error in check_gnx
getNewIndex: gnx clash bob.20180125143918.2: v: <VNode 7f99af4160f0 newHeadline> v2: <VNode 7f99af40f710 NewHeadline>
Called from <module>, main, insertAfter, __init__, new_vnode_helper, getNewIndex
Please report this error to Leo's developers
Traceback (most recent call last):
File "opOnClosedSqlite3.py", line 23, in <module>
main()
File "opOnClosedSqlite3.py", line 13, in main
cmdrX = bridge.openLeoFile('bugdemo{0:02d}.leo'.format(fidx))
File "/pri/git/leo-editor/leo/core/leoBridge.py", line 259, in openLeoFile
c = self.createFrame(fileName)
File "/pri/git/leo-editor/leo/core/leoBridge.py", line 293, in createFrame
c = g.openWithFileName(fileName)
File "/pri/git/leo-editor/leo/core/leoGlobals.py", line 3318, in openWithFileName
return g.app.loadManager.loadLocalFile(fileName, gui, old_c)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 3058, in loadLocalFile
c = lm.openFileByName(fn, gui, old_c, previousSettings)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 3099, in openFileByName
ok = lm.readOpenedLeoFile(c, fn, readAtFileNodesFlag, theFile)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 3274, in readOpenedLeoFile
readAtFileNodesFlag=readAtFileNodesFlag)
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 843, in openLeoFile
silent=silent,
File "/pri/git/leo-editor/leo/core/leoFileCommands.py", line 658, in getLeoFile
g.app.checkForOpenFile(c, fileName)
File "/pri/git/leo-editor/leo/core/leoApp.py", line 1376, in checkForOpenFile
aList = g.app.db.get(tag) or []
File "/pri/git/leo-editor/leo/core/leoCache.py", line 934, in get
if not self.has_key(key):return default
File "/pri/git/leo-editor/leo/core/leoCache.py", line 945, in has_key
for row in self.conn.execute(sql, (key,)):
sqlite3.ProgrammingError: Cannot operate on a closed database.
2018-01-25 14:39:18 /pri/git/leo_bug_demos/2018-01-25-leoBridge-Closed-sqlite3
|
sqlite3.ProgrammingError
|
def do_ClassDef(self, node):
result = []
name = node.name # Only a plain string is valid.
bases = [self.visit(z) for z in node.bases] if node.bases else []
if getattr(node, "keywords", None): # Python 3
for keyword in node.keywords:
bases.append("%s=%s" % (keyword.arg, self.visit(keyword.value)))
if getattr(node, "starargs", None): # Python 3
bases.append("*%s" % self.visit(node.starargs))
if getattr(node, "kwargs", None): # Python 3
bases.append("*%s" % self.visit(node.kwargs))
if bases:
result.append(self.indent("class %s(%s):\n" % (name, ",".join(bases))))
else:
result.append(self.indent("class %s:\n" % name))
for z in node.body:
self.level += 1
result.append(self.visit(z))
self.level -= 1
return "".join(result)
|
def do_ClassDef(self, node):
result = []
name = node.name # Only a plain string is valid.
bases = [self.visit(z) for z in node.bases] if node.bases else []
if getattr(node, "keywords", None): # Python 3
for keyword in node.keywords:
bases.append("%s=%s" % (keyword.arg, self.visit(keyword.value)))
if getattr(node, "starargs", None): # Python 3
bases.append("*%s", self.visit(node.starargs))
if getattr(node, "kwargs", None): # Python 3
bases.append("*%s", self.visit(node.kwargs))
if bases:
result.append(self.indent("class %s(%s):\n" % (name, ",".join(bases))))
else:
result.append(self.indent("class %s:\n" % name))
for z in node.body:
self.level += 1
result.append(self.visit(z))
self.level -= 1
return "".join(result)
|
https://github.com/leo-editor/leo-editor/issues/512
|
Trying to create a QVariant instance of QMetaType::Void type, an
invalid QVariant will be constructed instead
[this is repeated many many times]
======================================================================
ERROR: runTest (leo.core.leoTest.GeneralTestCase)
@test rST import test
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 74, in <module>
assert root.h.startswith('@@'), root.h
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 1635, in __get_h
return p.headString()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 672, in headString
return self.v.headString()
AttributeError: 'NoneType' object has no attribute 'headString'
======================================================================
ERROR: runTest (leo.core.leoTest.GeneralTestCase)
@test rST import test: simple
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 22, in <module>
assert root.h.startswith('@@'), root.h
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 1635, in __get_h
return p.headString()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 672, in headString
return self.v.headString()
AttributeError: 'NoneType' object has no attribute 'headString'
======================================================================
ERROR: runTest (leo.core.leoTest.GeneralTestCase)
@test rST import test: no double-underlines
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 73, in <module>
assert root.h.startswith('@@'), root.h
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 1635, in __get_h
return p.headString()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 672, in headString
return self.v.headString()
AttributeError: 'NoneType' object has no attribute 'headString'
======================================================================
ERROR: runTest (leo.core.leoTest.GeneralTestCase)
@test rST import test: long underlines
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 34, in <module>
assert root.h.startswith('@@'), root.h
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 1635, in __get_h
return p.headString()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 672, in headString
return self.v.headString()
AttributeError: 'NoneType' object has no attribute 'headString'
======================================================================
ERROR: runTest (leo.core.leoTest.GeneralTestCase)
@test rST import test: long overlines
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 35, in <module>
assert root.h.startswith('@@'), root.h
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 1635, in __get_h
return p.headString()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 672, in headString
return self.v.headString()
AttributeError: 'NoneType' object has no attribute 'headString'
======================================================================
ERROR: runTest (leo.core.leoTest.GeneralTestCase)
@test rST import test: trailing whitespace
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 22, in <module>
assert root.h.startswith('@@'), root.h
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 1635, in __get_h
return p.headString()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 672, in headString
return self.v.headString()
AttributeError: 'NoneType' object has no attribute 'headString'
======================================================================
ERROR: runTest (leo.core.leoTest.GeneralTestCase)
@test leo_rst
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 48, in <module>
assert root.h.startswith('@@'), root.h
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 1635, in __get_h
return p.headString()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoNodes.py", line 672, in headString
return self.v.headString()
AttributeError: 'NoneType' object has no attribute 'headString'
======================================================================
ERROR: runTest (leo.core.leoTest.GeneralTestCase)
@test x.makeShadowDirectory
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 31, in <module>
deleteShadowDir(shadow_dir)
File "/home/tbrown/.leo/scriptFile.py", line 20, in deleteShadowDir
os.rmdir(shadow_dir)
OSError: [Errno 39] Directory not empty: '/home/tbrown/.leo/shadow'
======================================================================
FAIL: runTest (leo.core.leoTest.GeneralTestCase)
@test all commands have an event arg
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 26, in <module>
assert arg0 in expected or arg1 in expected, message
AssertionError:
no event arg for command quickmove_bookmark_to_first_child, func: <lambda>
args: ArgSpec(args=['e'], varargs=None, keywords=None, defaults=None)
======================================================================
FAIL: runTest (leo.core.leoTest.GeneralTestCase)
@test add/delete html comments
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 27, in <module>
assert p.b == s,'fail5: s\n%s\nresult\n%s' % (repr(s),repr(p.b))
AssertionError: fail5: s
u'@language html\n<html>\n text \n</html>\n'
result
u'@language html\n<html>\n text \n</html>\n'
======================================================================
FAIL: runTest (leo.core.leoTest.GeneralTestCase)
@test helpForbindings
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 7, in <module>
c.helpCommands.helpForBindings()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/commands/helpCommands.py", line 326, in helpForBindings
self.c.putHelpFor(s)
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoCommands.py", line 7020, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/plugins/qt_gui.py", line 1029, in put_help
assert vr # For unit testing.
AssertionError
======================================================================
FAIL: runTest (leo.core.leoTest.GeneralTestCase)
@test helpForFindCommands
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 7, in <module>
c.helpCommands.helpForFindCommands()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/commands/helpCommands.py", line 756, in helpForFindCommands
self.c.putHelpFor(s)
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoCommands.py", line 7020, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/plugins/qt_gui.py", line 1029, in put_help
assert vr # For unit testing.
AssertionError
======================================================================
FAIL: runTest (leo.core.leoTest.GeneralTestCase)
@test helpForMinibuffer
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 211, in runTest
builtins.execfile(scriptFile, d)
File "/home/tbrown/.leo/scriptFile.py", line 6, in <module>
c.helpCommands.helpForMinibuffer()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/commands/helpCommands.py", line 815, in helpForMinibuffer
c.putHelpFor(s)
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoCommands.py", line 7020, in putHelpFor
g.app.gui.put_help(c, s, short_title)
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/plugins/qt_gui.py", line 1029, in put_help
assert vr # For unit testing.
AssertionError
======================================================================
FAIL: runTest (leo.core.leoTest.EditBodyTestCase)
EditBodyTestCase: addComments
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 105, in runTest
self.editBody()
File "/mnt/usr1/usr1/home/tbrown/t/Package/leo/git/leo-editor/leo/core/leoTest.py", line 85, in editBody
compareHeadlines=False), '%s: before undo1' % commandName
AssertionError: addComments: before undo1
----------------------------------------------------------------------
Ran 904 tests in 108.952s
FAILED (failures=6, errors=8, skipped=28)
tb:la: ~/t/Package/leo/git/leo-editor
leo-editorlocalhost:11.0>
|
AttributeError
|
def copy_to_my_settings(self, unl, which):
"""copy_to_my_settings - copy setting from leoSettings.leo
:param str unl: Leo UNL to copy from
:param int which: 1-3, leaf, leaf's parent, leaf's grandparent
:return: unl of leaf copy in myLeoSettings.leo
:rtype: str
"""
trace = False and not g.unitTesting
if trace:
g.es(unl)
path, unl = unl.split("#", 1)
# Undo the replacements made in p.getUNL.
path = path.replace("file://", "")
path = path.replace("unl://", "")
# Fix #434: Potential bug in settings
unl = unl.replace("%20", " ").split("-->")
tail = []
if which > 1: # copying parent or grandparent but select leaf later
tail = unl[-(which - 1) :]
unl = unl[: len(unl) + 1 - which]
my_settings_c = self.c.openMyLeoSettings()
my_settings_c.save() # if it didn't exist before, save required
settings = g.findNodeAnywhere(my_settings_c, "@settings")
c2 = g.app.loadManager.openSettingsFile(path)
if not c2:
return "" # Fix 434.
found, maxdepth, maxp = g.recursiveUNLFind(unl, c2)
if found:
if trace:
g.trace("FOUND", unl)
dest = maxp.get_UNL()
else:
if trace:
g.trace("CREATING", unl)
nd = settings.insertAsLastChild()
dest = nd.get_UNL()
self.copy_recursively(maxp, nd)
my_settings_c.redraw()
shortcutsDict, settingsDict = g.app.loadManager.createSettingsDicts(
my_settings_c, False
)
self.c.config.settingsDict.update(settingsDict)
my_settings_c.config.settingsDict.update(settingsDict)
if trace:
g.trace("-->".join([dest] + tail))
return "-->".join([dest] + tail)
|
def copy_to_my_settings(self, unl, which):
"""copy_to_my_settings - copy setting from leoSettings.leo
:param str unl: Leo UNL to copy from
:param int which: 1-3, leaf, leaf's parent, leaf's grandparent
:return: unl of leaf copy in myLeoSettings.leo
:rtype: str
"""
trace = False and not g.unitTesting
if trace:
g.es(unl)
path, unl = unl.split("#", 1)
# Undo the replacements made in p.getUNL.
path = path.replace("file://", "")
unl = unl.replace("%20", " ").split("-->")
tail = []
if which > 1: # copying parent or grandparent but select leaf later
tail = unl[-(which - 1) :]
unl = unl[: len(unl) + 1 - which]
my_settings_c = self.c.openMyLeoSettings()
my_settings_c.save() # if it didn't exist before, save required
settings = g.findNodeAnywhere(my_settings_c, "@settings")
c2 = g.app.loadManager.openSettingsFile(path)
found, maxdepth, maxp = g.recursiveUNLFind(unl, c2)
if found:
if trace:
g.trace("FOUND", unl)
dest = maxp.get_UNL()
else:
if trace:
g.trace("CREATING", unl)
nd = settings.insertAsLastChild()
dest = nd.get_UNL()
self.copy_recursively(maxp, nd)
my_settings_c.redraw()
shortcutsDict, settingsDict = g.app.loadManager.createSettingsDicts(
my_settings_c, False
)
self.c.config.settingsDict.update(settingsDict)
my_settings_c.config.settingsDict.update(settingsDict)
if trace:
g.trace("-->".join([dest] + tail))
return "-->".join([dest] + tail)
|
https://github.com/leo-editor/leo-editor/issues/434
|
$ python launchLeo.py
setting leoID from os.getenv('USER'): '<user>'
reading settings in /Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
reading settings in /Users/<user>/.leo/myLeoSettings.leo
Using default leo file name:
/Users/<user>/.leo/workbook.leo
** isPython3: True
Leo 5.4, build 20170301100728, Wed Mar 1 10:07:28 CST 2017
Git repo info: branch = master, commit = 8f01f57131ae
Python 3.5.3, PyQt version 5.6.2
darwin
reading settings in /Users/<user>/build-dirs/leo-editor/leo/doc/CheatSheet.leo
wrote recent file: /Users/<user>/.leo/.leoRecentFiles.txt
reading settings in /Users/<user>/.leo/myLeoSettings.leo
read only: unl:///Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
error parsing unl:///Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
Traceback (most recent call last):
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 1243, in parse_leo_file
s = str(s, encoding='utf-8')
TypeError: coercing to str: need a bytes-like object, NoneType found
exception executing command
Traceback (most recent call last):
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoCommands.py", line 5501, in doCommand
val = command(event)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2149, in f
self.find_setting(setting)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2112, in find_setting
unl = self.copy_to_my_settings(unl, which=2)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2068, in copy_to_my_settings
c2 = g.app.loadManager.openSettingsFile(path)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoApp.py", line 1903, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 833, in openLeoFile
silent=silent,
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 698, in getLeoFile
theFile.close()
AttributeError: 'NoneType' object has no attribute 'close'
|
TypeError
|
def parse_leo_file(self, theFile, inputFileName, silent, inClipboard, s=None):
c = self.c
# Fix #434: Potential bug in settings.
if not theFile and not s:
return None
try:
if g.isPython3:
if theFile:
# Use the open binary file, opened by the caller.
s = theFile.read() # isinstance(s, bytes)
s = self.cleanSaxInputString(s)
theFile = BytesIO(s)
else:
s = str(s, encoding="utf-8")
s = self.cleanSaxInputString(s)
theFile = StringIO(s)
else:
if theFile:
s = theFile.read()
s = self.cleanSaxInputString(s)
theFile = cStringIO.StringIO(s)
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_external_ges, 1)
# Include external general entities, esp. xml-stylesheet lines.
if 0: # Expat does not read external features.
parser.setFeature(xml.sax.handler.feature_external_pes, 1)
# Include all external parameter entities
# Hopefully the parser can figure out the encoding from the <?xml> element.
# It's very hard to do anything meaningful wih an exception.
handler = SaxContentHandler(c, inputFileName, silent, inClipboard)
parser.setContentHandler(handler)
parser.parse(theFile) # expat does not support parseString
# g.trace('parsing done')
sax_node = handler.getRootNode()
except Exception:
g.error("error parsing", inputFileName)
g.es_exception()
sax_node = None
return sax_node
|
def parse_leo_file(self, theFile, inputFileName, silent, inClipboard, s=None):
c = self.c
try:
if g.isPython3:
if theFile:
# Use the open binary file, opened by the caller.
s = theFile.read() # isinstance(s, bytes)
s = self.cleanSaxInputString(s)
theFile = BytesIO(s)
else:
s = str(s, encoding="utf-8")
s = self.cleanSaxInputString(s)
theFile = StringIO(s)
else:
if theFile:
s = theFile.read()
s = self.cleanSaxInputString(s)
theFile = cStringIO.StringIO(s)
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_external_ges, 1)
# Include external general entities, esp. xml-stylesheet lines.
if 0: # Expat does not read external features.
parser.setFeature(xml.sax.handler.feature_external_pes, 1)
# Include all external parameter entities
# Hopefully the parser can figure out the encoding from the <?xml> element.
# It's very hard to do anything meaningful wih an exception.
handler = SaxContentHandler(c, inputFileName, silent, inClipboard)
parser.setContentHandler(handler)
parser.parse(theFile) # expat does not support parseString
# g.trace('parsing done')
sax_node = handler.getRootNode()
except Exception:
g.error("error parsing", inputFileName)
g.es_exception()
sax_node = None
return sax_node
|
https://github.com/leo-editor/leo-editor/issues/434
|
$ python launchLeo.py
setting leoID from os.getenv('USER'): '<user>'
reading settings in /Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
reading settings in /Users/<user>/.leo/myLeoSettings.leo
Using default leo file name:
/Users/<user>/.leo/workbook.leo
** isPython3: True
Leo 5.4, build 20170301100728, Wed Mar 1 10:07:28 CST 2017
Git repo info: branch = master, commit = 8f01f57131ae
Python 3.5.3, PyQt version 5.6.2
darwin
reading settings in /Users/<user>/build-dirs/leo-editor/leo/doc/CheatSheet.leo
wrote recent file: /Users/<user>/.leo/.leoRecentFiles.txt
reading settings in /Users/<user>/.leo/myLeoSettings.leo
read only: unl:///Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
error parsing unl:///Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
Traceback (most recent call last):
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 1243, in parse_leo_file
s = str(s, encoding='utf-8')
TypeError: coercing to str: need a bytes-like object, NoneType found
exception executing command
Traceback (most recent call last):
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoCommands.py", line 5501, in doCommand
val = command(event)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2149, in f
self.find_setting(setting)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2112, in find_setting
unl = self.copy_to_my_settings(unl, which=2)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2068, in copy_to_my_settings
c2 = g.app.loadManager.openSettingsFile(path)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoApp.py", line 1903, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 833, in openLeoFile
silent=silent,
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 698, in getLeoFile
theFile.close()
AttributeError: 'NoneType' object has no attribute 'close'
|
TypeError
|
def readSaxFile(self, theFile, fileName, silent, inClipboard, reassignIndices, s=None):
"""Read the entire .leo file using the sax parser."""
dump = False and not g.unitTesting
fc = self
c = fc.c
# Pass one: create the intermediate nodes.
saxRoot = fc.parse_leo_file(
theFile, fileName, silent=silent, inClipboard=inClipboard, s=s
)
# Pass two: create the tree of vnodes from the intermediate nodes.
if saxRoot:
if dump:
fc.dumpSaxTree(saxRoot, dummy=True)
parent_v = c.hiddenRootNode
children = fc.createSaxChildren(saxRoot, parent_v)
assert c.hiddenRootNode.children == children
v = children and children[0] or None
return v
else:
return None
|
def readSaxFile(self, theFile, fileName, silent, inClipboard, reassignIndices, s=None):
"""Read the entire .leo file using the sax parser."""
dump = False and not g.unitTesting
fc = self
c = fc.c
# Pass one: create the intermediate nodes.
saxRoot = fc.parse_leo_file(
theFile, fileName, silent=silent, inClipboard=inClipboard, s=s
)
if dump:
fc.dumpSaxTree(saxRoot, dummy=True)
# Pass two: create the tree of vnodes from the intermediate nodes.
if saxRoot:
parent_v = c.hiddenRootNode
children = fc.createSaxChildren(saxRoot, parent_v)
assert c.hiddenRootNode.children == children
v = children and children[0] or None
return v
else:
return None
|
https://github.com/leo-editor/leo-editor/issues/434
|
$ python launchLeo.py
setting leoID from os.getenv('USER'): '<user>'
reading settings in /Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
reading settings in /Users/<user>/.leo/myLeoSettings.leo
Using default leo file name:
/Users/<user>/.leo/workbook.leo
** isPython3: True
Leo 5.4, build 20170301100728, Wed Mar 1 10:07:28 CST 2017
Git repo info: branch = master, commit = 8f01f57131ae
Python 3.5.3, PyQt version 5.6.2
darwin
reading settings in /Users/<user>/build-dirs/leo-editor/leo/doc/CheatSheet.leo
wrote recent file: /Users/<user>/.leo/.leoRecentFiles.txt
reading settings in /Users/<user>/.leo/myLeoSettings.leo
read only: unl:///Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
error parsing unl:///Users/<user>/build-dirs/leo-editor/leo/config/leoSettings.leo
Traceback (most recent call last):
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 1243, in parse_leo_file
s = str(s, encoding='utf-8')
TypeError: coercing to str: need a bytes-like object, NoneType found
exception executing command
Traceback (most recent call last):
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoCommands.py", line 5501, in doCommand
val = command(event)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2149, in f
self.find_setting(setting)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2112, in find_setting
unl = self.copy_to_my_settings(unl, which=2)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoConfig.py", line 2068, in copy_to_my_settings
c2 = g.app.loadManager.openSettingsFile(path)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoApp.py", line 1903, in openSettingsFile
readAtFileNodesFlag=False, silent=True)
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 833, in openLeoFile
silent=silent,
File "/Users/<user>/build-dirs/leo-editor/leo/core/leoFileCommands.py", line 698, in getLeoFile
theFile.close()
AttributeError: 'NoneType' object has no attribute 'close'
|
TypeError
|
def report_record_done(self, count, err_msg=""):
"""
Report the number of records in the latest processed batch,
so TaskDataService knows if some pending tasks are finished
and report_task_result to the master.
Return True if there are some finished tasks, False otherwise.
"""
self._reported_record_count += count
if err_msg:
self._failed_record_count += count
# TODO(qijun) This is a workaround for #1829
if not self._pending_tasks:
return False
task = self._pending_tasks[0]
total_record_num = task.end - task.start
if self._reported_record_count >= total_record_num:
if err_msg:
self._log_fail_records(task, err_msg)
# Keep popping tasks until the reported record count is less
# than the size of the current data since `batch_size` may be
# larger than `task.end - task.start`
with self._lock:
while self._pending_tasks and self._reported_record_count >= (
self._pending_tasks[0].end - self._pending_tasks[0].start
):
task = self._pending_tasks[0]
self._reported_record_count -= task.end - task.start
self._pending_tasks.popleft()
self._do_report_task(task, err_msg)
self._failed_record_count = 0
if self._pending_tasks:
self._current_task = self._pending_tasks[0]
return True
return False
|
def report_record_done(self, count, err_msg=""):
"""
Report the number of records in the latest processed batch,
so TaskDataService knows if some pending tasks are finished
and report_task_result to the master.
Return True if there are some finished tasks, False otherwise.
"""
self._reported_record_count += count
if err_msg:
self._failed_record_count += count
task = self._pending_tasks[0]
total_record_num = task.end - task.start
if self._reported_record_count >= total_record_num:
if err_msg:
self._log_fail_records(task, err_msg)
# Keep popping tasks until the reported record count is less
# than the size of the current data since `batch_size` may be
# larger than `task.end - task.start`
with self._lock:
while self._pending_tasks and self._reported_record_count >= (
self._pending_tasks[0].end - self._pending_tasks[0].start
):
task = self._pending_tasks[0]
self._reported_record_count -= task.end - task.start
self._pending_tasks.popleft()
self._do_report_task(task, err_msg)
self._failed_record_count = 0
if self._pending_tasks:
self._current_task = self._pending_tasks[0]
return True
return False
|
https://github.com/sql-machine-learning/elasticdl/issues/1829
|
2020-03-12 22:03:32.300671: W tensorflow/core/kernels/data/generator_dataset_op.cc:103] Error occurred when finalizing GeneratorDataset iterator: Cancelled: Operation was cancelled
Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/elasticdl/python/worker/main.py", line 44, in <module>
main()
File "/elasticdl/python/worker/main.py", line 40, in main
worker.run()
File "/elasticdl/python/worker/worker.py", line 1144, in run
self._train_and_evaluate()
File "/elasticdl/python/worker/worker.py", line 1074, in _train_and_evaluate
self._minibatch_size, err_msg
File "/elasticdl/python/worker/task_data_service.py", line 86, in report_record_done
task = self._pending_tasks[0]
IndexError: deque index out of range
|
IndexError
|
def __init__(
self,
model_file,
channel=None,
max_retrain_num=DEFAULT_MAX_MINIBATCH_RETRAIN_NUM,
codec_type=None,
):
"""
Arguments:
model_module: A module to define the model
channel: grpc channel
max_retrain_num: max number of a minibatch retrain as its gradients are not accepted by master
"""
model_module = load_user_model(model_file)
self._model = model_module.model
self._feature_columns = model_module.feature_columns()
build_model(self._model, self._feature_columns)
self._input_fn = model_module.input_fn
self._opt_fn = model_module.optimizer
self._loss = model_module.loss
all_columns = self._feature_columns + model_module.label_columns()
if codec_type == "tf_example":
self._codec = TFExampleCodec(all_columns)
elif codec_type == "bytes":
self._codec = BytesCodec(all_columns)
else:
raise ValueError("invalid codec_type: " + codec_type)
if channel is None:
self._stub = None
else:
self._stub = master_pb2_grpc.MasterStub(channel)
self._max_retrain_num = max_retrain_num
self._model_version = -1
self._codec_type = codec_type
|
def __init__(
self,
model_file,
channel=None,
max_retrain_num=DEFAULT_MAX_MINIBATCH_RETRAIN_NUM,
codec_type=None,
):
"""
Arguments:
model_module: A module to define the model
channel: grpc channel
max_retrain_num: max number of a minibatch retrain as its gradients are not accepted by master
"""
model_module = load_user_model(model_file)
self._model = model_module.model
self._feature_columns = model_module.feature_columns()
self._all_columns = self._feature_columns + model_module.label_columns()
build_model(self._model, self._feature_columns)
self._input_fn = model_module.input_fn
self._opt_fn = model_module.optimizer
self._loss = model_module.loss
if channel is None:
self._stub = None
else:
self._stub = master_pb2_grpc.MasterStub(channel)
self._max_retrain_num = max_retrain_num
self._model_version = -1
self._codec_type = codec_type
|
https://github.com/sql-machine-learning/elasticdl/issues/396
|
python -m unittest elasticdl/worker/*_test.py
/usr/local/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
2019-05-21 13:57:07.262725: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
WARNING:tensorflow:From /usr/local/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py:642: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
must be str, not NoneType
FLoss is 3.090042
Loss is 1.4608976
Loss is 0.913306
Loss is 0.5969497
Loss is 0.66515267
Loss is 0.3935135
Loss is 0.37774342
Loss is 0.289928
.
======================================================================
FAIL: test_distributed_train (elasticdl.worker.worker_test.WorkerTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/l.zou/git/elasticdl/elasticdl/worker/worker_test.py", line 96, in test_distributed_train
self.assertTrue(res)
AssertionError: False is not true
----------------------------------------------------------------------
Ran 2 tests in 0.165s
|
AssertionError
|
def distributed_train(self):
"""
Distributed training.
"""
while True:
task = self.get_task()
if not task.shard_file_name:
# No more task
break
batch_size = task.minibatch_size
err_msg = ""
try:
with recordio.File(
task.shard_file_name, "r", decoder=self._codec.decode
) as rdio_r:
reader = rdio_r.get_reader(task.start, task.end)
min_model_version = task.model_version
while True:
record_buf = list(itertools.islice(reader, 0, batch_size))
if not record_buf:
break
for _ in range(self._max_retrain_num):
# TODO: optimize the logic to avoid unnecessary get_model call.
self.get_model(max(self._model_version, min_model_version))
batch_input_data, batch_label = self._input_fn(record_buf)
with tf.GradientTape() as tape:
inputs = []
for f_col in self._feature_columns:
inputs.append(batch_input_data[f_col.key])
if len(inputs) == 1:
inputs = inputs[0]
outputs = self._model.call(inputs, training=True)
loss = self._loss(outputs, batch_label.flatten())
# TODO: Add regularization loss if any,
# which should be divided by the number of contributing workers.
grads = tape.gradient(loss, self._model.trainable_variables)
print("Loss is ", loss.numpy())
accepted, min_model_version = self.report_gradient(grads)
if accepted:
break
else:
# Worker got stuck, fail the task.
# TODO: stop the worker if it fails to make any progress for some time.
raise RuntimeError("Worker got stuck")
except Exception as ex:
err_msg = str(ex)
traceback.print_exc()
self.report_task_result(task.task_id, err_msg)
|
def distributed_train(self):
"""
Distributed training.
"""
if self._codec_type == "tf_example":
codec = TFExampleCodec(self._all_columns)
elif self._codec_type == "bytes":
codec = BytesCodec(self._all_columns)
else:
raise ValueError("invalid codec_type: " + self._codec_type)
while True:
task = self.get_task()
if not task.shard_file_name:
# No more task
break
batch_size = task.minibatch_size
err_msg = ""
try:
with recordio.File(
task.shard_file_name, "r", decoder=codec.decode
) as rdio_r:
reader = rdio_r.get_reader(task.start, task.end)
min_model_version = task.model_version
while True:
record_buf = list(itertools.islice(reader, 0, batch_size))
if not record_buf:
break
for _ in range(self._max_retrain_num):
# TODO: optimize the logic to avoid unnecessary get_model call.
self.get_model(max(self._model_version, min_model_version))
batch_input_data, batch_label = self._input_fn(record_buf)
with tf.GradientTape() as tape:
inputs = []
for f_col in self._feature_columns:
inputs.append(batch_input_data[f_col.key])
if len(inputs) == 1:
inputs = inputs[0]
outputs = self._model.call(inputs, training=True)
loss = self._loss(outputs, batch_label.flatten())
# TODO: Add regularization loss if any,
# which should be divided by the number of contributing workers.
grads = tape.gradient(loss, self._model.trainable_variables)
print("Loss is ", loss.numpy())
accepted, min_model_version = self.report_gradient(grads)
if accepted:
break
else:
# Worker got stuck, fail the task.
# TODO: stop the worker if it fails to make any progress for some time.
raise RuntimeError("Worker got stuck")
except Exception as ex:
err_msg = str(ex)
traceback.print_exc()
self.report_task_result(task.task_id, err_msg)
|
https://github.com/sql-machine-learning/elasticdl/issues/396
|
python -m unittest elasticdl/worker/*_test.py
/usr/local/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
2019-05-21 13:57:07.262725: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
WARNING:tensorflow:From /usr/local/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py:642: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
must be str, not NoneType
FLoss is 3.090042
Loss is 1.4608976
Loss is 0.913306
Loss is 0.5969497
Loss is 0.66515267
Loss is 0.3935135
Loss is 0.37774342
Loss is 0.289928
.
======================================================================
FAIL: test_distributed_train (elasticdl.worker.worker_test.WorkerTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/l.zou/git/elasticdl/elasticdl/worker/worker_test.py", line 96, in test_distributed_train
self.assertTrue(res)
AssertionError: False is not true
----------------------------------------------------------------------
Ran 2 tests in 0.165s
|
AssertionError
|
def local_train(self, file_list, batch_size, epoch=1, kwargs=None):
"""
Local training for local testing. Must in eager mode.
Argments:
batch_size: batch size in training
epoch: the number of epoch in training
kwargs: contains a dict of parameters used in training
"""
optimizer = self._opt_fn()
for _ in range(epoch):
for f in file_list:
with recordio.File(f, "r", decoder=self._codec.decode) as rdio_r:
reader = rdio_r.get_reader(0, rdio_r.count())
while True:
record_buf = list(itertools.islice(reader, 0, batch_size))
if not record_buf:
break
data, labels = self._input_fn(record_buf)
with tf.GradientTape() as tape:
inputs = []
for f_col in self._feature_columns:
inputs.append(data[f_col.key])
if len(inputs) == 1:
inputs = inputs[0]
outputs = self._model.call(inputs, training=True)
loss = self._loss(outputs, labels)
# Add regularization loss if any.
# Note: for distributed training, the regularization loss should
# be divided by the number of contributing workers, which
# might be difficult for elasticdl.
if self._model.losses:
loss += math_ops.add_n(self._model.losses)
grads = tape.gradient(loss, self._model.trainable_variables)
optimizer.apply_gradients(
zip(grads, self._model.trainable_variables)
)
print("Loss is ", loss.numpy())
|
def local_train(self, file_list, batch_size, epoch=1, kwargs=None):
"""
Local training for local testing. Must in eager mode.
Argments:
batch_size: batch size in training
epoch: the number of epoch in training
kwargs: contains a dict of parameters used in training
"""
optimizer = self._opt_fn()
for _ in range(epoch):
for f in file_list:
with recordio.File(f, "r") as rdio_r:
reader = rdio_r.get_reader(0, rdio_r.count())
while True:
record_buf = list(itertools.islice(reader, 0, batch_size))
if not record_buf:
break
data, labels = self._input_fn(record_buf)
with tf.GradientTape() as tape:
inputs = []
for f_col in self._feature_columns:
inputs.append(data[f_col.key])
if len(inputs) == 1:
inputs = inputs[0]
outputs = self._model.call(inputs, training=True)
loss = self._loss(outputs, labels)
# Add regularization loss if any.
# Note: for distributed training, the regularization loss should
# be divided by the number of contributing workers, which
# might be difficult for elasticdl.
if self._model.losses:
loss += math_ops.add_n(self._model.losses)
grads = tape.gradient(loss, self._model.trainable_variables)
optimizer.apply_gradients(
zip(grads, self._model.trainable_variables)
)
print("Loss is ", loss.numpy())
|
https://github.com/sql-machine-learning/elasticdl/issues/396
|
python -m unittest elasticdl/worker/*_test.py
/usr/local/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
2019-05-21 13:57:07.262725: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
WARNING:tensorflow:From /usr/local/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py:642: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
must be str, not NoneType
FLoss is 3.090042
Loss is 1.4608976
Loss is 0.913306
Loss is 0.5969497
Loss is 0.66515267
Loss is 0.3935135
Loss is 0.37774342
Loss is 0.289928
.
======================================================================
FAIL: test_distributed_train (elasticdl.worker.worker_test.WorkerTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/l.zou/git/elasticdl/elasticdl/worker/worker_test.py", line 96, in test_distributed_train
self.assertTrue(res)
AssertionError: False is not true
----------------------------------------------------------------------
Ran 2 tests in 0.165s
|
AssertionError
|
def _gen_master_def(image_name, model_file, argv, timestamp):
master_yaml = """
apiVersion: v1
kind: Pod
metadata:
name: "elasticdl-master-{timestamp}"
labels:
purpose: test-command
spec:
containers:
- name: "elasticdl-master-{timestamp}"
image: "{image_name}"
command: ["python"]
args: [
"-m", "elasticdl.master.main",
"--worker_image", "{image_name}",
"--model_file", "{m_file}"
]
imagePullPolicy: IfNotPresent
env:
- name: MY_POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
restartPolicy: Never
""".format(
m_file=_m_file_in_docker(model_file), image_name=image_name, timestamp=timestamp
)
master_def = yaml.safe_load(master_yaml)
# Build master arguments
master_def["spec"]["containers"][0]["args"].extend(argv)
return master_def
|
def _gen_master_def(image_name, model_file, argv, timestamp):
master_yaml = """
apiVersion: v1
kind: Pod
metadata:
name: elasticdl-master-{timestamp}
labels:
purpose: test-command
spec:
containers:
- name: elasticdl-master-{timestamp}
image: {image_name}
command: ["python"]
args: [
"-m", "elasticdl.master.main",
"--worker_image", {image_name},
"--model_file", "{m_file}"
]
imagePullPolicy: IfNotPresent
env:
- name: MY_POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
restartPolicy: Never
""".format(
m_file=_m_file_in_docker(model_file), image_name=image_name, timestamp=timestamp
)
master_def = yaml.safe_load(master_yaml)
# Build master arguments
master_def["spec"]["containers"][0]["args"].extend(argv)
return master_def
|
https://github.com/sql-machine-learning/elasticdl/issues/363
|
Traceback (most recent call last):
File "elasticdl/client/client.py", line 96, in <module>
main()
File "elasticdl/client/client.py", line 92, in main
_submit(image_name, args.model_file, argv, timestamp)
File "elasticdl/client/client.py", line 74, in _submit
master_def = _gen_master_def(image_name, model_file, argv, timestamp)
File "elasticdl/client/client.py", line 67, in _gen_master_def
master_def = yaml.safe_load(master_yaml)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/__init__.py", line 94, in safe_load
return load(stream, SafeLoader)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/__init__.py", line 72, in load
return loader.get_single_data()
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/constructor.py", line 35, in get_single_data
node = self.get_single_node()
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 36, in get_single_node
document = self.compose_document()
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 55, in compose_document
node = self.compose_node(None, None)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 84, in compose_node
node = self.compose_mapping_node(anchor)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 133, in compose_mapping_node
item_value = self.compose_node(node, item_key)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 84, in compose_node
node = self.compose_mapping_node(anchor)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 133, in compose_mapping_node
item_value = self.compose_node(node, item_key)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 82, in compose_node
node = self.compose_sequence_node(anchor)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 111, in compose_sequence_node
node.value.append(self.compose_node(node, index))
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 84, in compose_node
node = self.compose_mapping_node(anchor)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 133, in compose_mapping_node
item_value = self.compose_node(node, item_key)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 82, in compose_node
node = self.compose_sequence_node(anchor)
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/composer.py", line 110, in compose_sequence_node
while not self.check_event(SequenceEndEvent):
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/parser.py", line 98, in check_event
self.current_event = self.state()
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/parser.py", line 486, in parse_flow_sequence_entry
if self.check_token(KeyToken):
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/scanner.py", line 116, in check_token
self.fetch_more_tokens()
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/scanner.py", line 252, in fetch_more_tokens
return self.fetch_plain()
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/scanner.py", line 676, in fetch_plain
self.tokens.append(self.scan_plain())
File "/usr/local/anaconda3/lib/python3.6/site-packages/yaml/scanner.py", line 1299, in scan_plain
"Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.")
yaml.scanner.ScannerError: while scanning a plain scalar
in "<unicode string>", line 15, column 27:
"--worker_image", elasticdl:dev_1558332476444,
^
found unexpected ':'
in "<unicode string>", line 15, column 36:
"--worker_image", elasticdl:dev_1558332476444,
^
|
yaml.scanner.ScannerError
|
def _parameter_indexes(self, param: str) -> Tuple[int, ...]:
"""Obtain indexes for values associated with `param`.
A draw from the sampler is a flat vector of values. A multi-dimensional
variable will be stored in this vector in column-major order. This function
identifies the indices which allow us to extract values associated with a
parameter.
Parameters
----------
param : Parameter of interest.
Returns
-------
Indexes associated with parameter.
Note
----
This function assumes that parameters appearing in the program code follow
the sample and sampler parameters (e.g., ``lp__``, ``stepsize__``).
"""
# if `param` is a scalar, it will match one of the constrained names or it will match a
# sample param name (e.g., `lp__`) or a sampler param name (e.g., `stepsize__`)
if param in self.sample_and_sampler_param_names:
return (self.sample_and_sampler_param_names.index(param),)
sample_and_sampler_params_offset = len(self.sample_and_sampler_param_names)
if param in self.constrained_param_names:
return (
sample_and_sampler_params_offset
+ self.constrained_param_names.index(param),
)
def calculate_starts(dims: Tuple[Tuple[int, ...]]) -> Tuple[int, ...]:
"""Calculate starting indexes given dims."""
s = [cast(int, np.prod(d)) for d in dims]
starts = np.cumsum([0] + s)[: len(dims)]
return tuple(int(i) for i in starts)
starts = tuple(
sample_and_sampler_params_offset + i for i in calculate_starts(self.dims)
)
names_index = self.param_names.index(param)
flat_param_count = cast(int, np.prod(self.dims[names_index]))
return tuple(starts[names_index] + offset for offset in range(flat_param_count))
|
def _parameter_indexes(self, param: str) -> Tuple[int, ...]:
"""Obtain indexes for values associated with `param`.
A draw from the sampler is a flat vector of values. A multi-dimensional
variable will be stored in this vector in column-major order. This function
identifies the indices which allow us to extract values associated with a
parameter.
Parameters
----------
param : Parameter of interest.
Returns
-------
Indexes associated with parameter.
Note
----
This function assumes that parameters appearing in the program code follow
the sample and sampler parameters (e.g., ``lp__``, ``stepsize__``).
"""
# if `param` is a scalar, it will match one of the constrained names or it will match a
# sample param name (e.g., `lp__`) or a sampler param name (e.g., `stepsize__`)
if param in self.sample_and_sampler_param_names:
return (self.sample_and_sampler_param_names.index(param),)
sample_and_sampler_params_offset = len(self.sample_and_sampler_param_names)
if param in self.constrained_param_names:
return (
sample_and_sampler_params_offset
+ self.constrained_param_names.index(param),
)
def calculate_starts(dims: Tuple[Tuple[int, ...]]) -> Tuple[int, ...]:
"""Calculate starting indexes given dims."""
s = [np.prod(d) for d in dims]
starts = np.cumsum([0] + s)[: len(dims)]
return tuple(int(i) for i in starts)
starts = tuple(
sample_and_sampler_params_offset + i for i in calculate_starts(self.dims)
)
names_index = self.param_names.index(param)
flat_param_count = np.prod(self.dims[names_index])
return tuple(starts[names_index] + offset for offset in range(flat_param_count))
|
https://github.com/stan-dev/pystan/issues/201
|
Traceback (most recent call last):
File "scripts/pickle_error.py", line 45, in <module>
print(fit2["mu"])
File "<redacted>/lib/python3.7/site-packages/stan/fit.py", line 131, in __getitem__
raise RuntimeError("Still collecting draws for fit.")
RuntimeError: Still collecting draws for fit.
|
RuntimeError
|
def calculate_starts(dims: Tuple[Tuple[int, ...]]) -> Tuple[int, ...]:
"""Calculate starting indexes given dims."""
s = [cast(int, np.prod(d)) for d in dims]
starts = np.cumsum([0] + s)[: len(dims)]
return tuple(int(i) for i in starts)
|
def calculate_starts(dims: Tuple[Tuple[int, ...]]) -> Tuple[int, ...]:
"""Calculate starting indexes given dims."""
s = [np.prod(d) for d in dims]
starts = np.cumsum([0] + s)[: len(dims)]
return tuple(int(i) for i in starts)
|
https://github.com/stan-dev/pystan/issues/201
|
Traceback (most recent call last):
File "scripts/pickle_error.py", line 45, in <module>
print(fit2["mu"])
File "<redacted>/lib/python3.7/site-packages/stan/fit.py", line 131, in __getitem__
raise RuntimeError("Still collecting draws for fit.")
RuntimeError: Still collecting draws for fit.
|
RuntimeError
|
def __init__(
self,
stan_outputs: Tuple[bytes, ...],
num_chains: int,
param_names: Tuple[str, ...],
constrained_param_names: Tuple[str, ...],
dims: Tuple[Tuple[int, ...]],
num_warmup: int,
num_samples: int,
num_thin: int,
save_warmup: bool,
) -> None:
self.stan_outputs = stan_outputs
self.num_chains = num_chains
assert self.num_chains == len(self.stan_outputs)
self.param_names, self.dims, self.constrained_param_names = (
param_names,
dims,
constrained_param_names,
)
self.num_warmup, self.num_samples = num_warmup, num_samples
self.num_thin, self.save_warmup = num_thin, save_warmup
# `self.sample_and_sampler_param_names` collects the sample and sampler param names.
# - "sample params" include `lp__`, `accept_stat__`
# - "sampler params" include `stepsize__`, `treedepth__`, ...
# These names are gathered later in this function by inspecting the output from Stan.
self.sample_and_sampler_param_names: Tuple[str, ...]
num_flat_params = sum(
np.product(dims_ or 1) for dims_ in dims
) # if dims == [] then it is a scalar
assert num_flat_params == len(constrained_param_names)
num_samples_saved = (
self.num_samples + self.num_warmup * self.save_warmup
) // self.num_thin
# self._draws holds all the draws. We cannot allocate it before looking at the draws
# because we do not know how many sampler-specific parameters are present. Later in this
# function we count them and only then allocate the array for `self._draws`.
#
# _draws is an ndarray with shape (num_sample_and_sampler_params + num_flat_params, num_draws, num_chains)
self._draws: np.ndarray
parser = simdjson.Parser()
for chain_index, stan_output in zip(range(self.num_chains), self.stan_outputs):
draw_index = 0
for line in stan_output.splitlines():
try:
msg = parser.parse(line)
except ValueError:
# Occurs when draws contain an nan or infinity. simdjson cannot parse such values.
msg = json.loads(line)
if msg["topic"] == "sample":
# Ignore sample message which is mixed together with proper draws.
if not isinstance(msg["values"], (simdjson.Object, dict)):
continue
# for the first draw: collect sample and sampler parameter names.
if not hasattr(self, "_draws"):
feature_names = cast(Tuple[str, ...], tuple(msg["values"].keys()))
self.sample_and_sampler_param_names = tuple(
name for name in feature_names if name.endswith("__")
)
num_rows = (
len(self.sample_and_sampler_param_names) + num_flat_params
)
# column-major order ("F") aligns with how the draws are stored (in cols).
self._draws = np.empty(
(num_rows, num_samples_saved, num_chains), order="F"
)
# rudimentary check of parameter order (sample & sampler params must be first)
if num_flat_params and feature_names[-1].endswith("__"):
raise RuntimeError(
f"Expected last parameter name to be one declared in program code, found `{feature_names[-1]}`"
)
draw_row = tuple(
msg["values"].values()
) # a "row" of values from a single draw from Stan C++
self._draws[:, draw_index, chain_index] = draw_row
draw_index += 1
assert draw_index == num_samples_saved
assert self.sample_and_sampler_param_names and self._draws.size
self._draws.flags["WRITEABLE"] = False
|
def __init__(
self,
stan_outputs: Tuple[bytes, ...],
num_chains: int,
param_names: Tuple[str, ...],
constrained_param_names: Tuple[str, ...],
dims: Tuple[Tuple[int, ...]],
num_warmup: int,
num_samples: int,
num_thin: int,
save_warmup: bool,
) -> None:
self.stan_outputs = stan_outputs
self.num_chains = num_chains
assert self.num_chains == len(self.stan_outputs)
self.param_names, self.dims, self.constrained_param_names = (
param_names,
dims,
constrained_param_names,
)
self.num_warmup, self.num_samples = num_warmup, num_samples
self.num_thin, self.save_warmup = num_thin, save_warmup
# `self.sample_and_sampler_param_names` collects the sample and sampler param names.
# - "sample params" include `lp__`, `accept_stat__`
# - "sampler params" include `stepsize__`, `treedepth__`, ...
# These names are gathered later in this function by inspecting the output from Stan.
self.sample_and_sampler_param_names: Tuple[str, ...]
num_flat_params = sum(
np.product(dims_ or 1) for dims_ in dims
) # if dims == [] then it is a scalar
assert num_flat_params == len(constrained_param_names)
num_samples_saved = (
self.num_samples + self.num_warmup * self.save_warmup
) // self.num_thin
# self._draws holds all the draws. We cannot allocate it before looking at the draws
# because we do not know how many sampler-specific parameters are present. Later in this
# function we count them and only then allocate the array for `self._draws`.
#
# _draws is an ndarray with shape (num_sample_and_sampler_params + num_flat_params, num_draws, num_chains)
self._draws: np.ndarray
parser = simdjson.Parser()
for chain_index, stan_output in zip(range(self.num_chains), self.stan_outputs):
draw_index = 0
for line in stan_output.splitlines():
try:
msg = parser.parse(line)
except ValueError:
# Occurs when draws contain an nan or infinity. simdjson cannot parse such values.
msg = json.loads(line)
if msg["topic"] == "sample":
# Ignore sample message which is mixed together with proper draws.
if not isinstance(msg["values"], (simdjson.Object, dict)):
continue
# for the first draw: collect sample and sampler parameter names.
if not hasattr(self, "_draws"):
feature_names = cast(Tuple[str, ...], tuple(msg["values"].keys()))
self.sample_and_sampler_param_names = tuple(
name for name in feature_names if name.endswith("__")
)
num_rows = (
len(self.sample_and_sampler_param_names) + num_flat_params
)
# column-major order ("F") aligns with how the draws are stored (in cols).
self._draws = np.empty(
(num_rows, num_samples_saved, num_chains), order="F"
)
# rudimentary check of parameter order (sample & sampler params must be first)
if num_flat_params and feature_names[-1].endswith("__"):
raise RuntimeError(
f"Expected last parameter name to be one declared in program code, found `{feature_names[-1]}`"
)
draw_row = tuple(
msg["values"].values()
) # a "row" of values from a single draw from Stan C++
self._draws[:, draw_index, chain_index] = draw_row
draw_index += 1
assert draw_index == num_samples_saved
# set draws array to read-only, also indicates we are finished
assert self.sample_and_sampler_param_names and self._draws.size
self._draws.flags["WRITEABLE"] = False
|
https://github.com/stan-dev/pystan/issues/201
|
Traceback (most recent call last):
File "scripts/pickle_error.py", line 45, in <module>
print(fit2["mu"])
File "<redacted>/lib/python3.7/site-packages/stan/fit.py", line 131, in __getitem__
raise RuntimeError("Still collecting draws for fit.")
RuntimeError: Still collecting draws for fit.
|
RuntimeError
|
def __contains__(self, key):
return key in self.param_names
|
def __contains__(self, key):
if not self._finished:
raise RuntimeError("Still collecting draws for fit.")
return key in self.param_names
|
https://github.com/stan-dev/pystan/issues/201
|
Traceback (most recent call last):
File "scripts/pickle_error.py", line 45, in <module>
print(fit2["mu"])
File "<redacted>/lib/python3.7/site-packages/stan/fit.py", line 131, in __getitem__
raise RuntimeError("Still collecting draws for fit.")
RuntimeError: Still collecting draws for fit.
|
RuntimeError
|
def __getitem__(self, param):
"""Returns array with shape (stan_dimensions, num_chains * num_samples)"""
assert param.endswith("__") or param in self.param_names, param
param_indexes = self._parameter_indexes(param)
param_dim = (
[]
if param in self.sample_and_sampler_param_names
else self.dims[self.param_names.index(param)]
)
# fmt: off
num_samples_saved = (self.num_samples + self.num_warmup * self.save_warmup) // self.num_thin
assert self._draws.shape == (len(self.sample_and_sampler_param_names) + len(self.constrained_param_names), num_samples_saved, self.num_chains)
# fmt: on
# Stack chains together. Parameter is still stored flat.
view = self._draws[param_indexes, :, :].reshape(len(param_indexes), -1).view()
assert view.shape == (len(param_indexes), num_samples_saved * self.num_chains)
# reshape must yield something with least two dimensions
reshape_args = param_dim + [-1] if param_dim else (1, -1)
# reshape, recover the shape of the stan parameter
return view.reshape(*reshape_args, order="F")
|
def __getitem__(self, param):
"""Returns array with shape (stan_dimensions, num_chains * num_samples)"""
if not self._finished:
raise RuntimeError("Still collecting draws for fit.")
assert param.endswith("__") or param in self.param_names, param
param_indexes = self._parameter_indexes(param)
param_dim = (
[]
if param in self.sample_and_sampler_param_names
else self.dims[self.param_names.index(param)]
)
# fmt: off
num_samples_saved = (self.num_samples + self.num_warmup * self.save_warmup) // self.num_thin
assert self._draws.shape == (len(self.sample_and_sampler_param_names) + len(self.constrained_param_names), num_samples_saved, self.num_chains)
# fmt: on
# Stack chains together. Parameter is still stored flat.
view = self._draws[param_indexes, :, :].reshape(len(param_indexes), -1).view()
assert view.shape == (len(param_indexes), num_samples_saved * self.num_chains)
# reshape must yield something with least two dimensions
reshape_args = param_dim + [-1] if param_dim else (1, -1)
# reshape, recover the shape of the stan parameter
return view.reshape(*reshape_args, order="F")
|
https://github.com/stan-dev/pystan/issues/201
|
Traceback (most recent call last):
File "scripts/pickle_error.py", line 45, in <module>
print(fit2["mu"])
File "<redacted>/lib/python3.7/site-packages/stan/fit.py", line 131, in __getitem__
raise RuntimeError("Still collecting draws for fit.")
RuntimeError: Still collecting draws for fit.
|
RuntimeError
|
def __repr__(self) -> str:
# inspired by xarray
parts = [f"<stan.{type(self).__name__}>"]
def summarize_param(param_name, dims):
return f" {param_name}: {tuple(dims)}"
if self.param_names:
parts.append("Parameters:")
for param_name, dims in zip(self.param_names, self.dims):
parts.append(summarize_param(param_name, dims))
# total draws is num_draws (per-chain) times num_chains
parts.append(f"Draws: {self._draws.shape[-2] * self._draws.shape[-1]}")
return "\n".join(parts)
|
def __repr__(self) -> str:
# inspired by xarray
parts = [f"<stan.{type(self).__name__}>"]
def summarize_param(param_name, dims):
return f" {param_name}: {tuple(dims)}"
if self.param_names:
parts.append("Parameters:")
for param_name, dims in zip(self.param_names, self.dims):
parts.append(summarize_param(param_name, dims))
if self._finished:
# total draws is num_draws (per-chain) times num_chains
parts.append(f"Draws: {self._draws.shape[-2] * self._draws.shape[-1]}")
return "\n".join(parts)
|
https://github.com/stan-dev/pystan/issues/201
|
Traceback (most recent call last):
File "scripts/pickle_error.py", line 45, in <module>
print(fit2["mu"])
File "<redacted>/lib/python3.7/site-packages/stan/fit.py", line 131, in __getitem__
raise RuntimeError("Still collecting draws for fit.")
RuntimeError: Still collecting draws for fit.
|
RuntimeError
|
def plot_rug(self, height, expand_margins, legend, **kws):
for (
sub_vars,
sub_data,
) in self.iter_data(from_comp_data=True):
ax = self._get_axes(sub_vars)
kws.setdefault("linewidth", 1)
if expand_margins:
xmarg, ymarg = ax.margins()
if "x" in self.variables:
ymarg += height * 2
if "y" in self.variables:
xmarg += height * 2
ax.margins(x=xmarg, y=ymarg)
if "hue" in self.variables:
kws.pop("c", None)
kws.pop("color", None)
if "x" in self.variables:
self._plot_single_rug(sub_data, "x", height, ax, kws)
if "y" in self.variables:
self._plot_single_rug(sub_data, "y", height, ax, kws)
# --- Finalize the plot
self._add_axis_labels(ax)
if "hue" in self.variables and legend:
# TODO ideally i'd like the legend artist to look like a rug
legend_artist = partial(mpl.lines.Line2D, [], [])
self._add_legend(
ax,
legend_artist,
False,
False,
None,
1,
{},
{},
)
|
def plot_rug(self, height, expand_margins, legend, **kws):
for (
sub_vars,
sub_data,
) in self.iter_data():
ax = self._get_axes(sub_vars)
kws.setdefault("linewidth", 1)
if expand_margins:
xmarg, ymarg = ax.margins()
if "x" in self.variables:
ymarg += height * 2
if "y" in self.variables:
xmarg += height * 2
ax.margins(x=xmarg, y=ymarg)
if "hue" in self.variables:
kws.pop("c", None)
kws.pop("color", None)
if "x" in self.variables:
self._plot_single_rug(sub_data, "x", height, ax, kws)
if "y" in self.variables:
self._plot_single_rug(sub_data, "y", height, ax, kws)
# --- Finalize the plot
self._add_axis_labels(ax)
if "hue" in self.variables and legend:
# TODO ideally i'd like the legend artist to look like a rug
legend_artist = partial(mpl.lines.Line2D, [], [])
self._add_legend(
ax,
legend_artist,
False,
False,
None,
1,
{},
{},
)
|
https://github.com/mwaskom/seaborn/issues/2451
|
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-0cb72350e3e6> in <module>
1 #sns.rugplot()
----> 2 sns.rugplot(x=np.arange("2015-01-01", "2020-01-01", dtype="datetime64[m]"))
~/code/seaborn/seaborn/_decorators.py in inner_f(*args, **kwargs)
44 )
45 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46 return f(**kwargs)
47 return inner_f
48
~/code/seaborn/seaborn/distributions.py in rugplot(x, height, axis, ax, data, y, hue, palette, hue_order, hue_norm, expand_margins, legend, a, **kwargs)
2048 return ax
2049
-> 2050 p.plot_rug(height, expand_margins, legend, **kwargs)
2051
2052 return ax
~/code/seaborn/seaborn/distributions.py in plot_rug(self, height, expand_margins, legend, **kws)
1266
1267 if "x" in self.variables:
-> 1268 self._plot_single_rug(sub_data, "x", height, ax, kws)
1269 if "y" in self.variables:
1270 self._plot_single_rug(sub_data, "y", height, ax, kws)
~/code/seaborn/seaborn/distributions.py in _plot_single_rug(self, sub_data, var, height, ax, kws)
1294
1295 trans = tx.blended_transform_factory(ax.transData, ax.transAxes)
-> 1296 xy_pairs = np.column_stack([
1297 np.repeat(vector, 2), np.tile([0, height], n)
1298 ])
<__array_function__ internals> in column_stack(*args, **kwargs)
~/miniconda3/envs/seaborn-py38-latest/lib/python3.8/site-packages/numpy/lib/shape_base.py in column_stack(tup)
654 arr = array(arr, copy=False, subok=True, ndmin=2).T
655 arrays.append(arr)
--> 656 return _nx.concatenate(arrays, 1)
657
658
<__array_function__ internals> in concatenate(*args, **kwargs)
TypeError: invalid type promotion
|
TypeError
|
def __init__(
self,
data,
*,
hue=None,
hue_order=None,
palette=None,
hue_kws=None,
vars=None,
x_vars=None,
y_vars=None,
corner=False,
diag_sharey=True,
height=2.5,
aspect=1,
layout_pad=0.5,
despine=True,
dropna=False,
size=None,
):
"""Initialize the plot figure and PairGrid object.
Parameters
----------
data : DataFrame
Tidy (long-form) dataframe where each column is a variable and
each row is an observation.
hue : string (variable name)
Variable in ``data`` to map plot aspects to different colors. This
variable will be excluded from the default x and y variables.
hue_order : list of strings
Order for the levels of the hue variable in the palette
palette : dict or seaborn color palette
Set of colors for mapping the ``hue`` variable. If a dict, keys
should be values in the ``hue`` variable.
hue_kws : dictionary of param -> list of values mapping
Other keyword arguments to insert into the plotting call to let
other plot attributes vary across levels of the hue variable (e.g.
the markers in a scatterplot).
vars : list of variable names
Variables within ``data`` to use, otherwise use every column with
a numeric datatype.
{x, y}_vars : lists of variable names
Variables within ``data`` to use separately for the rows and
columns of the figure; i.e. to make a non-square plot.
corner : bool
If True, don't add axes to the upper (off-diagonal) triangle of the
grid, making this a "corner" plot.
height : scalar
Height (in inches) of each facet.
aspect : scalar
Aspect * height gives the width (in inches) of each facet.
layout_pad : scalar
Padding between axes; passed to ``fig.tight_layout``.
despine : boolean
Remove the top and right spines from the plots.
dropna : boolean
Drop missing values from the data before plotting.
See Also
--------
pairplot : Easily drawing common uses of :class:`PairGrid`.
FacetGrid : Subplot grid for plotting conditional relationships.
Examples
--------
.. include:: ../docstrings/PairGrid.rst
"""
super(PairGrid, self).__init__()
# Handle deprecations
if size is not None:
height = size
msg = (
"The `size` parameter has been renamed to `height`; "
"please update your code."
)
warnings.warn(UserWarning(msg))
# Sort out the variables that define the grid
numeric_cols = self._find_numeric_cols(data)
if hue in numeric_cols:
numeric_cols.remove(hue)
if vars is not None:
x_vars = list(vars)
y_vars = list(vars)
if x_vars is None:
x_vars = numeric_cols
if y_vars is None:
y_vars = numeric_cols
if np.isscalar(x_vars):
x_vars = [x_vars]
if np.isscalar(y_vars):
y_vars = [y_vars]
self.x_vars = x_vars = list(x_vars)
self.y_vars = y_vars = list(y_vars)
self.square_grid = self.x_vars == self.y_vars
if not x_vars:
raise ValueError("No variables found for grid columns.")
if not y_vars:
raise ValueError("No variables found for grid rows.")
# Create the figure and the array of subplots
figsize = len(x_vars) * height * aspect, len(y_vars) * height
fig, axes = plt.subplots(
len(y_vars),
len(x_vars),
figsize=figsize,
sharex="col",
sharey="row",
squeeze=False,
)
# Possibly remove upper axes to make a corner grid
# Note: setting up the axes is usually the most time-intensive part
# of using the PairGrid. We are foregoing the speed improvement that
# we would get by just not setting up the hidden axes so that we can
# avoid implementing plt.subplots ourselves. But worth thinking about.
self._corner = corner
if corner:
hide_indices = np.triu_indices_from(axes, 1)
for i, j in zip(*hide_indices):
axes[i, j].remove()
axes[i, j] = None
self.fig = fig
self.axes = axes
self.data = data
# Save what we are going to do with the diagonal
self.diag_sharey = diag_sharey
self.diag_vars = None
self.diag_axes = None
self._dropna = dropna
# Label the axes
self._add_axis_labels()
# Sort out the hue variable
self._hue_var = hue
if hue is None:
self.hue_names = hue_order = ["_nolegend_"]
self.hue_vals = pd.Series(["_nolegend_"] * len(data), index=data.index)
else:
# We need hue_order and hue_names because the former is used to control
# the order of drawing and the latter is used to control the order of
# the legend. hue_names can become string-typed while hue_order must
# retain the type of the input data. This is messy but results from
# the fact that PairGrid can implement the hue-mapping logic itself
# (and was originally written exclusively that way) but now can delegate
# to the axes-level functions, while always handling legend creation.
# See GH2307
hue_names = hue_order = categorical_order(data[hue], hue_order)
if dropna:
# Filter NA from the list of unique hue names
hue_names = list(filter(pd.notnull, hue_names))
self.hue_names = hue_names
self.hue_vals = data[hue]
# Additional dict of kwarg -> list of values for mapping the hue var
self.hue_kws = hue_kws if hue_kws is not None else {}
self._orig_palette = palette
self._hue_order = hue_order
self.palette = self._get_palette(data, hue, hue_order, palette)
self._legend_data = {}
# Make the plot look nice
self._tight_layout_rect = [0.01, 0.01, 0.99, 0.99]
self._tight_layout_pad = layout_pad
self._despine = despine
if despine:
utils.despine(fig=fig)
self.tight_layout(pad=layout_pad)
|
def __init__(
self,
data,
*,
hue=None,
hue_order=None,
palette=None,
hue_kws=None,
vars=None,
x_vars=None,
y_vars=None,
corner=False,
diag_sharey=True,
height=2.5,
aspect=1,
layout_pad=0.5,
despine=True,
dropna=False,
size=None,
):
"""Initialize the plot figure and PairGrid object.
Parameters
----------
data : DataFrame
Tidy (long-form) dataframe where each column is a variable and
each row is an observation.
hue : string (variable name)
Variable in ``data`` to map plot aspects to different colors. This
variable will be excluded from the default x and y variables.
hue_order : list of strings
Order for the levels of the hue variable in the palette
palette : dict or seaborn color palette
Set of colors for mapping the ``hue`` variable. If a dict, keys
should be values in the ``hue`` variable.
hue_kws : dictionary of param -> list of values mapping
Other keyword arguments to insert into the plotting call to let
other plot attributes vary across levels of the hue variable (e.g.
the markers in a scatterplot).
vars : list of variable names
Variables within ``data`` to use, otherwise use every column with
a numeric datatype.
{x, y}_vars : lists of variable names
Variables within ``data`` to use separately for the rows and
columns of the figure; i.e. to make a non-square plot.
corner : bool
If True, don't add axes to the upper (off-diagonal) triangle of the
grid, making this a "corner" plot.
height : scalar
Height (in inches) of each facet.
aspect : scalar
Aspect * height gives the width (in inches) of each facet.
layout_pad : scalar
Padding between axes; passed to ``fig.tight_layout``.
despine : boolean
Remove the top and right spines from the plots.
dropna : boolean
Drop missing values from the data before plotting.
See Also
--------
pairplot : Easily drawing common uses of :class:`PairGrid`.
FacetGrid : Subplot grid for plotting conditional relationships.
Examples
--------
.. include:: ../docstrings/PairGrid.rst
"""
super(PairGrid, self).__init__()
# Handle deprecations
if size is not None:
height = size
msg = (
"The `size` parameter has been renamed to `height`; "
"please update your code."
)
warnings.warn(UserWarning(msg))
# Sort out the variables that define the grid
numeric_cols = self._find_numeric_cols(data)
if hue in numeric_cols:
numeric_cols.remove(hue)
if vars is not None:
x_vars = list(vars)
y_vars = list(vars)
if x_vars is None:
x_vars = numeric_cols
if y_vars is None:
y_vars = numeric_cols
if np.isscalar(x_vars):
x_vars = [x_vars]
if np.isscalar(y_vars):
y_vars = [y_vars]
self.x_vars = list(x_vars)
self.y_vars = list(y_vars)
self.square_grid = self.x_vars == self.y_vars
# Create the figure and the array of subplots
figsize = len(x_vars) * height * aspect, len(y_vars) * height
fig, axes = plt.subplots(
len(y_vars),
len(x_vars),
figsize=figsize,
sharex="col",
sharey="row",
squeeze=False,
)
# Possibly remove upper axes to make a corner grid
# Note: setting up the axes is usually the most time-intensive part
# of using the PairGrid. We are foregoing the speed improvement that
# we would get by just not setting up the hidden axes so that we can
# avoid implementing plt.subplots ourselves. But worth thinking about.
self._corner = corner
if corner:
hide_indices = np.triu_indices_from(axes, 1)
for i, j in zip(*hide_indices):
axes[i, j].remove()
axes[i, j] = None
self.fig = fig
self.axes = axes
self.data = data
# Save what we are going to do with the diagonal
self.diag_sharey = diag_sharey
self.diag_vars = None
self.diag_axes = None
self._dropna = dropna
# Label the axes
self._add_axis_labels()
# Sort out the hue variable
self._hue_var = hue
if hue is None:
self.hue_names = hue_order = ["_nolegend_"]
self.hue_vals = pd.Series(["_nolegend_"] * len(data), index=data.index)
else:
# We need hue_order and hue_names because the former is used to control
# the order of drawing and the latter is used to control the order of
# the legend. hue_names can become string-typed while hue_order must
# retain the type of the input data. This is messy but results from
# the fact that PairGrid can implement the hue-mapping logic itself
# (and was originally written exclusively that way) but now can delegate
# to the axes-level functions, while always handling legend creation.
# See GH2307
hue_names = hue_order = categorical_order(data[hue], hue_order)
if dropna:
# Filter NA from the list of unique hue names
hue_names = list(filter(pd.notnull, hue_names))
self.hue_names = hue_names
self.hue_vals = data[hue]
# Additional dict of kwarg -> list of values for mapping the hue var
self.hue_kws = hue_kws if hue_kws is not None else {}
self._orig_palette = palette
self._hue_order = hue_order
self.palette = self._get_palette(data, hue, hue_order, palette)
self._legend_data = {}
# Make the plot look nice
self._tight_layout_rect = [0.01, 0.01, 0.99, 0.99]
self._tight_layout_pad = layout_pad
self._despine = despine
if despine:
utils.despine(fig=fig)
self.tight_layout(pad=layout_pad)
|
https://github.com/mwaskom/seaborn/issues/2354
|
Traceback (most recent call last):
File "<ipython-input-87-23324450a106>", line 1, in <module>
sns.pairplot(p, diag_kind=None, corner=True)
File "c:\program files\python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1974, in pairplot
plotter(scatterplot, **plot_kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1250, in map
self._map_bivariate(func, indices, **kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1434, in _map_bivariate
self._plot_bivariate(x_var, y_var, ax, func, **kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1446, in _plot_bivariate
plt.sca(ax)
File "C:\Users\tgentils\AppData\Roaming\Python\Python38\site-packages\matplotlib\pyplot.py", line 982, in sca
if not hasattr(ax.figure.canvas, "manager"):
AttributeError: 'NoneType' object has no attribute 'figure'
|
AttributeError
|
def map_diag(self, func, **kwargs):
"""Plot with a univariate function on each diagonal subplot.
Parameters
----------
func : callable plotting function
Must take an x array as a positional argument and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
# Add special diagonal axes for the univariate plot
if self.diag_axes is None:
diag_vars = []
diag_axes = []
for i, y_var in enumerate(self.y_vars):
for j, x_var in enumerate(self.x_vars):
if x_var == y_var:
# Make the density axes
diag_vars.append(x_var)
ax = self.axes[i, j]
diag_ax = ax.twinx()
diag_ax.set_axis_off()
diag_axes.append(diag_ax)
# Work around matplotlib bug
# https://github.com/matplotlib/matplotlib/issues/15188
if not plt.rcParams.get("ytick.left", True):
for tick in ax.yaxis.majorTicks:
tick.tick1line.set_visible(False)
# Remove main y axis from density axes in a corner plot
if self._corner:
ax.yaxis.set_visible(False)
if self._despine:
utils.despine(ax=ax, left=True)
# TODO add optional density ticks (on the right)
# when drawing a corner plot?
if self.diag_sharey and diag_axes:
# This may change in future matplotlibs
# See https://github.com/matplotlib/matplotlib/pull/9923
group = diag_axes[0].get_shared_y_axes()
for ax in diag_axes[1:]:
group.join(ax, diag_axes[0])
self.diag_vars = np.array(diag_vars, np.object_)
self.diag_axes = np.array(diag_axes, np.object_)
if "hue" not in signature(func).parameters:
return self._map_diag_iter_hue(func, **kwargs)
# Loop over diagonal variables and axes, making one plot in each
for var, ax in zip(self.diag_vars, self.diag_axes):
plt.sca(ax)
plot_kwargs = kwargs.copy()
vector = self.data[var]
if self._hue_var is not None:
hue = self.data[self._hue_var]
else:
hue = None
if self._dropna:
not_na = vector.notna()
if hue is not None:
not_na &= hue.notna()
vector = vector[not_na]
if hue is not None:
hue = hue[not_na]
plot_kwargs.setdefault("hue", hue)
plot_kwargs.setdefault("hue_order", self._hue_order)
plot_kwargs.setdefault("palette", self._orig_palette)
func(x=vector, **plot_kwargs)
self._clean_axis(ax)
self._add_axis_labels()
return self
|
def map_diag(self, func, **kwargs):
"""Plot with a univariate function on each diagonal subplot.
Parameters
----------
func : callable plotting function
Must take an x array as a positional argument and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
# Add special diagonal axes for the univariate plot
if self.diag_axes is None:
diag_vars = []
diag_axes = []
for i, y_var in enumerate(self.y_vars):
for j, x_var in enumerate(self.x_vars):
if x_var == y_var:
# Make the density axes
diag_vars.append(x_var)
ax = self.axes[i, j]
diag_ax = ax.twinx()
diag_ax.set_axis_off()
diag_axes.append(diag_ax)
# Work around matplotlib bug
# https://github.com/matplotlib/matplotlib/issues/15188
if not plt.rcParams.get("ytick.left", True):
for tick in ax.yaxis.majorTicks:
tick.tick1line.set_visible(False)
# Remove main y axis from density axes in a corner plot
if self._corner:
ax.yaxis.set_visible(False)
if self._despine:
utils.despine(ax=ax, left=True)
# TODO add optional density ticks (on the right)
# when drawing a corner plot?
if self.diag_sharey:
# This may change in future matplotlibs
# See https://github.com/matplotlib/matplotlib/pull/9923
group = diag_axes[0].get_shared_y_axes()
for ax in diag_axes[1:]:
group.join(ax, diag_axes[0])
self.diag_vars = np.array(diag_vars, np.object_)
self.diag_axes = np.array(diag_axes, np.object_)
if "hue" not in signature(func).parameters:
return self._map_diag_iter_hue(func, **kwargs)
# Loop over diagonal variables and axes, making one plot in each
for var, ax in zip(self.diag_vars, self.diag_axes):
plt.sca(ax)
plot_kwargs = kwargs.copy()
vector = self.data[var]
if self._hue_var is not None:
hue = self.data[self._hue_var]
else:
hue = None
if self._dropna:
not_na = vector.notna()
if hue is not None:
not_na &= hue.notna()
vector = vector[not_na]
if hue is not None:
hue = hue[not_na]
plot_kwargs.setdefault("hue", hue)
plot_kwargs.setdefault("hue_order", self._hue_order)
plot_kwargs.setdefault("palette", self._orig_palette)
func(x=vector, **plot_kwargs)
self._clean_axis(ax)
self._add_axis_labels()
return self
|
https://github.com/mwaskom/seaborn/issues/2354
|
Traceback (most recent call last):
File "<ipython-input-87-23324450a106>", line 1, in <module>
sns.pairplot(p, diag_kind=None, corner=True)
File "c:\program files\python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1974, in pairplot
plotter(scatterplot, **plot_kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1250, in map
self._map_bivariate(func, indices, **kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1434, in _map_bivariate
self._plot_bivariate(x_var, y_var, ax, func, **kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1446, in _plot_bivariate
plt.sca(ax)
File "C:\Users\tgentils\AppData\Roaming\Python\Python38\site-packages\matplotlib\pyplot.py", line 982, in sca
if not hasattr(ax.figure.canvas, "manager"):
AttributeError: 'NoneType' object has no attribute 'figure'
|
AttributeError
|
def _map_bivariate(self, func, indices, **kwargs):
"""Draw a bivariate plot on the indicated axes."""
# This is a hack to handle the fact that new distribution plots don't add
# their artists onto the axes. This is probably superior in general, but
# we'll need a better way to handle it in the axisgrid functions.
from .distributions import histplot, kdeplot
if func is histplot or func is kdeplot:
self._extract_legend_handles = True
kws = kwargs.copy() # Use copy as we insert other kwargs
for i, j in indices:
x_var = self.x_vars[j]
y_var = self.y_vars[i]
ax = self.axes[i, j]
if ax is None: # i.e. we are in corner mode
continue
self._plot_bivariate(x_var, y_var, ax, func, **kws)
self._add_axis_labels()
if "hue" in signature(func).parameters:
self.hue_names = list(self._legend_data)
|
def _map_bivariate(self, func, indices, **kwargs):
"""Draw a bivariate plot on the indicated axes."""
# This is a hack to handle the fact that new distribution plots don't add
# their artists onto the axes. This is probably superior in general, but
# we'll need a better way to handle it in the axisgrid functions.
from .distributions import histplot, kdeplot
if func is histplot or func is kdeplot:
self._extract_legend_handles = True
kws = kwargs.copy() # Use copy as we insert other kwargs
for i, j in indices:
x_var = self.x_vars[j]
y_var = self.y_vars[i]
ax = self.axes[i, j]
self._plot_bivariate(x_var, y_var, ax, func, **kws)
self._add_axis_labels()
if "hue" in signature(func).parameters:
self.hue_names = list(self._legend_data)
|
https://github.com/mwaskom/seaborn/issues/2354
|
Traceback (most recent call last):
File "<ipython-input-87-23324450a106>", line 1, in <module>
sns.pairplot(p, diag_kind=None, corner=True)
File "c:\program files\python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1974, in pairplot
plotter(scatterplot, **plot_kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1250, in map
self._map_bivariate(func, indices, **kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1434, in _map_bivariate
self._plot_bivariate(x_var, y_var, ax, func, **kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1446, in _plot_bivariate
plt.sca(ax)
File "C:\Users\tgentils\AppData\Roaming\Python\Python38\site-packages\matplotlib\pyplot.py", line 982, in sca
if not hasattr(ax.figure.canvas, "manager"):
AttributeError: 'NoneType' object has no attribute 'figure'
|
AttributeError
|
def pairplot(
data,
*,
hue=None,
hue_order=None,
palette=None,
vars=None,
x_vars=None,
y_vars=None,
kind="scatter",
diag_kind="auto",
markers=None,
height=2.5,
aspect=1,
corner=False,
dropna=False,
plot_kws=None,
diag_kws=None,
grid_kws=None,
size=None,
):
"""Plot pairwise relationships in a dataset.
By default, this function will create a grid of Axes such that each numeric
variable in ``data`` will by shared across the y-axes across a single row and
the x-axes across a single column. The diagonal plots are treated
differently: a univariate distribution plot is drawn to show the marginal
distribution of the data in each column.
It is also possible to show a subset of variables or plot different
variables on the rows and columns.
This is a high-level interface for :class:`PairGrid` that is intended to
make it easy to draw a few common styles. You should use :class:`PairGrid`
directly if you need more flexibility.
Parameters
----------
data : `pandas.DataFrame`
Tidy (long-form) dataframe where each column is a variable and
each row is an observation.
hue : name of variable in ``data``
Variable in ``data`` to map plot aspects to different colors.
hue_order : list of strings
Order for the levels of the hue variable in the palette
palette : dict or seaborn color palette
Set of colors for mapping the ``hue`` variable. If a dict, keys
should be values in the ``hue`` variable.
vars : list of variable names
Variables within ``data`` to use, otherwise use every column with
a numeric datatype.
{x, y}_vars : lists of variable names
Variables within ``data`` to use separately for the rows and
columns of the figure; i.e. to make a non-square plot.
kind : {'scatter', 'kde', 'hist', 'reg'}
Kind of plot to make.
diag_kind : {'auto', 'hist', 'kde', None}
Kind of plot for the diagonal subplots. If 'auto', choose based on
whether or not ``hue`` is used.
markers : single matplotlib marker code or list
Either the marker to use for all scatterplot points or a list of markers
with a length the same as the number of levels in the hue variable so that
differently colored points will also have different scatterplot
markers.
height : scalar
Height (in inches) of each facet.
aspect : scalar
Aspect * height gives the width (in inches) of each facet.
corner : bool
If True, don't add axes to the upper (off-diagonal) triangle of the
grid, making this a "corner" plot.
dropna : boolean
Drop missing values from the data before plotting.
{plot, diag, grid}_kws : dicts
Dictionaries of keyword arguments. ``plot_kws`` are passed to the
bivariate plotting function, ``diag_kws`` are passed to the univariate
plotting function, and ``grid_kws`` are passed to the :class:`PairGrid`
constructor.
Returns
-------
grid : :class:`PairGrid`
Returns the underlying :class:`PairGrid` instance for further tweaking.
See Also
--------
PairGrid : Subplot grid for more flexible plotting of pairwise relationships.
JointGrid : Grid for plotting joint and marginal distributions of two variables.
Examples
--------
.. include:: ../docstrings/pairplot.rst
"""
# Avoid circular import
from .distributions import histplot, kdeplot
# Handle deprecations
if size is not None:
height = size
msg = (
"The `size` parameter has been renamed to `height`; "
"please update your code."
)
warnings.warn(msg, UserWarning)
if not isinstance(data, pd.DataFrame):
raise TypeError(
"'data' must be pandas DataFrame object, not: {typefound}".format(
typefound=type(data)
)
)
plot_kws = {} if plot_kws is None else plot_kws.copy()
diag_kws = {} if diag_kws is None else diag_kws.copy()
grid_kws = {} if grid_kws is None else grid_kws.copy()
# Resolve "auto" diag kind
if diag_kind == "auto":
if hue is None:
diag_kind = "kde" if kind == "kde" else "hist"
else:
diag_kind = "hist" if kind == "hist" else "kde"
# Set up the PairGrid
grid_kws.setdefault("diag_sharey", diag_kind == "hist")
grid = PairGrid(
data,
vars=vars,
x_vars=x_vars,
y_vars=y_vars,
hue=hue,
hue_order=hue_order,
palette=palette,
corner=corner,
height=height,
aspect=aspect,
dropna=dropna,
**grid_kws,
)
# Add the markers here as PairGrid has figured out how many levels of the
# hue variable are needed and we don't want to duplicate that process
if markers is not None:
if kind == "reg":
# Needed until regplot supports style
if grid.hue_names is None:
n_markers = 1
else:
n_markers = len(grid.hue_names)
if not isinstance(markers, list):
markers = [markers] * n_markers
if len(markers) != n_markers:
raise ValueError(
(
"markers must be a singleton or a list of "
"markers for each level of the hue variable"
)
)
grid.hue_kws = {"marker": markers}
elif kind == "scatter":
if isinstance(markers, str):
plot_kws["marker"] = markers
elif hue is not None:
plot_kws["style"] = data[hue]
plot_kws["markers"] = markers
# Draw the marginal plots on the diagonal
diag_kws = diag_kws.copy()
diag_kws.setdefault("legend", False)
if diag_kind == "hist":
grid.map_diag(histplot, **diag_kws)
elif diag_kind == "kde":
diag_kws.setdefault("fill", True)
grid.map_diag(kdeplot, **diag_kws)
# Maybe plot on the off-diagonals
if diag_kind is not None:
plotter = grid.map_offdiag
else:
plotter = grid.map
if kind == "scatter":
from .relational import scatterplot # Avoid circular import
plotter(scatterplot, **plot_kws)
elif kind == "reg":
from .regression import regplot # Avoid circular import
plotter(regplot, **plot_kws)
elif kind == "kde":
from .distributions import kdeplot # Avoid circular import
plotter(kdeplot, **plot_kws)
elif kind == "hist":
from .distributions import histplot # Avoid circular import
plotter(histplot, **plot_kws)
# Add a legend
if hue is not None:
grid.add_legend()
grid.tight_layout()
return grid
|
def pairplot(
data,
*,
hue=None,
hue_order=None,
palette=None,
vars=None,
x_vars=None,
y_vars=None,
kind="scatter",
diag_kind="auto",
markers=None,
height=2.5,
aspect=1,
corner=False,
dropna=False,
plot_kws=None,
diag_kws=None,
grid_kws=None,
size=None,
):
"""Plot pairwise relationships in a dataset.
By default, this function will create a grid of Axes such that each numeric
variable in ``data`` will by shared across the y-axes across a single row and
the x-axes across a single column. The diagonal plots are treated
differently: a univariate distribution plot is drawn to show the marginal
distribution of the data in each column.
It is also possible to show a subset of variables or plot different
variables on the rows and columns.
This is a high-level interface for :class:`PairGrid` that is intended to
make it easy to draw a few common styles. You should use :class:`PairGrid`
directly if you need more flexibility.
Parameters
----------
data : `pandas.DataFrame`
Tidy (long-form) dataframe where each column is a variable and
each row is an observation.
hue : name of variable in ``data``
Variable in ``data`` to map plot aspects to different colors.
hue_order : list of strings
Order for the levels of the hue variable in the palette
palette : dict or seaborn color palette
Set of colors for mapping the ``hue`` variable. If a dict, keys
should be values in the ``hue`` variable.
vars : list of variable names
Variables within ``data`` to use, otherwise use every column with
a numeric datatype.
{x, y}_vars : lists of variable names
Variables within ``data`` to use separately for the rows and
columns of the figure; i.e. to make a non-square plot.
kind : {'scatter', 'kde', 'hist', 'reg'}
Kind of plot to make.
diag_kind : {'auto', 'hist', 'kde', None}
Kind of plot for the diagonal subplots. If 'auto', choose based on
whether or not ``hue`` is used.
markers : single matplotlib marker code or list
Either the marker to use for all scatterplot points or a list of markers
with a length the same as the number of levels in the hue variable so that
differently colored points will also have different scatterplot
markers.
height : scalar
Height (in inches) of each facet.
aspect : scalar
Aspect * height gives the width (in inches) of each facet.
corner : bool
If True, don't add axes to the upper (off-diagonal) triangle of the
grid, making this a "corner" plot.
dropna : boolean
Drop missing values from the data before plotting.
{plot, diag, grid}_kws : dicts
Dictionaries of keyword arguments. ``plot_kws`` are passed to the
bivariate plotting function, ``diag_kws`` are passed to the univariate
plotting function, and ``grid_kws`` are passed to the :class:`PairGrid`
constructor.
Returns
-------
grid : :class:`PairGrid`
Returns the underlying :class:`PairGrid` instance for further tweaking.
See Also
--------
PairGrid : Subplot grid for more flexible plotting of pairwise relationships.
JointGrid : Grid for plotting joint and marginal distributions of two variables.
Examples
--------
.. include:: ../docstrings/pairplot.rst
"""
# Avoid circular import
from .distributions import histplot, kdeplot
# Handle deprecations
if size is not None:
height = size
msg = (
"The `size` parameter has been renamed to `height`; "
"please update your code."
)
warnings.warn(msg, UserWarning)
if not isinstance(data, pd.DataFrame):
raise TypeError(
"'data' must be pandas DataFrame object, not: {typefound}".format(
typefound=type(data)
)
)
plot_kws = {} if plot_kws is None else plot_kws.copy()
diag_kws = {} if diag_kws is None else diag_kws.copy()
grid_kws = {} if grid_kws is None else grid_kws.copy()
# Set up the PairGrid
grid_kws.setdefault("diag_sharey", diag_kind == "hist")
grid = PairGrid(
data,
vars=vars,
x_vars=x_vars,
y_vars=y_vars,
hue=hue,
hue_order=hue_order,
palette=palette,
corner=corner,
height=height,
aspect=aspect,
dropna=dropna,
**grid_kws,
)
# Add the markers here as PairGrid has figured out how many levels of the
# hue variable are needed and we don't want to duplicate that process
if markers is not None:
if kind == "reg":
# Needed until regplot supports style
if grid.hue_names is None:
n_markers = 1
else:
n_markers = len(grid.hue_names)
if not isinstance(markers, list):
markers = [markers] * n_markers
if len(markers) != n_markers:
raise ValueError(
(
"markers must be a singleton or a list of "
"markers for each level of the hue variable"
)
)
grid.hue_kws = {"marker": markers}
elif kind == "scatter":
if isinstance(markers, str):
plot_kws["marker"] = markers
elif hue is not None:
plot_kws["style"] = data[hue]
plot_kws["markers"] = markers
# Maybe plot on the diagonal
if diag_kind == "auto":
if hue is None:
diag_kind = "kde" if kind == "kde" else "hist"
else:
diag_kind = "hist" if kind == "hist" else "kde"
diag_kws = diag_kws.copy()
diag_kws.setdefault("legend", False)
if diag_kind == "hist":
grid.map_diag(histplot, **diag_kws)
elif diag_kind == "kde":
diag_kws.setdefault("fill", True)
grid.map_diag(kdeplot, **diag_kws)
# Maybe plot on the off-diagonals
if diag_kind is not None:
plotter = grid.map_offdiag
else:
plotter = grid.map
if kind == "scatter":
from .relational import scatterplot # Avoid circular import
plotter(scatterplot, **plot_kws)
elif kind == "reg":
from .regression import regplot # Avoid circular import
plotter(regplot, **plot_kws)
elif kind == "kde":
from .distributions import kdeplot # Avoid circular import
plotter(kdeplot, **plot_kws)
elif kind == "hist":
from .distributions import histplot # Avoid circular import
plotter(histplot, **plot_kws)
# Add a legend
if hue is not None:
grid.add_legend()
grid.tight_layout()
return grid
|
https://github.com/mwaskom/seaborn/issues/2354
|
Traceback (most recent call last):
File "<ipython-input-87-23324450a106>", line 1, in <module>
sns.pairplot(p, diag_kind=None, corner=True)
File "c:\program files\python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1974, in pairplot
plotter(scatterplot, **plot_kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1250, in map
self._map_bivariate(func, indices, **kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1434, in _map_bivariate
self._plot_bivariate(x_var, y_var, ax, func, **kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1446, in _plot_bivariate
plt.sca(ax)
File "C:\Users\tgentils\AppData\Roaming\Python\Python38\site-packages\matplotlib\pyplot.py", line 982, in sca
if not hasattr(ax.figure.canvas, "manager"):
AttributeError: 'NoneType' object has no attribute 'figure'
|
AttributeError
|
def jointplot(
*,
x=None,
y=None,
data=None,
kind="scatter",
color=None,
height=6,
ratio=5,
space=0.2,
dropna=False,
xlim=None,
ylim=None,
marginal_ticks=False,
joint_kws=None,
marginal_kws=None,
hue=None,
palette=None,
hue_order=None,
hue_norm=None,
**kwargs,
):
# Avoid circular imports
from .relational import scatterplot
from .regression import regplot, residplot
from .distributions import histplot, kdeplot, _freedman_diaconis_bins
# Handle deprecations
if "size" in kwargs:
height = kwargs.pop("size")
msg = (
"The `size` parameter has been renamed to `height`; "
"please update your code."
)
warnings.warn(msg, UserWarning)
# Set up empty default kwarg dicts
joint_kws = {} if joint_kws is None else joint_kws.copy()
joint_kws.update(kwargs)
marginal_kws = {} if marginal_kws is None else marginal_kws.copy()
# Handle deprecations of distplot-specific kwargs
distplot_keys = [
"rug",
"fit",
"hist_kws",
"norm_histhist_kws",
"rug_kws",
]
unused_keys = []
for key in distplot_keys:
if key in marginal_kws:
unused_keys.append(key)
marginal_kws.pop(key)
if unused_keys and kind != "kde":
msg = (
"The marginal plotting function has changed to `histplot`,"
" which does not accept the following argument(s): {}."
).format(", ".join(unused_keys))
warnings.warn(msg, UserWarning)
# Validate the plot kind
plot_kinds = ["scatter", "hist", "hex", "kde", "reg", "resid"]
_check_argument("kind", plot_kinds, kind)
# Raise early if using `hue` with a kind that does not support it
if hue is not None and kind in ["hex", "reg", "resid"]:
msg = f"Use of `hue` with `kind='{kind}'` is not currently supported."
raise ValueError(msg)
# Make a colormap based off the plot color
# (Currently used only for kind="hex")
if color is None:
color = "C0"
color_rgb = mpl.colors.colorConverter.to_rgb(color)
colors = [
utils.set_hls_values(color_rgb, l=l) # noqa
for l in np.linspace(1, 0, 12)
]
cmap = blend_palette(colors, as_cmap=True)
# Matplotlib's hexbin plot is not na-robust
if kind == "hex":
dropna = True
# Initialize the JointGrid object
grid = JointGrid(
data=data,
x=x,
y=y,
hue=hue,
palette=palette,
hue_order=hue_order,
hue_norm=hue_norm,
dropna=dropna,
height=height,
ratio=ratio,
space=space,
xlim=xlim,
ylim=ylim,
marginal_ticks=marginal_ticks,
)
if grid.hue is not None:
marginal_kws.setdefault("legend", False)
# Plot the data using the grid
if kind.startswith("scatter"):
joint_kws.setdefault("color", color)
grid.plot_joint(scatterplot, **joint_kws)
if grid.hue is None:
marg_func = histplot
else:
marg_func = kdeplot
marginal_kws.setdefault("fill", True)
marginal_kws.setdefault("color", color)
grid.plot_marginals(marg_func, **marginal_kws)
elif kind.startswith("hist"):
# TODO process pair parameters for bins, etc. and pass
# to both jount and marginal plots
joint_kws.setdefault("color", color)
grid.plot_joint(histplot, **joint_kws)
marginal_kws.setdefault("kde", False)
marginal_kws.setdefault("color", color)
marg_x_kws = marginal_kws.copy()
marg_y_kws = marginal_kws.copy()
pair_keys = "bins", "binwidth", "binrange"
for key in pair_keys:
if isinstance(joint_kws.get(key), tuple):
x_val, y_val = joint_kws[key]
marg_x_kws.setdefault(key, x_val)
marg_y_kws.setdefault(key, y_val)
histplot(data=data, x=x, hue=hue, **marg_x_kws, ax=grid.ax_marg_x)
histplot(data=data, y=y, hue=hue, **marg_y_kws, ax=grid.ax_marg_y)
elif kind.startswith("kde"):
joint_kws.setdefault("color", color)
grid.plot_joint(kdeplot, **joint_kws)
marginal_kws.setdefault("color", color)
if "fill" in joint_kws:
marginal_kws.setdefault("fill", joint_kws["fill"])
grid.plot_marginals(kdeplot, **marginal_kws)
elif kind.startswith("hex"):
x_bins = min(_freedman_diaconis_bins(grid.x), 50)
y_bins = min(_freedman_diaconis_bins(grid.y), 50)
gridsize = int(np.mean([x_bins, y_bins]))
joint_kws.setdefault("gridsize", gridsize)
joint_kws.setdefault("cmap", cmap)
grid.plot_joint(plt.hexbin, **joint_kws)
marginal_kws.setdefault("kde", False)
marginal_kws.setdefault("color", color)
grid.plot_marginals(histplot, **marginal_kws)
elif kind.startswith("reg"):
marginal_kws.setdefault("color", color)
marginal_kws.setdefault("kde", True)
grid.plot_marginals(histplot, **marginal_kws)
joint_kws.setdefault("color", color)
grid.plot_joint(regplot, **joint_kws)
elif kind.startswith("resid"):
joint_kws.setdefault("color", color)
grid.plot_joint(residplot, **joint_kws)
x, y = grid.ax_joint.collections[0].get_offsets().T
marginal_kws.setdefault("color", color)
histplot(x=x, hue=hue, ax=grid.ax_marg_x, **marginal_kws)
histplot(y=y, hue=hue, ax=grid.ax_marg_y, **marginal_kws)
return grid
|
def jointplot(
*,
x=None,
y=None,
data=None,
kind="scatter",
color=None,
height=6,
ratio=5,
space=0.2,
dropna=False,
xlim=None,
ylim=None,
marginal_ticks=False,
joint_kws=None,
marginal_kws=None,
hue=None,
palette=None,
hue_order=None,
hue_norm=None,
**kwargs,
):
# Avoid circular imports
from .relational import scatterplot
from .regression import regplot, residplot
from .distributions import histplot, kdeplot, _freedman_diaconis_bins
# Handle deprecations
if "size" in kwargs:
height = kwargs.pop("size")
msg = (
"The `size` parameter has been renamed to `height`; "
"please update your code."
)
warnings.warn(msg, UserWarning)
# Set up empty default kwarg dicts
joint_kws = {} if joint_kws is None else joint_kws.copy()
joint_kws.update(kwargs)
marginal_kws = {} if marginal_kws is None else marginal_kws.copy()
# Handle deprecations of distplot-specific kwargs
distplot_keys = [
"rug",
"fit",
"hist_kws",
"norm_histhist_kws",
"rug_kws",
]
unused_keys = []
for key in distplot_keys:
if key in marginal_kws:
unused_keys.append(key)
marginal_kws.pop(key)
if unused_keys and kind != "kde":
msg = (
"The marginal plotting function has changed to `histplot`,"
" which does not accept the following argument(s): {}."
).format(", ".join(unused_keys))
warnings.warn(msg, UserWarning)
# Validate the plot kind
plot_kinds = ["scatter", "hist", "hex", "kde", "reg", "resid"]
_check_argument("kind", plot_kinds, kind)
# Make a colormap based off the plot color
# (Currently used only for kind="hex")
if color is None:
color = "C0"
color_rgb = mpl.colors.colorConverter.to_rgb(color)
colors = [
utils.set_hls_values(color_rgb, l=l) # noqa
for l in np.linspace(1, 0, 12)
]
cmap = blend_palette(colors, as_cmap=True)
# Matplotlib's hexbin plot is not na-robust
if kind == "hex":
dropna = True
# Initialize the JointGrid object
grid = JointGrid(
data=data,
x=x,
y=y,
hue=hue,
palette=palette,
hue_order=hue_order,
hue_norm=hue_norm,
dropna=dropna,
height=height,
ratio=ratio,
space=space,
xlim=xlim,
ylim=ylim,
marginal_ticks=marginal_ticks,
)
if grid.hue is not None:
marginal_kws.setdefault("legend", False)
# Plot the data using the grid
if kind.startswith("scatter"):
joint_kws.setdefault("color", color)
grid.plot_joint(scatterplot, **joint_kws)
if grid.hue is None:
marg_func = histplot
else:
marg_func = kdeplot
marginal_kws.setdefault("fill", True)
marginal_kws.setdefault("color", color)
grid.plot_marginals(marg_func, **marginal_kws)
elif kind.startswith("hist"):
# TODO process pair parameters for bins, etc. and pass
# to both jount and marginal plots
joint_kws.setdefault("color", color)
grid.plot_joint(histplot, **joint_kws)
marginal_kws.setdefault("kde", False)
marginal_kws.setdefault("color", color)
marg_x_kws = marginal_kws.copy()
marg_y_kws = marginal_kws.copy()
pair_keys = "bins", "binwidth", "binrange"
for key in pair_keys:
if isinstance(joint_kws.get(key), tuple):
x_val, y_val = joint_kws[key]
marg_x_kws.setdefault(key, x_val)
marg_y_kws.setdefault(key, y_val)
histplot(data=data, x=x, hue=hue, **marg_x_kws, ax=grid.ax_marg_x)
histplot(data=data, y=y, hue=hue, **marg_y_kws, ax=grid.ax_marg_y)
elif kind.startswith("kde"):
joint_kws.setdefault("color", color)
grid.plot_joint(kdeplot, **joint_kws)
marginal_kws.setdefault("color", color)
if "fill" in joint_kws:
marginal_kws.setdefault("fill", joint_kws["fill"])
grid.plot_marginals(kdeplot, **marginal_kws)
elif kind.startswith("hex"):
x_bins = min(_freedman_diaconis_bins(grid.x), 50)
y_bins = min(_freedman_diaconis_bins(grid.y), 50)
gridsize = int(np.mean([x_bins, y_bins]))
joint_kws.setdefault("gridsize", gridsize)
joint_kws.setdefault("cmap", cmap)
grid.plot_joint(plt.hexbin, **joint_kws)
marginal_kws.setdefault("kde", False)
marginal_kws.setdefault("color", color)
grid.plot_marginals(histplot, **marginal_kws)
elif kind.startswith("reg"):
marginal_kws.setdefault("color", color)
marginal_kws.setdefault("kde", True)
grid.plot_marginals(histplot, **marginal_kws)
joint_kws.setdefault("color", color)
grid.plot_joint(regplot, **joint_kws)
elif kind.startswith("resid"):
joint_kws.setdefault("color", color)
grid.plot_joint(residplot, **joint_kws)
x, y = grid.ax_joint.collections[0].get_offsets().T
marginal_kws.setdefault("color", color)
histplot(x=x, hue=hue, ax=grid.ax_marg_x, **marginal_kws)
histplot(y=y, hue=hue, ax=grid.ax_marg_y, **marginal_kws)
return grid
|
https://github.com/mwaskom/seaborn/issues/2354
|
Traceback (most recent call last):
File "<ipython-input-87-23324450a106>", line 1, in <module>
sns.pairplot(p, diag_kind=None, corner=True)
File "c:\program files\python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1974, in pairplot
plotter(scatterplot, **plot_kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1250, in map
self._map_bivariate(func, indices, **kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1434, in _map_bivariate
self._plot_bivariate(x_var, y_var, ax, func, **kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1446, in _plot_bivariate
plt.sca(ax)
File "C:\Users\tgentils\AppData\Roaming\Python\Python38\site-packages\matplotlib\pyplot.py", line 982, in sca
if not hasattr(ax.figure.canvas, "manager"):
AttributeError: 'NoneType' object has no attribute 'figure'
|
AttributeError
|
def _compute_univariate_density(
self,
data_variable,
common_norm,
common_grid,
estimate_kws,
log_scale,
):
# Initialize the estimator object
estimator = KDE(**estimate_kws)
all_data = self.plot_data.dropna()
if set(self.variables) - {"x", "y"}:
if common_grid:
all_observations = self.comp_data.dropna()
estimator.define_support(all_observations[data_variable])
else:
common_norm = False
densities = {}
for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True):
# Extract the data points from this sub set and remove nulls
sub_data = sub_data.dropna()
observations = sub_data[data_variable]
observation_variance = observations.var()
if math.isclose(observation_variance, 0) or np.isnan(observation_variance):
msg = "Dataset has 0 variance; skipping density estimate."
warnings.warn(msg, UserWarning)
continue
# Extract the weights for this subset of observations
if "weights" in self.variables:
weights = sub_data["weights"]
else:
weights = None
# Estimate the density of observations at this level
density, support = estimator(observations, weights=weights)
if log_scale:
support = np.power(10, support)
# Apply a scaling factor so that the integral over all subsets is 1
if common_norm:
density *= len(sub_data) / len(all_data)
# Store the density for this level
key = tuple(sub_vars.items())
densities[key] = pd.Series(density, index=support)
return densities
|
def _compute_univariate_density(
self,
data_variable,
common_norm,
common_grid,
estimate_kws,
log_scale,
):
# Initialize the estimator object
estimator = KDE(**estimate_kws)
all_data = self.plot_data.dropna()
if set(self.variables) - {"x", "y"}:
if common_grid:
all_observations = self.comp_data.dropna()
estimator.define_support(all_observations[data_variable])
else:
common_norm = False
densities = {}
for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True):
# Extract the data points from this sub set and remove nulls
sub_data = sub_data.dropna()
observations = sub_data[data_variable]
observation_variance = observations.var()
if np.isclose(observation_variance, 0) or np.isnan(observation_variance):
msg = "Dataset has 0 variance; skipping density estimate."
warnings.warn(msg, UserWarning)
continue
# Extract the weights for this subset of observations
if "weights" in self.variables:
weights = sub_data["weights"]
else:
weights = None
# Estimate the density of observations at this level
density, support = estimator(observations, weights=weights)
if log_scale:
support = np.power(10, support)
# Apply a scaling factor so that the integral over all subsets is 1
if common_norm:
density *= len(sub_data) / len(all_data)
# Store the density for this level
key = tuple(sub_vars.items())
densities[key] = pd.Series(density, index=support)
return densities
|
https://github.com/mwaskom/seaborn/issues/2354
|
Traceback (most recent call last):
File "<ipython-input-87-23324450a106>", line 1, in <module>
sns.pairplot(p, diag_kind=None, corner=True)
File "c:\program files\python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1974, in pairplot
plotter(scatterplot, **plot_kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1250, in map
self._map_bivariate(func, indices, **kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1434, in _map_bivariate
self._plot_bivariate(x_var, y_var, ax, func, **kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1446, in _plot_bivariate
plt.sca(ax)
File "C:\Users\tgentils\AppData\Roaming\Python\Python38\site-packages\matplotlib\pyplot.py", line 982, in sca
if not hasattr(ax.figure.canvas, "manager"):
AttributeError: 'NoneType' object has no attribute 'figure'
|
AttributeError
|
def plot_bivariate_density(
self,
common_norm,
fill,
levels,
thresh,
color,
legend,
cbar,
cbar_ax,
cbar_kws,
estimate_kws,
**contour_kws,
):
contour_kws = contour_kws.copy()
estimator = KDE(**estimate_kws)
if not set(self.variables) - {"x", "y"}:
common_norm = False
all_data = self.plot_data.dropna()
# Loop through the subsets and estimate the KDEs
densities, supports = {}, {}
for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True):
# Extract the data points from this sub set and remove nulls
sub_data = sub_data.dropna()
observations = sub_data[["x", "y"]]
# Extract the weights for this subset of observations
if "weights" in self.variables:
weights = sub_data["weights"]
else:
weights = None
# Check that KDE will not error out
variance = observations[["x", "y"]].var()
if any(math.isclose(x, 0) for x in variance) or variance.isna().any():
msg = "Dataset has 0 variance; skipping density estimate."
warnings.warn(msg, UserWarning)
continue
# Estimate the density of observations at this level
observations = observations["x"], observations["y"]
density, support = estimator(*observations, weights=weights)
# Transform the support grid back to the original scale
xx, yy = support
if self._log_scaled("x"):
xx = np.power(10, xx)
if self._log_scaled("y"):
yy = np.power(10, yy)
support = xx, yy
# Apply a scaling factor so that the integral over all subsets is 1
if common_norm:
density *= len(sub_data) / len(all_data)
key = tuple(sub_vars.items())
densities[key] = density
supports[key] = support
# Define a grid of iso-proportion levels
if thresh is None:
thresh = 0
if isinstance(levels, Number):
levels = np.linspace(thresh, 1, levels)
else:
if min(levels) < 0 or max(levels) > 1:
raise ValueError("levels must be in [0, 1]")
# Transform from iso-proportions to iso-densities
if common_norm:
common_levels = self._quantile_to_level(
list(densities.values()),
levels,
)
draw_levels = {k: common_levels for k in densities}
else:
draw_levels = {
k: self._quantile_to_level(d, levels) for k, d in densities.items()
}
# Get a default single color from the attribute cycle
if self.ax is None:
default_color = "C0" if color is None else color
else:
(scout,) = self.ax.plot([], color=color)
default_color = scout.get_color()
scout.remove()
# Define the coloring of the contours
if "hue" in self.variables:
for param in ["cmap", "colors"]:
if param in contour_kws:
msg = f"{param} parameter ignored when using hue mapping."
warnings.warn(msg, UserWarning)
contour_kws.pop(param)
else:
# Work out a default coloring of the contours
coloring_given = set(contour_kws) & {"cmap", "colors"}
if fill and not coloring_given:
cmap = self._cmap_from_color(default_color)
contour_kws["cmap"] = cmap
if not fill and not coloring_given:
contour_kws["colors"] = [default_color]
# Use our internal colormap lookup
cmap = contour_kws.pop("cmap", None)
if isinstance(cmap, str):
cmap = color_palette(cmap, as_cmap=True)
if cmap is not None:
contour_kws["cmap"] = cmap
# Loop through the subsets again and plot the data
for sub_vars, _ in self.iter_data("hue"):
if "hue" in sub_vars:
color = self._hue_map(sub_vars["hue"])
if fill:
contour_kws["cmap"] = self._cmap_from_color(color)
else:
contour_kws["colors"] = [color]
ax = self._get_axes(sub_vars)
# Choose the function to plot with
# TODO could add a pcolormesh based option as well
# Which would look something like element="raster"
if fill:
contour_func = ax.contourf
else:
contour_func = ax.contour
key = tuple(sub_vars.items())
if key not in densities:
continue
density = densities[key]
xx, yy = supports[key]
label = contour_kws.pop("label", None)
cset = contour_func(
xx,
yy,
density,
levels=draw_levels[key],
**contour_kws,
)
if "hue" not in self.variables:
cset.collections[0].set_label(label)
# Add a color bar representing the contour heights
# Note: this shows iso densities, not iso proportions
# See more notes in histplot about how this could be improved
if cbar:
cbar_kws = {} if cbar_kws is None else cbar_kws
ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws)
# --- Finalize the plot
ax = self.ax if self.ax is not None else self.facets.axes.flat[0]
self._add_axis_labels(ax)
if "hue" in self.variables and legend:
# TODO if possible, I would like to move the contour
# intensity information into the legend too and label the
# iso proportions rather than the raw density values
artist_kws = {}
if fill:
artist = partial(mpl.patches.Patch)
else:
artist = partial(mpl.lines.Line2D, [], [])
ax_obj = self.ax if self.ax is not None else self.facets
self._add_legend(
ax_obj,
artist,
fill,
False,
"layer",
1,
artist_kws,
{},
)
|
def plot_bivariate_density(
self,
common_norm,
fill,
levels,
thresh,
color,
legend,
cbar,
cbar_ax,
cbar_kws,
estimate_kws,
**contour_kws,
):
contour_kws = contour_kws.copy()
estimator = KDE(**estimate_kws)
if not set(self.variables) - {"x", "y"}:
common_norm = False
all_data = self.plot_data.dropna()
# Loop through the subsets and estimate the KDEs
densities, supports = {}, {}
for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True):
# Extract the data points from this sub set and remove nulls
sub_data = sub_data.dropna()
observations = sub_data[["x", "y"]]
# Extract the weights for this subset of observations
if "weights" in self.variables:
weights = sub_data["weights"]
else:
weights = None
# Check that KDE will not error out
variance = observations[["x", "y"]].var()
if np.isclose(variance, 0).any() or variance.isna().any():
msg = "Dataset has 0 variance; skipping density estimate."
warnings.warn(msg, UserWarning)
continue
# Estimate the density of observations at this level
observations = observations["x"], observations["y"]
density, support = estimator(*observations, weights=weights)
# Transform the support grid back to the original scale
xx, yy = support
if self._log_scaled("x"):
xx = np.power(10, xx)
if self._log_scaled("y"):
yy = np.power(10, yy)
support = xx, yy
# Apply a scaling factor so that the integral over all subsets is 1
if common_norm:
density *= len(sub_data) / len(all_data)
key = tuple(sub_vars.items())
densities[key] = density
supports[key] = support
# Define a grid of iso-proportion levels
if thresh is None:
thresh = 0
if isinstance(levels, Number):
levels = np.linspace(thresh, 1, levels)
else:
if min(levels) < 0 or max(levels) > 1:
raise ValueError("levels must be in [0, 1]")
# Transform from iso-proportions to iso-densities
if common_norm:
common_levels = self._quantile_to_level(
list(densities.values()),
levels,
)
draw_levels = {k: common_levels for k in densities}
else:
draw_levels = {
k: self._quantile_to_level(d, levels) for k, d in densities.items()
}
# Get a default single color from the attribute cycle
if self.ax is None:
default_color = "C0" if color is None else color
else:
(scout,) = self.ax.plot([], color=color)
default_color = scout.get_color()
scout.remove()
# Define the coloring of the contours
if "hue" in self.variables:
for param in ["cmap", "colors"]:
if param in contour_kws:
msg = f"{param} parameter ignored when using hue mapping."
warnings.warn(msg, UserWarning)
contour_kws.pop(param)
else:
# Work out a default coloring of the contours
coloring_given = set(contour_kws) & {"cmap", "colors"}
if fill and not coloring_given:
cmap = self._cmap_from_color(default_color)
contour_kws["cmap"] = cmap
if not fill and not coloring_given:
contour_kws["colors"] = [default_color]
# Use our internal colormap lookup
cmap = contour_kws.pop("cmap", None)
if isinstance(cmap, str):
cmap = color_palette(cmap, as_cmap=True)
if cmap is not None:
contour_kws["cmap"] = cmap
# Loop through the subsets again and plot the data
for sub_vars, _ in self.iter_data("hue"):
if "hue" in sub_vars:
color = self._hue_map(sub_vars["hue"])
if fill:
contour_kws["cmap"] = self._cmap_from_color(color)
else:
contour_kws["colors"] = [color]
ax = self._get_axes(sub_vars)
# Choose the function to plot with
# TODO could add a pcolormesh based option as well
# Which would look something like element="raster"
if fill:
contour_func = ax.contourf
else:
contour_func = ax.contour
key = tuple(sub_vars.items())
if key not in densities:
continue
density = densities[key]
xx, yy = supports[key]
label = contour_kws.pop("label", None)
cset = contour_func(
xx,
yy,
density,
levels=draw_levels[key],
**contour_kws,
)
if "hue" not in self.variables:
cset.collections[0].set_label(label)
# Add a color bar representing the contour heights
# Note: this shows iso densities, not iso proportions
# See more notes in histplot about how this could be improved
if cbar:
cbar_kws = {} if cbar_kws is None else cbar_kws
ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws)
# --- Finalize the plot
ax = self.ax if self.ax is not None else self.facets.axes.flat[0]
self._add_axis_labels(ax)
if "hue" in self.variables and legend:
# TODO if possible, I would like to move the contour
# intensity information into the legend too and label the
# iso proportions rather than the raw density values
artist_kws = {}
if fill:
artist = partial(mpl.patches.Patch)
else:
artist = partial(mpl.lines.Line2D, [], [])
ax_obj = self.ax if self.ax is not None else self.facets
self._add_legend(
ax_obj,
artist,
fill,
False,
"layer",
1,
artist_kws,
{},
)
|
https://github.com/mwaskom/seaborn/issues/2354
|
Traceback (most recent call last):
File "<ipython-input-87-23324450a106>", line 1, in <module>
sns.pairplot(p, diag_kind=None, corner=True)
File "c:\program files\python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1974, in pairplot
plotter(scatterplot, **plot_kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1250, in map
self._map_bivariate(func, indices, **kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1434, in _map_bivariate
self._plot_bivariate(x_var, y_var, ax, func, **kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1446, in _plot_bivariate
plt.sca(ax)
File "C:\Users\tgentils\AppData\Roaming\Python\Python38\site-packages\matplotlib\pyplot.py", line 982, in sca
if not hasattr(ax.figure.canvas, "manager"):
AttributeError: 'NoneType' object has no attribute 'figure'
|
AttributeError
|
def color_palette(palette=None, n_colors=None, desat=None, as_cmap=False):
"""Return a list of colors or continuous colormap defining a palette.
Possible ``palette`` values include:
- Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind)
- Name of matplotlib colormap
- 'husl' or 'hls'
- 'ch:<cubehelix arguments>'
- 'light:<color>', 'dark:<color>', 'blend:<color>,<color>',
- A sequence of colors in any format matplotlib accepts
Calling this function with ``palette=None`` will return the current
matplotlib color cycle.
This function can also be used in a ``with`` statement to temporarily
set the color cycle for a plot or set of plots.
See the :ref:`tutorial <palette_tutorial>` for more information.
Parameters
----------
palette: None, string, or sequence, optional
Name of palette or None to return current palette. If a sequence, input
colors are used but possibly cycled and desaturated.
n_colors : int, optional
Number of colors in the palette. If ``None``, the default will depend
on how ``palette`` is specified. Named palettes default to 6 colors,
but grabbing the current palette or passing in a list of colors will
not change the number of colors unless this is specified. Asking for
more colors than exist in the palette will cause it to cycle. Ignored
when ``as_cmap`` is True.
desat : float, optional
Proportion to desaturate each color by.
as_cmap : bool
If True, return a :class:`matplotlib.colors.Colormap`.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
set_palette : Set the default color cycle for all plots.
set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to
colors from one of the seaborn palettes.
Examples
--------
.. include:: ../docstrings/color_palette.rst
"""
if palette is None:
palette = get_color_cycle()
if n_colors is None:
n_colors = len(palette)
elif not isinstance(palette, str):
palette = palette
if n_colors is None:
n_colors = len(palette)
else:
if n_colors is None:
# Use all colors in a qualitative palette or 6 of another kind
n_colors = QUAL_PALETTE_SIZES.get(palette, 6)
if palette in SEABORN_PALETTES:
# Named "seaborn variant" of matplotlib default color cycle
palette = SEABORN_PALETTES[palette]
elif palette == "hls":
# Evenly spaced colors in cylindrical RGB space
palette = hls_palette(n_colors, as_cmap=as_cmap)
elif palette == "husl":
# Evenly spaced colors in cylindrical Lab space
palette = husl_palette(n_colors, as_cmap=as_cmap)
elif palette.lower() == "jet":
# Paternalism
raise ValueError("No.")
elif palette.startswith("ch:"):
# Cubehelix palette with params specified in string
args, kwargs = _parse_cubehelix_args(palette)
palette = cubehelix_palette(n_colors, *args, **kwargs, as_cmap=as_cmap)
elif palette.startswith("light:"):
# light palette to color specified in string
_, color = palette.split(":")
reverse = color.endswith("_r")
if reverse:
color = color[:-2]
palette = light_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)
elif palette.startswith("dark:"):
# light palette to color specified in string
_, color = palette.split(":")
reverse = color.endswith("_r")
if reverse:
color = color[:-2]
palette = dark_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)
elif palette.startswith("blend:"):
# blend palette between colors specified in string
_, colors = palette.split(":")
colors = colors.split(",")
palette = blend_palette(colors, n_colors, as_cmap=as_cmap)
else:
try:
# Perhaps a named matplotlib colormap?
palette = mpl_palette(palette, n_colors, as_cmap=as_cmap)
except ValueError:
raise ValueError("%s is not a valid palette name" % palette)
if desat is not None:
palette = [desaturate(c, desat) for c in palette]
if not as_cmap:
# Always return as many colors as we asked for
pal_cycle = cycle(palette)
palette = [next(pal_cycle) for _ in range(n_colors)]
# Always return in r, g, b tuple format
try:
palette = map(mpl.colors.colorConverter.to_rgb, palette)
palette = _ColorPalette(palette)
except ValueError:
raise ValueError(f"Could not generate a palette for {palette}")
return palette
|
def color_palette(palette=None, n_colors=None, desat=None, as_cmap=False):
"""Return a list of colors or continuous colormap defining a palette.
Possible ``palette`` values include:
- Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind)
- Name of matplotlib colormap
- 'husl' or 'hsl'
- 'ch:<cubehelix arguments>'
- 'light:<color>', 'dark:<color>', 'blend:<color>,<color>',
- A sequence of colors in any format matplotlib accepts
Calling this function with ``palette=None`` will return the current
matplotlib color cycle.
This function can also be used in a ``with`` statement to temporarily
set the color cycle for a plot or set of plots.
See the :ref:`tutorial <palette_tutorial>` for more information.
Parameters
----------
palette: None, string, or sequence, optional
Name of palette or None to return current palette. If a sequence, input
colors are used but possibly cycled and desaturated.
n_colors : int, optional
Number of colors in the palette. If ``None``, the default will depend
on how ``palette`` is specified. Named palettes default to 6 colors,
but grabbing the current palette or passing in a list of colors will
not change the number of colors unless this is specified. Asking for
more colors than exist in the palette will cause it to cycle. Ignored
when ``as_cmap`` is True.
desat : float, optional
Proportion to desaturate each color by.
as_cmap : bool
If True, return a :class:`matplotlib.colors.Colormap`.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
set_palette : Set the default color cycle for all plots.
set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to
colors from one of the seaborn palettes.
Examples
--------
.. include:: ../docstrings/color_palette.rst
"""
if palette is None:
palette = get_color_cycle()
if n_colors is None:
n_colors = len(palette)
elif not isinstance(palette, str):
palette = palette
if n_colors is None:
n_colors = len(palette)
else:
if n_colors is None:
# Use all colors in a qualitative palette or 6 of another kind
n_colors = QUAL_PALETTE_SIZES.get(palette, 6)
if palette in SEABORN_PALETTES:
# Named "seaborn variant" of matplotlib default color cycle
palette = SEABORN_PALETTES[palette]
elif palette == "hls":
# Evenly spaced colors in cylindrical RGB space
palette = hls_palette(n_colors, as_cmap=as_cmap)
elif palette == "husl":
# Evenly spaced colors in cylindrical Lab space
palette = husl_palette(n_colors, as_cmap=as_cmap)
elif palette.lower() == "jet":
# Paternalism
raise ValueError("No.")
elif palette.startswith("ch:"):
# Cubehelix palette with params specified in string
args, kwargs = _parse_cubehelix_args(palette)
palette = cubehelix_palette(n_colors, *args, **kwargs, as_cmap=as_cmap)
elif palette.startswith("light:"):
# light palette to color specified in string
_, color = palette.split(":")
reverse = color.endswith("_r")
if reverse:
color = color[:-2]
palette = light_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)
elif palette.startswith("dark:"):
# light palette to color specified in string
_, color = palette.split(":")
reverse = color.endswith("_r")
if reverse:
color = color[:-2]
palette = dark_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap)
elif palette.startswith("blend:"):
# blend palette between colors specified in string
_, colors = palette.split(":")
colors = colors.split(",")
palette = blend_palette(colors, n_colors, as_cmap=as_cmap)
else:
try:
# Perhaps a named matplotlib colormap?
palette = mpl_palette(palette, n_colors, as_cmap=as_cmap)
except ValueError:
raise ValueError("%s is not a valid palette name" % palette)
if desat is not None:
palette = [desaturate(c, desat) for c in palette]
if not as_cmap:
# Always return as many colors as we asked for
pal_cycle = cycle(palette)
palette = [next(pal_cycle) for _ in range(n_colors)]
# Always return in r, g, b tuple format
try:
palette = map(mpl.colors.colorConverter.to_rgb, palette)
palette = _ColorPalette(palette)
except ValueError:
raise ValueError(f"Could not generate a palette for {palette}")
return palette
|
https://github.com/mwaskom/seaborn/issues/2354
|
Traceback (most recent call last):
File "<ipython-input-87-23324450a106>", line 1, in <module>
sns.pairplot(p, diag_kind=None, corner=True)
File "c:\program files\python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1974, in pairplot
plotter(scatterplot, **plot_kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1250, in map
self._map_bivariate(func, indices, **kwargs)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1434, in _map_bivariate
self._plot_bivariate(x_var, y_var, ax, func, **kws)
File "c:\program files\python38\lib\site-packages\seaborn\axisgrid.py", line 1446, in _plot_bivariate
plt.sca(ax)
File "C:\Users\tgentils\AppData\Roaming\Python\Python38\site-packages\matplotlib\pyplot.py", line 982, in sca
if not hasattr(ax.figure.canvas, "manager"):
AttributeError: 'NoneType' object has no attribute 'figure'
|
AttributeError
|
def set(self, **kwargs):
"""Set attributes on each subplot Axes."""
for ax in self.axes.flat:
if ax is not None: # Handle removed axes
ax.set(**kwargs)
return self
|
def set(self, **kwargs):
"""Set attributes on each subplot Axes."""
for ax in self.axes.flat:
ax.set(**kwargs)
return self
|
https://github.com/mwaskom/seaborn/issues/2228
|
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-b993ffaa9ada> in <module>
4 line_kws=dict(color='r'),
5 scatter_kws=dict(alpha=0.1, marker='.'))
----> 6 g.set(xlim=(0, 1), ylim=(0, 1))
~/miniconda3/envs/py37/lib/python3.7/site-packages/seaborn/axisgrid.py in set(self, **kwargs)
26 """Set attributes on each subplot Axes."""
27 for ax in self.axes.flat:
---> 28 ax.set(**kwargs)
29 return self
30
AttributeError: 'NoneType' object has no attribute 'set'
|
AttributeError
|
def _deprecate_positional_args(f):
"""Decorator for methods that issues warnings for positional arguments.
Using the keyword-only argument syntax in pep 3102, arguments after the
* will issue a warning when passed as a positional argument.
Parameters
----------
f : function
function to check arguments on
"""
sig = signature(f)
kwonly_args = []
all_args = []
for name, param in sig.parameters.items():
if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
all_args.append(name)
elif param.kind == Parameter.KEYWORD_ONLY:
kwonly_args.append(name)
@wraps(f)
def inner_f(*args, **kwargs):
extra_args = len(args) - len(all_args)
if extra_args > 0:
plural = "s" if extra_args > 1 else ""
article = "" if plural else "a "
warnings.warn(
"Pass the following variable{} as {}keyword arg{}: {}. "
"From version 0.12, the only valid positional argument "
"will be `data`, and passing other arguments without an "
"explicit keyword will result in an error or misinterpretation.".format(
plural, article, plural, ", ".join(kwonly_args[:extra_args])
),
FutureWarning,
)
kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
return f(**kwargs)
return inner_f
|
def _deprecate_positional_args(f):
"""Decorator for methods that issues warnings for positional arguments.
Using the keyword-only argument syntax in pep 3102, arguments after the
* will issue a warning when passed as a positional argument.
Parameters
----------
f : function
function to check arguments on
"""
sig = signature(f)
kwonly_args = []
all_args = []
for name, param in sig.parameters.items():
if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
all_args.append(name)
elif param.kind == Parameter.KEYWORD_ONLY:
kwonly_args.append(name)
@wraps(f)
def inner_f(*args, **kwargs):
extra_args = len(args) - len(all_args)
if extra_args > 0:
plural = "s" if extra_args > 1 else ""
article = "" if plural else "a "
warnings.warn(
"Pass the following variable{} as {}keyword arg{}: {}. "
"From version 0.12, the only valid positional argument "
"will be `data`, and passing other arguments without an "
"explcit keyword will result in an error or misinterpretation.".format(
plural, article, plural, ", ".join(kwonly_args[:extra_args])
),
FutureWarning,
)
kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
return f(**kwargs)
return inner_f
|
https://github.com/mwaskom/seaborn/issues/2101
|
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
AttributeError: 'float' object has no attribute 'rint'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
60 try:
---> 61 return bound(*args, **kwds)
62 except TypeError:
TypeError: loop of ufunc does not support argument 0 of type float which has no callable rint method
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
AttributeError: 'float' object has no attribute 'rint'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
<ipython-input-76-61b464cca20e> in <module>
----> 1 sns.lineplot(x=[0, 1, 0, 1], y=[0, 1, 0, 2], hue=pd.Series([1, 1, 3, 3], dtype=object))
~/code/seaborn/seaborn/_decorators.py in inner_f(*args, **kwargs)
44 )
45 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46 return f(**kwargs)
47 return inner_f
48
~/code/seaborn/seaborn/relational.py in lineplot(x, y, hue, size, style, data, palette, hue_order, hue_norm, sizes, size_order, size_norm, dashes, markers, style_order, units, estimator, ci, n_boot, seed, sort, err_style, err_kws, legend, ax, **kwargs)
642 ax = plt.gca()
643
--> 644 p.plot(ax, kwargs)
645 return ax
646
~/code/seaborn/seaborn/relational.py in plot(self, ax, kws)
362 self.label_axes(ax)
363 if self.legend:
--> 364 self.add_legend_data(ax)
365 handles, _ = ax.get_legend_handles_labels()
366 if handles:
~/code/seaborn/seaborn/relational.py in add_legend_data(self, ax)
70 locator = mpl.ticker.MaxNLocator(nbins=3)
71 limits = min(self._hue_map.levels), max(self._hue_map.levels)
---> 72 hue_levels, hue_formatted_levels = locator_to_legend_entries(
73 locator, limits, self.plot_data["hue"].dtype
74 )
~/code/seaborn/seaborn/utils.py in locator_to_legend_entries(locator, limits, dtype)
564 # once pinned matplotlib>=3.1.0 with:
565 # formatted_levels = formatter.format_ticks(raw_levels)
--> 566 formatter.set_locs(raw_levels)
567 formatted_levels = [formatter(x) for x in raw_levels]
568
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/matplotlib/ticker.py in set_locs(self, locs)
687 self._compute_offset()
688 self._set_order_of_magnitude()
--> 689 self._set_format()
690
691 def _compute_offset(self):
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/matplotlib/ticker.py in _set_format(self)
789 thresh = 1e-3 * 10 ** loc_range_oom
790 while sigfigs >= 0:
--> 791 if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh:
792 sigfigs -= 1
793 else:
<__array_function__ internals> in round_(*args, **kwargs)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in round_(a, decimals, out)
3597 around : equivalent function; see for details.
3598 """
-> 3599 return around(a, decimals=decimals, out=out)
3600
3601
<__array_function__ internals> in around(*args, **kwargs)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in around(a, decimals, out)
3222
3223 """
-> 3224 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3225
3226
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
68 # Call _wrapit from within the except clause to ensure a potential
69 # exception has a traceback chain.
---> 70 return _wrapit(obj, method, *args, **kwds)
71
72
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapit(obj, method, *args, **kwds)
45 except AttributeError:
46 wrap = None
---> 47 result = getattr(asarray(obj), method)(*args, **kwds)
48 if wrap:
49 if not isinstance(result, mu.ndarray):
TypeError: loop of ufunc does not support argument 0 of type float which has no callable rint method
|
AttributeError
|
def inner_f(*args, **kwargs):
extra_args = len(args) - len(all_args)
if extra_args > 0:
plural = "s" if extra_args > 1 else ""
article = "" if plural else "a "
warnings.warn(
"Pass the following variable{} as {}keyword arg{}: {}. "
"From version 0.12, the only valid positional argument "
"will be `data`, and passing other arguments without an "
"explicit keyword will result in an error or misinterpretation.".format(
plural, article, plural, ", ".join(kwonly_args[:extra_args])
),
FutureWarning,
)
kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
return f(**kwargs)
|
def inner_f(*args, **kwargs):
extra_args = len(args) - len(all_args)
if extra_args > 0:
plural = "s" if extra_args > 1 else ""
article = "" if plural else "a "
warnings.warn(
"Pass the following variable{} as {}keyword arg{}: {}. "
"From version 0.12, the only valid positional argument "
"will be `data`, and passing other arguments without an "
"explcit keyword will result in an error or misinterpretation.".format(
plural, article, plural, ", ".join(kwonly_args[:extra_args])
),
FutureWarning,
)
kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
return f(**kwargs)
|
https://github.com/mwaskom/seaborn/issues/2101
|
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
AttributeError: 'float' object has no attribute 'rint'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
60 try:
---> 61 return bound(*args, **kwds)
62 except TypeError:
TypeError: loop of ufunc does not support argument 0 of type float which has no callable rint method
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
AttributeError: 'float' object has no attribute 'rint'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
<ipython-input-76-61b464cca20e> in <module>
----> 1 sns.lineplot(x=[0, 1, 0, 1], y=[0, 1, 0, 2], hue=pd.Series([1, 1, 3, 3], dtype=object))
~/code/seaborn/seaborn/_decorators.py in inner_f(*args, **kwargs)
44 )
45 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46 return f(**kwargs)
47 return inner_f
48
~/code/seaborn/seaborn/relational.py in lineplot(x, y, hue, size, style, data, palette, hue_order, hue_norm, sizes, size_order, size_norm, dashes, markers, style_order, units, estimator, ci, n_boot, seed, sort, err_style, err_kws, legend, ax, **kwargs)
642 ax = plt.gca()
643
--> 644 p.plot(ax, kwargs)
645 return ax
646
~/code/seaborn/seaborn/relational.py in plot(self, ax, kws)
362 self.label_axes(ax)
363 if self.legend:
--> 364 self.add_legend_data(ax)
365 handles, _ = ax.get_legend_handles_labels()
366 if handles:
~/code/seaborn/seaborn/relational.py in add_legend_data(self, ax)
70 locator = mpl.ticker.MaxNLocator(nbins=3)
71 limits = min(self._hue_map.levels), max(self._hue_map.levels)
---> 72 hue_levels, hue_formatted_levels = locator_to_legend_entries(
73 locator, limits, self.plot_data["hue"].dtype
74 )
~/code/seaborn/seaborn/utils.py in locator_to_legend_entries(locator, limits, dtype)
564 # once pinned matplotlib>=3.1.0 with:
565 # formatted_levels = formatter.format_ticks(raw_levels)
--> 566 formatter.set_locs(raw_levels)
567 formatted_levels = [formatter(x) for x in raw_levels]
568
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/matplotlib/ticker.py in set_locs(self, locs)
687 self._compute_offset()
688 self._set_order_of_magnitude()
--> 689 self._set_format()
690
691 def _compute_offset(self):
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/matplotlib/ticker.py in _set_format(self)
789 thresh = 1e-3 * 10 ** loc_range_oom
790 while sigfigs >= 0:
--> 791 if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh:
792 sigfigs -= 1
793 else:
<__array_function__ internals> in round_(*args, **kwargs)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in round_(a, decimals, out)
3597 around : equivalent function; see for details.
3598 """
-> 3599 return around(a, decimals=decimals, out=out)
3600
3601
<__array_function__ internals> in around(*args, **kwargs)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in around(a, decimals, out)
3222
3223 """
-> 3224 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3225
3226
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
68 # Call _wrapit from within the except clause to ensure a potential
69 # exception has a traceback chain.
---> 70 return _wrapit(obj, method, *args, **kwds)
71
72
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapit(obj, method, *args, **kwds)
45 except AttributeError:
46 wrap = None
---> 47 result = getattr(asarray(obj), method)(*args, **kwds)
48 if wrap:
49 if not isinstance(result, mu.ndarray):
TypeError: loop of ufunc does not support argument 0 of type float which has no callable rint method
|
AttributeError
|
def add_legend_data(self, ax):
"""Add labeled artists to represent the different plot semantics."""
verbosity = self.legend
if verbosity not in ["brief", "full"]:
err = "`legend` must be 'brief', 'full', or False"
raise ValueError(err)
legend_kwargs = {}
keys = []
title_kws = dict(color="w", s=0, linewidth=0, marker="", dashes="")
def update(var_name, val_name, **kws):
key = var_name, val_name
if key in legend_kwargs:
legend_kwargs[key].update(**kws)
else:
keys.append(key)
legend_kwargs[key] = dict(**kws)
# -- Add a legend for hue semantics
if verbosity == "brief" and self._hue_map.map_type == "numeric":
if isinstance(self._hue_map.norm, mpl.colors.LogNorm):
locator = mpl.ticker.LogLocator(numticks=3)
else:
locator = mpl.ticker.MaxNLocator(nbins=3)
limits = min(self._hue_map.levels), max(self._hue_map.levels)
hue_levels, hue_formatted_levels = locator_to_legend_entries(
locator, limits, self.plot_data["hue"].infer_objects().dtype
)
elif self._hue_map.levels is None:
hue_levels = hue_formatted_levels = []
else:
hue_levels = hue_formatted_levels = self._hue_map.levels
# Add the hue semantic subtitle
if "hue" in self.variables and self.variables["hue"] is not None:
update((self.variables["hue"], "title"), self.variables["hue"], **title_kws)
# Add the hue semantic labels
for level, formatted_level in zip(hue_levels, hue_formatted_levels):
if level is not None:
color = self._hue_map(level)
update(self.variables["hue"], formatted_level, color=color)
# -- Add a legend for size semantics
if verbosity == "brief" and self._size_map.map_type == "numeric":
# Define how ticks will interpolate between the min/max data values
if isinstance(self._size_map.norm, mpl.colors.LogNorm):
locator = mpl.ticker.LogLocator(numticks=3)
else:
locator = mpl.ticker.MaxNLocator(nbins=3)
# Define the min/max data values
limits = min(self._size_map.levels), max(self._size_map.levels)
size_levels, size_formatted_levels = locator_to_legend_entries(
locator, limits, self.plot_data["size"].infer_objects().dtype
)
elif self._size_map.levels is None:
size_levels = size_formatted_levels = []
else:
size_levels = size_formatted_levels = self._size_map.levels
# Add the size semantic subtitle
if "size" in self.variables and self.variables["size"] is not None:
update((self.variables["size"], "title"), self.variables["size"], **title_kws)
# Add the size semantic labels
for level, formatted_level in zip(size_levels, size_formatted_levels):
if level is not None:
size = self._size_map(level)
update(
self.variables["size"],
formatted_level,
linewidth=size,
s=size,
)
# -- Add a legend for style semantics
# Add the style semantic title
if "style" in self.variables and self.variables["style"] is not None:
update((self.variables["style"], "title"), self.variables["style"], **title_kws)
# Add the style semantic labels
if self._style_map.levels is not None:
for level in self._style_map.levels:
if level is not None:
attrs = self._style_map(level)
update(
self.variables["style"],
level,
marker=attrs.get("marker", ""),
dashes=attrs.get("dashes", ""),
)
func = getattr(ax, self._legend_func)
legend_data = {}
legend_order = []
for key in keys:
_, label = key
kws = legend_kwargs[key]
kws.setdefault("color", ".2")
use_kws = {}
for attr in self._legend_attributes + ["visible"]:
if attr in kws:
use_kws[attr] = kws[attr]
artist = func([], [], label=label, **use_kws)
if self._legend_func == "plot":
artist = artist[0]
legend_data[key] = artist
legend_order.append(key)
self.legend_data = legend_data
self.legend_order = legend_order
|
def add_legend_data(self, ax):
"""Add labeled artists to represent the different plot semantics."""
verbosity = self.legend
if verbosity not in ["brief", "full"]:
err = "`legend` must be 'brief', 'full', or False"
raise ValueError(err)
legend_kwargs = {}
keys = []
title_kws = dict(color="w", s=0, linewidth=0, marker="", dashes="")
def update(var_name, val_name, **kws):
key = var_name, val_name
if key in legend_kwargs:
legend_kwargs[key].update(**kws)
else:
keys.append(key)
legend_kwargs[key] = dict(**kws)
# -- Add a legend for hue semantics
if verbosity == "brief" and self._hue_map.map_type == "numeric":
if isinstance(self._hue_map.norm, mpl.colors.LogNorm):
locator = mpl.ticker.LogLocator(numticks=3)
else:
locator = mpl.ticker.MaxNLocator(nbins=3)
limits = min(self._hue_map.levels), max(self._hue_map.levels)
hue_levels, hue_formatted_levels = locator_to_legend_entries(
locator, limits, self.plot_data["hue"].dtype
)
elif self._hue_map.levels is None:
hue_levels = hue_formatted_levels = []
else:
hue_levels = hue_formatted_levels = self._hue_map.levels
# Add the hue semantic subtitle
if "hue" in self.variables and self.variables["hue"] is not None:
update((self.variables["hue"], "title"), self.variables["hue"], **title_kws)
# Add the hue semantic labels
for level, formatted_level in zip(hue_levels, hue_formatted_levels):
if level is not None:
color = self._hue_map(level)
update(self.variables["hue"], formatted_level, color=color)
# -- Add a legend for size semantics
if verbosity == "brief" and self._size_map.map_type == "numeric":
# Define how ticks will interpolate between the min/max data values
if isinstance(self._size_map.norm, mpl.colors.LogNorm):
locator = mpl.ticker.LogLocator(numticks=3)
else:
locator = mpl.ticker.MaxNLocator(nbins=3)
# Define the min/max data values
limits = min(self._size_map.levels), max(self._size_map.levels)
size_levels, size_formatted_levels = locator_to_legend_entries(
locator, limits, self.plot_data["size"].dtype
)
elif self._size_map.levels is None:
size_levels = size_formatted_levels = []
else:
size_levels = size_formatted_levels = self._size_map.levels
# Add the size semantic subtitle
if "size" in self.variables and self.variables["size"] is not None:
update((self.variables["size"], "title"), self.variables["size"], **title_kws)
# Add the size semantic labels
for level, formatted_level in zip(size_levels, size_formatted_levels):
if level is not None:
size = self._size_map(level)
update(
self.variables["size"],
formatted_level,
linewidth=size,
s=size,
)
# -- Add a legend for style semantics
# Add the style semantic title
if "style" in self.variables and self.variables["style"] is not None:
update((self.variables["style"], "title"), self.variables["style"], **title_kws)
# Add the style semantic labels
if self._style_map.levels is not None:
for level in self._style_map.levels:
if level is not None:
attrs = self._style_map(level)
update(
self.variables["style"],
level,
marker=attrs.get("marker", ""),
dashes=attrs.get("dashes", ""),
)
func = getattr(ax, self._legend_func)
legend_data = {}
legend_order = []
for key in keys:
_, label = key
kws = legend_kwargs[key]
kws.setdefault("color", ".2")
use_kws = {}
for attr in self._legend_attributes + ["visible"]:
if attr in kws:
use_kws[attr] = kws[attr]
artist = func([], [], label=label, **use_kws)
if self._legend_func == "plot":
artist = artist[0]
legend_data[key] = artist
legend_order.append(key)
self.legend_data = legend_data
self.legend_order = legend_order
|
https://github.com/mwaskom/seaborn/issues/2101
|
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
AttributeError: 'float' object has no attribute 'rint'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
60 try:
---> 61 return bound(*args, **kwds)
62 except TypeError:
TypeError: loop of ufunc does not support argument 0 of type float which has no callable rint method
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
AttributeError: 'float' object has no attribute 'rint'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
<ipython-input-76-61b464cca20e> in <module>
----> 1 sns.lineplot(x=[0, 1, 0, 1], y=[0, 1, 0, 2], hue=pd.Series([1, 1, 3, 3], dtype=object))
~/code/seaborn/seaborn/_decorators.py in inner_f(*args, **kwargs)
44 )
45 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46 return f(**kwargs)
47 return inner_f
48
~/code/seaborn/seaborn/relational.py in lineplot(x, y, hue, size, style, data, palette, hue_order, hue_norm, sizes, size_order, size_norm, dashes, markers, style_order, units, estimator, ci, n_boot, seed, sort, err_style, err_kws, legend, ax, **kwargs)
642 ax = plt.gca()
643
--> 644 p.plot(ax, kwargs)
645 return ax
646
~/code/seaborn/seaborn/relational.py in plot(self, ax, kws)
362 self.label_axes(ax)
363 if self.legend:
--> 364 self.add_legend_data(ax)
365 handles, _ = ax.get_legend_handles_labels()
366 if handles:
~/code/seaborn/seaborn/relational.py in add_legend_data(self, ax)
70 locator = mpl.ticker.MaxNLocator(nbins=3)
71 limits = min(self._hue_map.levels), max(self._hue_map.levels)
---> 72 hue_levels, hue_formatted_levels = locator_to_legend_entries(
73 locator, limits, self.plot_data["hue"].dtype
74 )
~/code/seaborn/seaborn/utils.py in locator_to_legend_entries(locator, limits, dtype)
564 # once pinned matplotlib>=3.1.0 with:
565 # formatted_levels = formatter.format_ticks(raw_levels)
--> 566 formatter.set_locs(raw_levels)
567 formatted_levels = [formatter(x) for x in raw_levels]
568
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/matplotlib/ticker.py in set_locs(self, locs)
687 self._compute_offset()
688 self._set_order_of_magnitude()
--> 689 self._set_format()
690
691 def _compute_offset(self):
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/matplotlib/ticker.py in _set_format(self)
789 thresh = 1e-3 * 10 ** loc_range_oom
790 while sigfigs >= 0:
--> 791 if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh:
792 sigfigs -= 1
793 else:
<__array_function__ internals> in round_(*args, **kwargs)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in round_(a, decimals, out)
3597 around : equivalent function; see for details.
3598 """
-> 3599 return around(a, decimals=decimals, out=out)
3600
3601
<__array_function__ internals> in around(*args, **kwargs)
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in around(a, decimals, out)
3222
3223 """
-> 3224 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3225
3226
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
68 # Call _wrapit from within the except clause to ensure a potential
69 # exception has a traceback chain.
---> 70 return _wrapit(obj, method, *args, **kwds)
71
72
~/miniconda3/envs/seaborn-refactor/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapit(obj, method, *args, **kwds)
45 except AttributeError:
46 wrap = None
---> 47 result = getattr(asarray(obj), method)(*args, **kwds)
48 if wrap:
49 if not isinstance(result, mu.ndarray):
TypeError: loop of ufunc does not support argument 0 of type float which has no callable rint method
|
AttributeError
|
def _determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust):
"""Use some heuristics to set good defaults for colorbar and range."""
# plot_data is a np.ma.array instance
calc_data = plot_data.astype(np.float).filled(np.nan)
if vmin is None:
if robust:
vmin = np.nanpercentile(calc_data, 2)
else:
vmin = np.nanmin(calc_data)
if vmax is None:
if robust:
vmax = np.nanpercentile(calc_data, 98)
else:
vmax = np.nanmax(calc_data)
self.vmin, self.vmax = vmin, vmax
# Choose default colormaps if not provided
if cmap is None:
if center is None:
self.cmap = cm.rocket
else:
self.cmap = cm.icefire
elif isinstance(cmap, str):
self.cmap = mpl.cm.get_cmap(cmap)
elif isinstance(cmap, list):
self.cmap = mpl.colors.ListedColormap(cmap)
else:
self.cmap = cmap
# Recenter a divergent colormap
if center is not None:
# Copy bad values
# in mpl<3.2 only masked values are honored with "bad" color spec
# (see https://github.com/matplotlib/matplotlib/pull/14257)
bad = self.cmap(np.ma.masked_invalid([np.nan]))[0]
# under/over values are set for sure when cmap extremes
# do not map to the same color as +-inf
under = self.cmap(-np.inf)
over = self.cmap(np.inf)
under_set = under != self.cmap(0)
over_set = over != self.cmap(self.cmap.N - 1)
vrange = max(vmax - center, center - vmin)
normlize = mpl.colors.Normalize(center - vrange, center + vrange)
cmin, cmax = normlize([vmin, vmax])
cc = np.linspace(cmin, cmax, 256)
self.cmap = mpl.colors.ListedColormap(self.cmap(cc))
self.cmap.set_bad(bad)
if under_set:
self.cmap.set_under(under)
if over_set:
self.cmap.set_over(over)
|
def _determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust):
"""Use some heuristics to set good defaults for colorbar and range."""
# plot_data is a np.ma.array instance
calc_data = plot_data.filled(np.nan)
if vmin is None:
if robust:
vmin = np.nanpercentile(calc_data, 2)
else:
vmin = np.nanmin(calc_data)
if vmax is None:
if robust:
vmax = np.nanpercentile(calc_data, 98)
else:
vmax = np.nanmax(calc_data)
self.vmin, self.vmax = vmin, vmax
# Choose default colormaps if not provided
if cmap is None:
if center is None:
self.cmap = cm.rocket
else:
self.cmap = cm.icefire
elif isinstance(cmap, str):
self.cmap = mpl.cm.get_cmap(cmap)
elif isinstance(cmap, list):
self.cmap = mpl.colors.ListedColormap(cmap)
else:
self.cmap = cmap
# Recenter a divergent colormap
if center is not None:
# Copy bad values
# in mpl<3.2 only masked values are honored with "bad" color spec
# (see https://github.com/matplotlib/matplotlib/pull/14257)
bad = self.cmap(np.ma.masked_invalid([np.nan]))[0]
# under/over values are set for sure when cmap extremes
# do not map to the same color as +-inf
under = self.cmap(-np.inf)
over = self.cmap(np.inf)
under_set = under != self.cmap(0)
over_set = over != self.cmap(self.cmap.N - 1)
vrange = max(vmax - center, center - vmin)
normlize = mpl.colors.Normalize(center - vrange, center + vrange)
cmin, cmax = normlize([vmin, vmax])
cc = np.linspace(cmin, cmax, 256)
self.cmap = mpl.colors.ListedColormap(self.cmap(cc))
self.cmap.set_bad(bad)
if under_set:
self.cmap.set_under(under)
if over_set:
self.cmap.set_over(over)
|
https://github.com/mwaskom/seaborn/issues/2102
|
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~.../venv_mac/lib/python3.8/site-packages/numpy/ma/core.py in _check_fill_value(fill_value, ndtype)
472 try:
--> 473 fill_value = np.array(fill_value, copy=False, dtype=ndtype)
474 except (OverflowError, ValueError):
ValueError: cannot convert float NaN to integer
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-61-c14fb3f470ab> in <module>
1 with sns.axes_style("white"):
2 f, ax = plt.subplots(figsize=(7, 5))
----> 3 ax = sns.heatmap(numbers, mask=mask)
4 # ax = sns.heatmap(numbers)
5
~.../venv_mac/lib/python3.8/site-packages/seaborn/matrix.py in heatmap(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, linewidths, linecolor, cbar, cbar_kws, cbar_ax, square, xticklabels, yticklabels, mask, ax, **kwargs)
533 """
534 # Initialize the plotter object
--> 535 plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt,
536 annot_kws, cbar, cbar_kws, xticklabels,
537 yticklabels, mask)
~.../venv_mac/lib/python3.8/site-packages/seaborn/matrix.py in __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels, yticklabels, mask)
162
163 # Determine good default values for the colormapping
--> 164 self._determine_cmap_params(plot_data, vmin, vmax,
165 cmap, center, robust)
166
~.../venv_mac/lib/python3.8/site-packages/seaborn/matrix.py in _determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust)
196
197 # plot_data is a np.ma.array instance
--> 198 calc_data = plot_data.filled(np.nan)
199 if vmin is None:
200 if robust:
~.../venv_mac/lib/python3.8/site-packages/numpy/ma/core.py in filled(self, fill_value)
3737 fill_value = self.fill_value
3738 else:
-> 3739 fill_value = _check_fill_value(fill_value, self.dtype)
3740
3741 if self is masked_singleton:
~.../venv_mac/lib/python3.8/site-packages/numpy/ma/core.py in _check_fill_value(fill_value, ndtype)
477 # that the passed fill_value is not compatible with the ndtype.
478 err_msg = "Cannot convert fill_value %s to dtype %s"
--> 479 raise TypeError(err_msg % (fill_value, ndtype))
480 return np.array(fill_value)
481
TypeError: Cannot convert fill_value nan to dtype int64
|
ValueError
|
def establish_variables(self, data, **kws):
"""Extract variables from data or use directly."""
self.data = data
# Validate the inputs
any_strings = any([isinstance(v, string_types) for v in kws.values()])
if any_strings and data is None:
raise ValueError("Must pass `data` if using named variables.")
# Set the variables
for var, val in kws.items():
if isinstance(val, string_types):
setattr(self, var, data[val])
elif isinstance(val, list):
setattr(self, var, np.asarray(val))
else:
setattr(self, var, val)
|
def establish_variables(self, data, **kws):
"""Extract variables from data or use directly."""
self.data = data
# Validate the inputs
any_strings = any([isinstance(v, string_types) for v in kws.values()])
if any_strings and data is None:
raise ValueError("Must pass `data` if using named variables.")
# Set the variables
for var, val in kws.items():
if isinstance(val, string_types):
setattr(self, var, data[val])
else:
setattr(self, var, val)
|
https://github.com/mwaskom/seaborn/issues/28
|
<matplotlib.figure.Figure object at 0xbdb0b6c>
Traceback (most recent call last):
File "<ipython-input-4-48c88ed4333f>", line 1, in <module>
sns.regplot(x, y)
File ".../seaborn/plotobjs.py", line 742, in regplot
boots = moss.bootstrap(x, y, func=_bootstrap_reg)
File ".../lib/python2.7/site-packages/moss/statistical.py", line 61, in bootstrap
sample = [a[resampler] for a in args]
TypeError: only integer arrays with one element can be converted to an index
|
TypeError
|
def regplot(
x,
y,
data=None,
corr_func=stats.pearsonr,
func_name=None,
xlabel="",
ylabel="",
ci=95,
size=None,
annotloc=None,
color=None,
reg_kws=None,
scatter_kws=None,
dist_kws=None,
text_kws=None,
):
"""Scatterplot with regreesion line, marginals, and correlation value.
Parameters
----------
x : sequence or string
Independent variable.
y : sequence or string
Dependent variable.
data : dataframe, optional
If dataframe is given, x, and y are interpreted as string keys
for selecting to dataframe column names.
corr_func : callable, optional
Correlation function; expected to take two arrays and return a
numeric or (statistic, pval) tuple.
func_name : string, optional
Use in lieu of function name for fit statistic annotation.
xlabel, ylabel : string, optional
Axis label names if inputs are not Pandas objects or to override.
ci : int or None
Confidence interval for the regression estimate.
size: int
Figure size (will be a square; only need one int).
annotloc : two or three tuple
Specified with (xpos, ypos [, horizontalalignment]).
color : matplotlib color scheme
Color of everything but the regression line; can be overridden by
passing `color` to subfunc kwargs.
{reg, scatter, dist, text}_kws: dicts
Further keyword arguments for the constituent plots.
"""
# Interperet inputs
if data is not None:
if not xlabel:
xlabel = x
if not ylabel:
ylabel = y
x = data[x].values
y = data[y].values
else:
if hasattr(x, "name") and not xlabel:
if x.name is not None:
xlabel = x.name
if hasattr(y, "name") and not ylabel:
if y.name is not None:
ylabel = y.name
x = np.asarray(x)
y = np.asarray(y)
# Set up the figure and axes
size = 6 if size is None else size
fig = plt.figure(figsize=(size, size))
ax_scatter = fig.add_axes([0.05, 0.05, 0.75, 0.75])
ax_x_marg = fig.add_axes([0.05, 0.82, 0.75, 0.13])
ax_y_marg = fig.add_axes([0.82, 0.05, 0.13, 0.75])
# Plot the scatter
if scatter_kws is None:
scatter_kws = {}
if color is not None and "color" not in scatter_kws:
scatter_kws.update(color=color)
marker = scatter_kws.pop("markerstyle", "o")
alpha_maker = stats.norm(0, 100)
alpha = alpha_maker.pdf(len(x)) / alpha_maker.pdf(0)
alpha = max(alpha, 0.1)
alpha = scatter_kws.pop("alpha", alpha)
ax_scatter.plot(x, y, marker, alpha=alpha, mew=0, **scatter_kws)
ax_scatter.set_xlabel(xlabel)
ax_scatter.set_ylabel(ylabel)
# Marginal plots using our distplot function
if dist_kws is None:
dist_kws = {}
if color is not None and "color" not in dist_kws:
dist_kws.update(color=color)
if "legend" not in dist_kws:
dist_kws["legend"] = False
dist_kws["xlabel"] = False
distplot(x, ax=ax_x_marg, **dist_kws)
distplot(y, ax=ax_y_marg, vertical=True, **dist_kws)
for ax in [ax_x_marg, ax_y_marg]:
ax.set_xticklabels([])
ax.set_yticklabels([])
# Regression line plot
xlim = ax_scatter.get_xlim()
a, b = np.polyfit(x, y, 1)
if reg_kws is None:
reg_kws = {}
reg_color = reg_kws.pop("color", "#222222")
ax_scatter.plot(xlim, np.polyval([a, b], xlim), color=reg_color, **reg_kws)
# Bootstrapped regression standard error
if ci is not None:
xx = np.linspace(xlim[0], xlim[1], 100)
def _bootstrap_reg(x, y):
fit = np.polyfit(x, y, 1)
return np.polyval(fit, xx)
boots = moss.bootstrap(x, y, func=_bootstrap_reg)
ci_lims = [50 - ci / 2.0, 50 + ci / 2.0]
ci_band = moss.percentiles(boots, ci_lims, axis=0)
ax_scatter.fill_between(xx, *ci_band, color=reg_color, alpha=0.15)
ax_scatter.set_xlim(xlim)
# Calcluate a fit statistic and p value
if func_name is None:
func_name = corr_func.__name__
out = corr_func(x, y)
try:
s, p = out
msg = "%s: %.3f (p=%.3g%s)" % (func_name, s, p, moss.sig_stars(p))
except TypeError:
s = corr_func(x, y)
msg = "%s: %.3f" % (func_name, s)
if annotloc is None:
xmin, xmax = xlim
x_range = xmax - xmin
# Assume the fit statistic is correlation-esque for some
# intuition on where the fit annotation should go
if s < 0:
xloc, align = xmax - x_range * 0.02, "right"
else:
xloc, align = xmin + x_range * 0.02, "left"
ymin, ymax = ax_scatter.get_ylim()
y_range = ymax - ymin
yloc = ymax - y_range * 0.02
else:
if len(annotloc) == 3:
xloc, yloc, align = annotloc
else:
xloc, yloc = annotloc
align = "left"
if text_kws is None:
text_kws = {}
ax_scatter.text(xloc, yloc, msg, ha=align, va="top", **text_kws)
# Set the axes on the marginal plots
ax_x_marg.set_xlim(ax_scatter.get_xlim())
ax_x_marg.set_yticks([])
ax_y_marg.set_ylim(ax_scatter.get_ylim())
ax_y_marg.set_xticks([])
|
def regplot(
x,
y,
data=None,
corr_func=stats.pearsonr,
func_name=None,
xlabel="",
ylabel="",
ci=95,
size=None,
annotloc=None,
color=None,
reg_kws=None,
scatter_kws=None,
dist_kws=None,
text_kws=None,
):
"""Scatterplot with regreesion line, marginals, and correlation value.
Parameters
----------
x : sequence
independent variables
y : sequence
dependent variables
data : dataframe, optional
if dataframe is given, x, and y are interpreted as
string keys mapping to dataframe column names
corr_func : callable, optional
correlation function; expected to take two arrays
and return a numeric or (statistic, pval) tuple
func_name : string, optional
use for fit statistic annotation in lieu of function name
xlabel, ylabel : string, optional
label names
ci : int or None
confidence interval for the regression line
size: int
figure size (will be a square; only need one int)
annotloc : two or three tuple
(xpos, ypos [, horizontalalignment])
color : matplotlib color scheme
color of everything but the regression line
overridden by passing `color` to subfunc kwargs
{reg, scatter, dist, text}_kws: dicts
further keyword arguments for the constituent plots
"""
# Interperet inputs
if data is not None:
if not any(map(bool, [xlabel, ylabel])):
xlabel, ylabel = x, y
x = np.array(data[x])
y = np.array(data[y])
# Set up the figure and axes
size = 6 if size is None else size
fig = plt.figure(figsize=(size, size))
ax_scatter = fig.add_axes([0.05, 0.05, 0.75, 0.75])
ax_x_marg = fig.add_axes([0.05, 0.82, 0.75, 0.13])
ax_y_marg = fig.add_axes([0.82, 0.05, 0.13, 0.75])
# Plot the scatter
if scatter_kws is None:
scatter_kws = {}
if color is not None and "color" not in scatter_kws:
scatter_kws.update(color=color)
marker = scatter_kws.pop("markerstyle", "o")
alpha_maker = stats.norm(0, 100)
alpha = alpha_maker.pdf(len(x)) / alpha_maker.pdf(0)
alpha = max(alpha, 0.1)
alpha = scatter_kws.pop("alpha", alpha)
ax_scatter.plot(x, y, marker, alpha=alpha, mew=0, **scatter_kws)
ax_scatter.set_xlabel(xlabel)
ax_scatter.set_ylabel(ylabel)
# Marginal plots using our distplot function
if dist_kws is None:
dist_kws = {}
if color is not None and "color" not in dist_kws:
dist_kws.update(color=color)
if "legend" not in dist_kws:
dist_kws["legend"] = False
dist_kws["xlabel"] = False
distplot(x, ax=ax_x_marg, **dist_kws)
distplot(y, ax=ax_y_marg, vertical=True, **dist_kws)
for ax in [ax_x_marg, ax_y_marg]:
ax.set_xticklabels([])
ax.set_yticklabels([])
# Regression line plot
xlim = ax_scatter.get_xlim()
a, b = np.polyfit(x, y, 1)
if reg_kws is None:
reg_kws = {}
reg_color = reg_kws.pop("color", "#222222")
ax_scatter.plot(xlim, np.polyval([a, b], xlim), color=reg_color, **reg_kws)
# Bootstrapped regression standard error
if ci is not None:
xx = np.linspace(xlim[0], xlim[1], 100)
def _bootstrap_reg(x, y):
fit = np.polyfit(x, y, 1)
return np.polyval(fit, xx)
boots = moss.bootstrap(x, y, func=_bootstrap_reg)
ci_lims = [50 - ci / 2.0, 50 + ci / 2.0]
ci_band = moss.percentiles(boots, ci_lims, axis=0)
ax_scatter.fill_between(xx, *ci_band, color=reg_color, alpha=0.15)
ax_scatter.set_xlim(xlim)
# Calcluate a fit statistic and p value
if func_name is None:
func_name = corr_func.__name__
out = corr_func(x, y)
try:
s, p = out
msg = "%s: %.3f (p=%.3g%s)" % (func_name, s, p, moss.sig_stars(p))
except TypeError:
s = corr_func(x, y)
msg = "%s: %.3f" % (func_name, s)
if annotloc is None:
xmin, xmax = xlim
x_range = xmax - xmin
# Assume the fit statistic is correlation-esque for some
# intuition on where the fit annotation should go
if s < 0:
xloc, align = xmax - x_range * 0.02, "right"
else:
xloc, align = xmin + x_range * 0.02, "left"
ymin, ymax = ax_scatter.get_ylim()
y_range = ymax - ymin
yloc = ymax - y_range * 0.02
else:
if len(annotloc) == 3:
xloc, yloc, align = annotloc
else:
xloc, yloc = annotloc
align = "left"
if text_kws is None:
text_kws = {}
ax_scatter.text(xloc, yloc, msg, ha=align, va="top", **text_kws)
# Set the axes on the marginal plots
ax_x_marg.set_xlim(ax_scatter.get_xlim())
ax_x_marg.set_yticks([])
ax_y_marg.set_ylim(ax_scatter.get_ylim())
ax_y_marg.set_xticks([])
|
https://github.com/mwaskom/seaborn/issues/28
|
<matplotlib.figure.Figure object at 0xbdb0b6c>
Traceback (most recent call last):
File "<ipython-input-4-48c88ed4333f>", line 1, in <module>
sns.regplot(x, y)
File ".../seaborn/plotobjs.py", line 742, in regplot
boots = moss.bootstrap(x, y, func=_bootstrap_reg)
File ".../lib/python2.7/site-packages/moss/statistical.py", line 61, in bootstrap
sample = [a[resampler] for a in args]
TypeError: only integer arrays with one element can be converted to an index
|
TypeError
|
def violinplot(
vals,
groupby=None,
inner="box",
color=None,
positions=None,
names=None,
order=None,
bw="scott",
widths=0.8,
alpha=None,
saturation=0.7,
join_rm=False,
gridsize=100,
cut=3,
inner_kws=None,
ax=None,
vert=True,
**kwargs,
):
"""Create a violin plot (a combination of boxplot and kernel density plot).
Parameters
----------
vals : DataFrame, Series, 2D array, or list of vectors.
Data for plot. DataFrames and 2D arrays are assumed to be "wide" with
each column mapping to a box. Lists of data are assumed to have one
element per box. Can also provide one long Series in conjunction with
a grouping element as the `groupy` parameter to reshape the data into
several violins. Otherwise 1D data will produce a single violins.
groupby : grouping object
If `vals` is a Series, this is used to group into boxes by calling
pd.groupby(vals, groupby).
inner : {'box' | 'stick' | 'points'}
Plot quartiles or individual sample values inside violin.
color : mpl color, sequence of colors, or seaborn palette name
Inner violin colors
positions : number or sequence of numbers
Position of first violin or positions of each violin.
names : list of strings, optional
Names to plot on x axis; otherwise plots numbers. This will override
names inferred from Pandas inputs.
order : list of strings, optional
If vals is a Pandas object with name information, you can control the
order of the plot by providing the violin names in your preferred
order.
bw : {'scott' | 'silverman' | scalar}
Name of reference method to determine kernel size, or size as a
scalar.
widths : float
Width of each violin at maximum density.
alpha : float, optional
Transparancy of violin fill.
saturation : float, 0-1
Saturation relative to the fully-saturated color. Large patches tend
to look better at lower saturations, so this dims the palette colors
a bit by default.
join_rm : boolean, optional
If True, positions in the input arrays are treated as repeated
measures and are joined with a line plot.
gridsize : int
Number of discrete gridpoints to evaluate the density on.
cut : scalar
Draw the estimate to cut * bw from the extreme data points.
inner_kws : dict, optional
Keyword arugments for inner plot.
ax : matplotlib axis, optional
Axis to plot on, otherwise grab current axis.
vert : boolean, optional
If true (default), draw vertical plots; otherwise, draw horizontal
ones.
kwargs : additional parameters to fill_betweenx
Returns
-------
ax : matplotlib axis
Axis with violin plot.
"""
if ax is None:
ax = plt.gca()
# Reshape and find labels for the plot
vals, xlabel, ylabel, names = _box_reshape(vals, groupby, names, order)
# Sort out the plot colors
colors, gray = _box_colors(vals, color, saturation)
# Initialize the kwarg dict for the inner plot
if inner_kws is None:
inner_kws = {}
inner_kws.setdefault("alpha", 0.6 if inner == "points" else 1)
inner_kws["alpha"] *= 1 if alpha is None else alpha
inner_kws.setdefault("color", gray)
inner_kws.setdefault("marker", "." if inner == "points" else "")
lw = inner_kws.pop("lw", 1.5 if inner == "box" else 0.8)
inner_kws.setdefault("linewidth", lw)
# Find where the violins are going
if positions is None:
positions = np.arange(1, len(vals) + 1)
elif not hasattr(positions, "__iter__"):
positions = np.arange(positions, len(vals) + positions)
# Set the default linewidth if not provided in kwargs
try:
lw = kwargs[({"lw", "linewidth"} & set(kwargs)).pop()]
except KeyError:
lw = 1.5
# Iterate over the variables
for i, a in enumerate(vals):
x = positions[i]
# If we only have a single value, plot a horizontal line
if len(np.unique(a)) == 1:
y = a[0]
if vert:
ax.plot([x - widths / 2, x + widths / 2], [y, y], **inner_kws)
else:
ax.plot([y, y], [x - widths / 2, x + widths / 2], **inner_kws)
continue
# Fit the KDE
try:
kde = stats.gaussian_kde(a, bw)
except TypeError:
kde = stats.gaussian_kde(a)
if bw != "scott": # scipy default
msg = (
"Ignoring bandwidth choice, "
"please upgrade scipy to use a different bandwidth."
)
warnings.warn(msg, UserWarning)
# Determine the support region
if isinstance(bw, str):
bw_name = "scotts" if bw == "scott" else bw
_bw = getattr(kde, "%s_factor" % bw_name)() * a.std(ddof=1)
else:
_bw = bw
y = _kde_support(a, _bw, gridsize, cut, (-np.inf, np.inf))
dens = kde.evaluate(y)
scl = 1 / (dens.max() / (widths / 2))
dens *= scl
# Draw the violin. If vert (default), we will use ``ax.plot`` in the
# standard way; otherwise, we invert x,y.
# For this, define a simple wrapper ``ax_plot``
color = colors[i]
if vert:
ax.fill_betweenx(y, x - dens, x + dens, alpha=alpha, color=color)
def ax_plot(x, y, *args, **kwargs):
ax.plot(x, y, *args, **kwargs)
else:
ax.fill_between(y, x - dens, x + dens, alpha=alpha, color=color)
def ax_plot(x, y, *args, **kwargs):
ax.plot(y, x, *args, **kwargs)
if inner == "box":
for quant in percentiles(a, [25, 75]):
q_x = kde.evaluate(quant) * scl
q_x = [x - q_x, x + q_x]
ax_plot(q_x, [quant, quant], linestyle=":", **inner_kws)
med = np.median(a)
m_x = kde.evaluate(med) * scl
m_x = [x - m_x, x + m_x]
ax_plot(m_x, [med, med], linestyle="--", **inner_kws)
elif inner == "stick":
x_vals = kde.evaluate(a) * scl
x_vals = [x - x_vals, x + x_vals]
ax_plot(x_vals, [a, a], linestyle="-", **inner_kws)
elif inner == "points":
x_vals = [x for _ in a]
ax_plot(x_vals, a, mew=0, linestyle="", **inner_kws)
for side in [-1, 1]:
ax_plot((side * dens) + x, y, c=gray, lw=lw)
# Draw the repeated measure bridges
if join_rm:
ax.plot(range(1, len(vals) + 1), vals, color=inner_kws["color"], alpha=2.0 / 3)
# Add in semantic labels
if names is not None:
if len(vals) != len(names):
raise ValueError("Length of names list must match nuber of bins")
names = list(names)
if vert:
# Add in semantic labels
ax.set_xticks(positions)
ax.set_xlim(positions[0] - 0.5, positions[-1] + 0.5)
ax.set_xticklabels(names)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
else:
# Add in semantic labels
ax.set_yticks(positions)
ax.set_yticklabels(names)
ax.set_ylim(positions[0] - 0.5, positions[-1] + 0.5)
if ylabel is not None:
ax.set_ylabel(xlabel)
if xlabel is not None:
ax.set_xlabel(ylabel)
ax.xaxis.grid(False)
return ax
|
def violinplot(
vals,
groupby=None,
inner="box",
color=None,
positions=None,
names=None,
order=None,
bw="scott",
widths=0.8,
alpha=None,
saturation=0.7,
join_rm=False,
gridsize=100,
cut=3,
inner_kws=None,
ax=None,
vert=True,
**kwargs,
):
"""Create a violin plot (a combination of boxplot and kernel density plot).
Parameters
----------
vals : DataFrame, Series, 2D array, or list of vectors.
Data for plot. DataFrames and 2D arrays are assumed to be "wide" with
each column mapping to a box. Lists of data are assumed to have one
element per box. Can also provide one long Series in conjunction with
a grouping element as the `groupy` parameter to reshape the data into
several violins. Otherwise 1D data will produce a single violins.
groupby : grouping object
If `vals` is a Series, this is used to group into boxes by calling
pd.groupby(vals, groupby).
inner : {'box' | 'stick' | 'points'}
Plot quartiles or individual sample values inside violin.
color : mpl color, sequence of colors, or seaborn palette name
Inner violin colors
positions : number or sequence of numbers
Position of first violin or positions of each violin.
names : list of strings, optional
Names to plot on x axis; otherwise plots numbers. This will override
names inferred from Pandas inputs.
order : list of strings, optional
If vals is a Pandas object with name information, you can control the
order of the plot by providing the violin names in your preferred
order.
bw : {'scott' | 'silverman' | scalar}
Name of reference method to determine kernel size, or size as a
scalar.
widths : float
Width of each violin at maximum density.
alpha : float, optional
Transparancy of violin fill.
saturation : float, 0-1
Saturation relative to the fully-saturated color. Large patches tend
to look better at lower saturations, so this dims the palette colors
a bit by default.
join_rm : boolean, optional
If True, positions in the input arrays are treated as repeated
measures and are joined with a line plot.
gridsize : int
Number of discrete gridpoints to evaluate the density on.
cut : scalar
Draw the estimate to cut * bw from the extreme data points.
inner_kws : dict, optional
Keyword arugments for inner plot.
ax : matplotlib axis, optional
Axis to plot on, otherwise grab current axis.
vert : boolean, optional
If true (default), draw vertical plots; otherwise, draw horizontal
ones.
kwargs : additional parameters to fill_betweenx
Returns
-------
ax : matplotlib axis
Axis with violin plot.
"""
if ax is None:
ax = plt.gca()
# Reshape and find labels for the plot
vals, xlabel, ylabel, names = _box_reshape(vals, groupby, names, order)
# Sort out the plot colors
colors, gray = _box_colors(vals, color, saturation)
# Initialize the kwarg dict for the inner plot
if inner_kws is None:
inner_kws = {}
inner_kws.setdefault("alpha", 0.6 if inner == "points" else 1)
inner_kws["alpha"] *= 1 if alpha is None else alpha
inner_kws.setdefault("color", gray)
inner_kws.setdefault("marker", "." if inner == "points" else "")
lw = inner_kws.pop("lw", 1.5 if inner == "box" else 0.8)
inner_kws.setdefault("linewidth", lw)
# Find where the violins are going
if positions is None:
positions = np.arange(1, len(vals) + 1)
elif not hasattr(positions, "__iter__"):
positions = np.arange(positions, len(vals) + positions)
# Set the default linewidth if not provided in kwargs
try:
lw = kwargs[({"lw", "linewidth"} & set(kwargs)).pop()]
except KeyError:
lw = 1.5
# Iterate over the variables
for i, a in enumerate(vals):
x = positions[i]
# If we only have a single value, plot a horizontal line
if len(a) == 1:
y = a[0]
if vert:
ax.plot([x - widths / 2, x + widths / 2], [y, y], **inner_kws)
else:
ax.plot([y, y], [x - widths / 2, x + widths / 2], **inner_kws)
continue
# Fit the KDE
try:
kde = stats.gaussian_kde(a, bw)
except TypeError:
kde = stats.gaussian_kde(a)
if bw != "scott": # scipy default
msg = (
"Ignoring bandwidth choice, "
"please upgrade scipy to use a different bandwidth."
)
warnings.warn(msg, UserWarning)
# Determine the support region
if isinstance(bw, str):
bw_name = "scotts" if bw == "scott" else bw
_bw = getattr(kde, "%s_factor" % bw_name)() * a.std(ddof=1)
else:
_bw = bw
y = _kde_support(a, _bw, gridsize, cut, (-np.inf, np.inf))
dens = kde.evaluate(y)
scl = 1 / (dens.max() / (widths / 2))
dens *= scl
# Draw the violin. If vert (default), we will use ``ax.plot`` in the
# standard way; otherwise, we invert x,y.
# For this, define a simple wrapper ``ax_plot``
color = colors[i]
if vert:
ax.fill_betweenx(y, x - dens, x + dens, alpha=alpha, color=color)
def ax_plot(x, y, *args, **kwargs):
ax.plot(x, y, *args, **kwargs)
else:
ax.fill_between(y, x - dens, x + dens, alpha=alpha, color=color)
def ax_plot(x, y, *args, **kwargs):
ax.plot(y, x, *args, **kwargs)
if inner == "box":
for quant in percentiles(a, [25, 75]):
q_x = kde.evaluate(quant) * scl
q_x = [x - q_x, x + q_x]
ax_plot(q_x, [quant, quant], linestyle=":", **inner_kws)
med = np.median(a)
m_x = kde.evaluate(med) * scl
m_x = [x - m_x, x + m_x]
ax_plot(m_x, [med, med], linestyle="--", **inner_kws)
elif inner == "stick":
x_vals = kde.evaluate(a) * scl
x_vals = [x - x_vals, x + x_vals]
ax_plot(x_vals, [a, a], linestyle="-", **inner_kws)
elif inner == "points":
x_vals = [x for _ in a]
ax_plot(x_vals, a, mew=0, linestyle="", **inner_kws)
for side in [-1, 1]:
ax_plot((side * dens) + x, y, c=gray, lw=lw)
# Draw the repeated measure bridges
if join_rm:
ax.plot(range(1, len(vals) + 1), vals, color=inner_kws["color"], alpha=2.0 / 3)
# Add in semantic labels
if names is not None:
if len(vals) != len(names):
raise ValueError("Length of names list must match nuber of bins")
names = list(names)
if vert:
# Add in semantic labels
ax.set_xticks(positions)
ax.set_xlim(positions[0] - 0.5, positions[-1] + 0.5)
ax.set_xticklabels(names)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
else:
# Add in semantic labels
ax.set_yticks(positions)
ax.set_yticklabels(names)
ax.set_ylim(positions[0] - 0.5, positions[-1] + 0.5)
if ylabel is not None:
ax.set_ylabel(xlabel)
if xlabel is not None:
ax.set_xlabel(ylabel)
ax.xaxis.grid(False)
return ax
|
https://github.com/mwaskom/seaborn/issues/368
|
In [101]: data = [np.random.randn(100), [.83,.83,.83]]
In [102]: sns.violinplot(data)
---------------------------------------------------------------------------
LinAlgError Traceback (most recent call last)
<ipython-input-102-d0b7a65512ee> in <module>()
----> 1 sns.violinplot(data)
/usr/local/lib/python2.7/site-packages/seaborn/distributions.pyc in violinplot(vals, groupby, inner, color, positions, names, order, bw, widths, alpha, saturation, join_rm, gridsize, cut, inner_kws, ax, vert, **kwargs)
377 # Fit the KDE
378 try:
--> 379 kde = stats.gaussian_kde(a, bw)
380 except TypeError:
381 kde = stats.gaussian_kde(a)
/usr/local/lib/python2.7/site-packages/scipy/stats/kde.pyc in __init__(self, dataset, bw_method)
186
187 self.d, self.n = self.dataset.shape
--> 188 self.set_bandwidth(bw_method=bw_method)
189
190 def evaluate(self, points):
/usr/local/lib/python2.7/site-packages/scipy/stats/kde.pyc in set_bandwidth(self, bw_method)
496 raise ValueError(msg)
497
--> 498 self._compute_covariance()
499
500 def _compute_covariance(self):
/usr/local/lib/python2.7/site-packages/scipy/stats/kde.pyc in _compute_covariance(self)
507 self._data_covariance = atleast_2d(np.cov(self.dataset, rowvar=1,
508 bias=False))
--> 509 self._data_inv_cov = linalg.inv(self._data_covariance)
510
511 self.covariance = self._data_covariance * self.factor**2
/usr/local/lib/python2.7/site-packages/scipy/linalg/basic.pyc in inv(a, overwrite_a, check_finite)
381 inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1)
382 if info > 0:
--> 383 raise LinAlgError("singular matrix")
384 if info < 0:
385 raise ValueError('illegal value in %d-th argument of internal '
LinAlgError: singular matrix
|
LinAlgError
|
def url_for(self, view_name, **kwargs):
"""
Same as :func:`sanic.Sanic.url_for`, but automatically determine
`scheme` and `netloc` base on the request. Since this method is aiming
to generate correct schema & netloc, `_external` is implied.
:param kwargs: takes same parameters as in :func:`sanic.Sanic.url_for`
:return: an absolute url to the given view
:rtype: str
"""
# Full URL SERVER_NAME can only be handled in app.url_for
try:
if "//" in self.app.config.SERVER_NAME:
return self.app.url_for(view_name, _external=True, **kwargs)
except AttributeError:
pass
scheme = self.scheme
host = self.server_name
port = self.server_port
if (scheme.lower() in ("http", "ws") and port == 80) or (
scheme.lower() in ("https", "wss") and port == 443
):
netloc = host
else:
netloc = "{}:{}".format(host, port)
return self.app.url_for(
view_name, _external=True, _scheme=scheme, _server=netloc, **kwargs
)
|
def url_for(self, view_name, **kwargs):
"""
Same as :func:`sanic.Sanic.url_for`, but automatically determine
`scheme` and `netloc` base on the request. Since this method is aiming
to generate correct schema & netloc, `_external` is implied.
:param kwargs: takes same parameters as in :func:`sanic.Sanic.url_for`
:return: an absolute url to the given view
:rtype: str
"""
# Full URL SERVER_NAME can only be handled in app.url_for
if "//" in self.app.config.SERVER_NAME:
return self.app.url_for(view_name, _external=True, **kwargs)
scheme = self.scheme
host = self.server_name
port = self.server_port
if (scheme.lower() in ("http", "ws") and port == 80) or (
scheme.lower() in ("https", "wss") and port == 443
):
netloc = host
else:
netloc = "{}:{}".format(host, port)
return self.app.url_for(
view_name, _external=True, _scheme=scheme, _server=netloc, **kwargs
)
|
https://github.com/sanic-org/sanic/issues/1707
|
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/sanic/app.py", line 942, in handle_request
response = await response
File "/app/tsauth/views/activate.py", line 41, in init_activate
request=request)
File "/usr/local/lib/python3.7/site-packages/mako/template.py", line 476, in render
return runtime._render(self, self.callable_, args, data)
File "/usr/local/lib/python3.7/site-packages/mako/runtime.py", line 883, in _render
**_kwargs_for_callable(callable_, data)
File "/usr/local/lib/python3.7/site-packages/mako/runtime.py", line 920, in _render_context
_exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
File "/usr/local/lib/python3.7/site-packages/mako/runtime.py", line 947, in _exec_template
callable_(context, *args, **kwargs)
File "transaction_mako", line 60, in render_body
File "/usr/local/lib/python3.7/site-packages/sanic/request.py", line 522, in url_for
if "//" in self.app.config.SERVER_NAME:
File "/usr/local/lib/python3.7/site-packages/sanic/config.py", line 54, in __getattr__
raise AttributeError("Config has no '{}'".format(ke.args[0]))
AttributeError: Config has no 'SERVER_NAME'
[2019-10-23 12:38:09 +0000] - (sanic.access)[INFO][<redacted>:33328]: GET <redacted> 500 144
10/23/2019 12:38:09 PM ERROR Exception occurred while handling uri: '<redacted>'
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/sanic/config.py", line 52, in __getattr__
return self[attr]
KeyError: 'SERVER_NAME'
|
AttributeError
|
def __init__(
self,
name=None,
router=None,
error_handler=None,
load_env=True,
request_class=None,
strict_slashes=False,
log_config=None,
configure_logging=True,
):
# Get name from previous stack frame
if name is None:
warnings.warn(
"Sanic(name=None) is deprecated and None value support "
"for `name` will be removed in the next release. "
"Please use Sanic(name='your_application_name') instead.",
DeprecationWarning,
stacklevel=2,
)
frame_records = stack()[1]
name = getmodulename(frame_records[1])
# logging
if configure_logging:
logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)
self.name = name
self.asgi = False
self.router = router or Router()
self.request_class = request_class
self.error_handler = error_handler or ErrorHandler()
self.config = Config(load_env=load_env)
self.request_middleware = deque()
self.response_middleware = deque()
self.blueprints = {}
self._blueprint_order = []
self.configure_logging = configure_logging
self.debug = None
self.sock = None
self.strict_slashes = strict_slashes
self.listeners = defaultdict(list)
self.is_running = False
self.is_request_stream = False
self.websocket_enabled = False
self.websocket_tasks = set()
# Register alternative method names
self.go_fast = self.run
|
def __init__(
self,
name=None,
router=None,
error_handler=None,
load_env=True,
request_class=None,
strict_slashes=False,
log_config=None,
configure_logging=True,
):
# Get name from previous stack frame
if name is None:
frame_records = stack()[1]
name = getmodulename(frame_records[1])
# logging
if configure_logging:
logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)
self.name = name
self.asgi = False
self.router = router or Router()
self.request_class = request_class
self.error_handler = error_handler or ErrorHandler()
self.config = Config(load_env=load_env)
self.request_middleware = deque()
self.response_middleware = deque()
self.blueprints = {}
self._blueprint_order = []
self.configure_logging = configure_logging
self.debug = None
self.sock = None
self.strict_slashes = strict_slashes
self.listeners = defaultdict(list)
self.is_running = False
self.is_request_stream = False
self.websocket_enabled = False
self.websocket_tasks = set()
# Register alternative method names
self.go_fast = self.run
|
https://github.com/sanic-org/sanic/issues/1601
|
[2019-06-05 03:32:59 +0000] [10] [ERROR] Exception occurred while handling uri: 'http://localhost:5000/'
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/sanic/app.py", line 906, in handle_request
handler.__name__
File "/usr/local/lib/python3.7/site-packages/sanic/app.py", line 1355, in _build_endpoint_name
return ".".join(parts)
TypeError: sequence item 0: expected str instance, NoneType found
[2019-06-05 03:32:59 +0000] - (sanic.access)[INFO][172.17.0.1:55388]: GET http://localhost:5000/ 500 144
|
TypeError
|
def get_headers(self, version="1.1", keep_alive=False, keep_alive_timeout=None):
# This is all returned in a kind-of funky way
# We tried to make this as fast as possible in pure python
timeout_header = b""
if keep_alive and keep_alive_timeout is not None:
timeout_header = b"Keep-Alive: %d\r\n" % keep_alive_timeout
self.headers["Transfer-Encoding"] = "chunked"
self.headers.pop("Content-Length", None)
self.headers["Content-Type"] = self.headers.get("Content-Type", self.content_type)
headers = self._parse_headers()
if self.status is 200:
status = b"OK"
else:
status = STATUS_CODES.get(self.status)
return (b"HTTP/%b %d %b\r\n%b%b\r\n") % (
version.encode(),
self.status,
status,
timeout_header,
headers,
)
|
def get_headers(self, version="1.1", keep_alive=False, keep_alive_timeout=None):
# This is all returned in a kind-of funky way
# We tried to make this as fast as possible in pure python
timeout_header = b""
if keep_alive and keep_alive_timeout is not None:
timeout_header = b"Keep-Alive: %d\r\n" % keep_alive_timeout
self.headers["Transfer-Encoding"] = "chunked"
self.headers.pop("Content-Length", None)
self.headers["Content-Type"] = self.headers.get("Content-Type", self.content_type)
headers = self._parse_headers()
if self.status is 200:
status = b"OK"
else:
status = http.STATUS_CODES.get(self.status)
return (b"HTTP/%b %d %b\r\n%b%b\r\n") % (
version.encode(),
self.status,
status,
timeout_header,
headers,
)
|
https://github.com/sanic-org/sanic/issues/1323
|
Traceback (most recent call last):
File "/env/lib/python3.6/site-packages/sanic/__main__.py", line 4, in <module>
from sanic.log import logger
File "/env/lib/python3.6/site-packages/sanic/__init__.py", line 1, in <module>
from sanic.app import Sanic
File "/env/lib/python3.6/site-packages/sanic/app.py", line 21, in <module>
from sanic.server import serve, serve_multiple, HttpProtocol, Signal
File "/env/lib/python3.6/site-packages/sanic/server.py", line 31, in <module>
from sanic.request import Request
File "/env/lib/python3.6/site-packages/sanic/request.py", line 6, in <module>
from http.cookies import SimpleCookie
ModuleNotFoundError: No module named 'http.cookies'; 'http' is not a package
|
ModuleNotFoundError
|
def output(self, version="1.1", keep_alive=False, keep_alive_timeout=None):
# This is all returned in a kind-of funky way
# We tried to make this as fast as possible in pure python
timeout_header = b""
if keep_alive and keep_alive_timeout is not None:
timeout_header = b"Keep-Alive: %d\r\n" % keep_alive_timeout
body = b""
if has_message_body(self.status):
body = self.body
self.headers["Content-Length"] = self.headers.get(
"Content-Length", len(self.body)
)
self.headers["Content-Type"] = self.headers.get("Content-Type", self.content_type)
if self.status in (304, 412):
self.headers = remove_entity_headers(self.headers)
headers = self._parse_headers()
if self.status is 200:
status = b"OK"
else:
status = STATUS_CODES.get(self.status, b"UNKNOWN RESPONSE")
return (b"HTTP/%b %d %b\r\nConnection: %b\r\n%b%b\r\n%b") % (
version.encode(),
self.status,
status,
b"keep-alive" if keep_alive else b"close",
timeout_header,
headers,
body,
)
|
def output(self, version="1.1", keep_alive=False, keep_alive_timeout=None):
# This is all returned in a kind-of funky way
# We tried to make this as fast as possible in pure python
timeout_header = b""
if keep_alive and keep_alive_timeout is not None:
timeout_header = b"Keep-Alive: %d\r\n" % keep_alive_timeout
body = b""
if http.has_message_body(self.status):
body = self.body
self.headers["Content-Length"] = self.headers.get(
"Content-Length", len(self.body)
)
self.headers["Content-Type"] = self.headers.get("Content-Type", self.content_type)
if self.status in (304, 412):
self.headers = http.remove_entity_headers(self.headers)
headers = self._parse_headers()
if self.status is 200:
status = b"OK"
else:
status = http.STATUS_CODES.get(self.status, b"UNKNOWN RESPONSE")
return (b"HTTP/%b %d %b\r\nConnection: %b\r\n%b%b\r\n%b") % (
version.encode(),
self.status,
status,
b"keep-alive" if keep_alive else b"close",
timeout_header,
headers,
body,
)
|
https://github.com/sanic-org/sanic/issues/1323
|
Traceback (most recent call last):
File "/env/lib/python3.6/site-packages/sanic/__main__.py", line 4, in <module>
from sanic.log import logger
File "/env/lib/python3.6/site-packages/sanic/__init__.py", line 1, in <module>
from sanic.app import Sanic
File "/env/lib/python3.6/site-packages/sanic/app.py", line 21, in <module>
from sanic.server import serve, serve_multiple, HttpProtocol, Signal
File "/env/lib/python3.6/site-packages/sanic/server.py", line 31, in <module>
from sanic.request import Request
File "/env/lib/python3.6/site-packages/sanic/request.py", line 6, in <module>
from http.cookies import SimpleCookie
ModuleNotFoundError: No module named 'http.cookies'; 'http' is not a package
|
ModuleNotFoundError
|
async def handle_request(self, request, write_callback, stream_callback):
"""Take a request from the HTTP Server and return a response object
to be sent back The HTTP Server only expects a response object, so
exception handling must be done here
:param request: HTTP Request object
:param write_callback: Synchronous response function to be
called with the response as the only argument
:param stream_callback: Coroutine that handles streaming a
StreamingHTTPResponse if produced by the handler.
:return: Nothing
"""
try:
# -------------------------------------------- #
# Request Middleware
# -------------------------------------------- #
request.app = self
response = await self._run_request_middleware(request)
# No middleware results
if not response:
# -------------------------------------------- #
# Execute Handler
# -------------------------------------------- #
# Fetch handler from router
handler, args, kwargs, uri = self.router.get(request)
request.uri_template = uri
if handler is None:
raise ServerError(
("'None' was returned while requesting a handler from the router")
)
# Run response handler
response = handler(request, *args, **kwargs)
if isawaitable(response):
response = await response
except Exception as e:
# -------------------------------------------- #
# Response Generation Failed
# -------------------------------------------- #
try:
response = self.error_handler.response(request, e)
if isawaitable(response):
response = await response
except Exception as e:
if isinstance(e, SanicException):
response = self.error_handler.default(request=request, exception=e)
elif self.debug:
response = HTTPResponse(
"Error while handling error: {}\nStack: {}".format(e, format_exc()),
status=500,
)
else:
response = HTTPResponse(
"An error occurred while handling an error", status=500
)
finally:
# -------------------------------------------- #
# Response Middleware
# -------------------------------------------- #
try:
response = await self._run_response_middleware(request, response)
except BaseException:
error_logger.exception(
"Exception occurred in one of response middleware handlers"
)
# pass the response to the correct callback
if isinstance(response, StreamingHTTPResponse):
await stream_callback(response)
else:
write_callback(response)
|
async def handle_request(self, request, write_callback, stream_callback):
"""Take a request from the HTTP Server and return a response object
to be sent back The HTTP Server only expects a response object, so
exception handling must be done here
:param request: HTTP Request object
:param write_callback: Synchronous response function to be
called with the response as the only argument
:param stream_callback: Coroutine that handles streaming a
StreamingHTTPResponse if produced by the handler.
:return: Nothing
"""
try:
# -------------------------------------------- #
# Request Middleware
# -------------------------------------------- #
request.app = self
response = await self._run_request_middleware(request)
# No middleware results
if not response:
# -------------------------------------------- #
# Execute Handler
# -------------------------------------------- #
# Fetch handler from router
handler, args, kwargs, uri = self.router.get(request)
request.uri_template = uri
if handler is None:
raise ServerError(
("'None' was returned while requesting a handler from the router")
)
# Run response handler
response = handler(request, *args, **kwargs)
if isawaitable(response):
response = await response
except Exception as e:
# -------------------------------------------- #
# Response Generation Failed
# -------------------------------------------- #
try:
response = self.error_handler.response(request, e)
if isawaitable(response):
response = await response
except Exception as e:
if self.debug:
response = HTTPResponse(
"Error while handling error: {}\nStack: {}".format(e, format_exc())
)
else:
response = HTTPResponse("An error occurred while handling an error")
finally:
# -------------------------------------------- #
# Response Middleware
# -------------------------------------------- #
try:
response = await self._run_response_middleware(request, response)
except BaseException:
error_logger.exception(
"Exception occurred in one of response middleware handlers"
)
# pass the response to the correct callback
if isinstance(response, StreamingHTTPResponse):
await stream_callback(response)
else:
write_callback(response)
|
https://github.com/sanic-org/sanic/issues/1042
|
Error while handling error: File not found
Stack: Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/static.py", line 76, in _handler
stats = await stat(file_path)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/coroutines.py", line 213, in coro
res = yield from res
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
FileNotFoundError: [Errno 2] No such file or directory: '/Users/rob/git/GITHUB/zzzz-server/scripts/static/favicon.ico'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/app.py", line 565, in handle_request
response = await response
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/coroutines.py", line 109, in __next__
return self.gen.send(None)
File "/Users/rob/git/GITHUB/zzzz-server/scripts/dummy.py", line 21, in catch_all
raise exception
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/app.py", line 556, in handle_request
response = await response
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/coroutines.py", line 128, in throw
return self.gen.throw(type, value, traceback)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/static.py", line 120, in _handler
relative_url=file_uri)
sanic.exceptions.FileNotFound: File not found
|
FileNotFoundError
|
def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Request
:param exception: Exception to handle
:return: Response object
"""
handler = self.handlers.get(type(exception), self.default)
try:
response = handler(request=request, exception=exception)
except Exception:
self.log(format_exc())
if self.debug:
url = getattr(request, "url", "unknown")
response_message = (
'Exception raised in exception handler "{}" for uri: "{}"\n{}'
).format(handler.__name__, url, format_exc())
log.error(response_message)
return text(response_message, 500)
else:
return text("An error occurred while handling an error", 500)
return response
|
def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Request
:param exception: Exception to handle
:return: Response object
"""
handler = self.handlers.get(type(exception), self.default)
try:
response = handler(request=request, exception=exception)
except Exception:
self.log(format_exc())
if self.debug:
response_message = (
'Exception raised in exception handler "{}" for uri: "{}"\n{}'
).format(handler.__name__, request.url, format_exc())
log.error(response_message)
return text(response_message, 500)
else:
return text("An error occurred while handling an error", 500)
return response
|
https://github.com/sanic-org/sanic/issues/483
|
2017-02-24 07:53:18,845 ERROR Process-22219 MainThread sanic.handlers.log:73 Traceback (most recent call last):
File "/home/kpath/kpath/venv/lib/python3.6/site-packages/sanic/handlers.py", line 54, in response
response = handler(request=request, exception=exception)
File "app.py", line 486, in default
sentry.captureException()
File "/home/kpath/kpath/venv/lib/python3.6/site-packages/raven/base.py", line 799, in captureException
'raven.events.Exception', exc_info=exc_info, **kwargs)
File "/home/kpath/kpath/venv/lib/python3.6/site-packages/raven/base.py", line 615, in capture
elif not self.should_capture(exc_info):
File "/home/kpath/kpath/venv/lib/python3.6/site-packages/raven/base.py", line 803, in should_capture
exc_name = '%s.%s' % (exc_type.__module__, exc_type.__name__)
AttributeError: 'NoneType' object has no attribute '__module__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/kpath/kpath/venv/lib/python3.6/site-packages/sanic/server.py", line 201, in write_error
response = self.error_handler.response(self.request, exception)
File "/home/kpath/kpath/venv/lib/python3.6/site-packages/sanic/handlers.py", line 61, in response
handler.__name__, request.url, format_exc())
AttributeError: 'NoneType' object has no attribute 'url'
2017-02-24 07:53:18,845 ERROR Process-22219 MainThread sanic.server.bail_out:226 Writing error failed, connection closed AttributeError("'NoneType' object has no attribute 'url'",)
|
AttributeError
|
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs):
"""
Perform XMPP Notification
"""
if not self._enabled:
self.logger.warning(
"XMPP Notifications are not supported by this system "
"- install sleekxmpp or slixmpp."
)
return False
# Detect our JID if it isn't otherwise specified
jid = self.jid
password = self.password
if not jid:
if self.user and self.password:
# xmpp://user:password@hostname
jid = "{}@{}".format(self.user, self.host)
else:
# xmpp://password@hostname
jid = self.host
password = self.password if self.password else self.user
# Compute port number
if not self.port:
port = self.default_secure_port if self.secure else self.default_unsecure_port
else:
port = self.port
try:
# Communicate with XMPP.
xmpp_adapter = self._adapter(
host=self.host,
port=port,
secure=self.secure,
verify_certificate=self.verify_certificate,
xep=self.xep,
jid=jid,
password=password,
body=body,
targets=self.targets,
before_message=self.throttle,
logger=self.logger,
)
except ValueError:
# We failed
return False
# Initialize XMPP machinery and begin processing the XML stream.
outcome = xmpp_adapter.process()
return outcome
|
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs):
"""
Perform XMPP Notification
"""
if not self._enabled:
self.logger.warning(
"XMPP Notifications are not supported by this system - install sleekxmpp."
)
return False
# Detect our JID if it isn't otherwise specified
jid = self.jid
password = self.password
if not jid:
if self.user and self.password:
# xmpp://user:password@hostname
jid = "{}@{}".format(self.user, self.host)
else:
# xmpp://password@hostname
jid = self.host
password = self.password if self.password else self.user
# Compute port number
if not self.port:
port = self.default_secure_port if self.secure else self.default_unsecure_port
else:
port = self.port
try:
# Communicate with XMPP.
xmpp_adapter = SleekXmppAdapter(
host=self.host,
port=port,
secure=self.secure,
verify_certificate=self.verify_certificate,
xep=self.xep,
jid=jid,
password=password,
body=body,
targets=self.targets,
before_message=self.throttle,
logger=self.logger,
)
except ValueError:
# We failed
return False
# Initialize XMPP machinery and begin processing the XML stream.
outcome = xmpp_adapter.process()
return outcome
|
https://github.com/caronc/apprise/issues/227
|
2020-04-06 10:04:39,084 - DEBUG - Loaded URL: xmpp://user:password@xmpp.nayr.us/user%40nayr.us?verify=yes&overflow=upstream&xep=30%2C199&format=text
2020-04-06 10:04:39,087 - DEBUG - Loaded Plugin: RFC 6120: Stream Feature: STARTTLS
2020-04-06 10:04:39,087 - DEBUG - Loaded Plugin: RFC 6120: Stream Feature: Resource Binding
2020-04-06 10:04:39,088 - DEBUG - Loaded Plugin: RFC 3920: Stream Feature: Start Session
2020-04-06 10:04:39,089 - DEBUG - Loaded Plugin: RFC 6121: Stream Feature: Roster Versioning
2020-04-06 10:04:39,090 - DEBUG - Loaded Plugin: RFC 6121: Stream Feature: Subscription Pre-Approval
2020-04-06 10:04:39,093 - DEBUG - Loaded Plugin: RFC 6120: Stream Feature: SASL
2020-04-06 10:04:39,095 - DEBUG - Loaded Plugin: XEP-0030: Service Discovery
2020-04-06 10:04:39,096 - DEBUG - Loaded Plugin: XEP-0199: XMPP Ping
2020-04-06 10:04:39,096 - DEBUG - DNS: Querying xmpp.nayr.us for AAAA records.
2020-04-06 10:04:39,099 - DEBUG - DNS: No AAAA records for xmpp.nayr.us
2020-04-06 10:04:39,099 - DEBUG - DNS: Querying xmpp.nayr.us for A records.
2020-04-06 10:04:39,103 - DEBUG - Connecting to 172.16.129.15:5222
2020-04-06 10:04:39,103 - DEBUG - Event triggered: connected
2020-04-06 10:04:39,103 - DEBUG - ==== TRANSITION disconnected -> connected
2020-04-06 10:04:39,104 - DEBUG - Starting HANDLER THREAD
2020-04-06 10:04:39,104 - DEBUG - Loading event runner
2020-04-06 10:04:39,105 - DEBUG - SEND (IMMED): <stream:stream to='xmpp.nayr.us' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' xml:lang='en' version='1.0'>
2020-04-06 10:04:39,113 - DEBUG - RECV: <stream:stream version="1.0" from="xmpp.nayr.us" id="8527860a-fcb1-49d6-a601-89b93dabcaac" xml:lang="en">
2020-04-06 10:04:39,114 - DEBUG - RECV: <stream:features xmlns="http://etherx.jabber.org/streams"><starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"><required /></starttls></stream:features>
2020-04-06 10:04:39,115 - DEBUG - SEND (IMMED): <starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"><required /></starttls>
2020-04-06 10:04:39,117 - DEBUG - RECV: <proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
2020-04-06 10:04:39,117 - DEBUG - Starting TLS
2020-04-06 10:04:39,117 - INFO - Negotiating TLS
2020-04-06 10:04:39,117 - INFO - Using SSL version: TLSv1
2020-04-06 10:04:39,618 - DEBUG - CERT: -----BEGIN CERTIFICATE-----
MIIG9zCCBd+gAwIBAgISAx4xdCT+J2NntCKIHvypzA9sMA0GCSqGSIb3DQEBCwUA
MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD
ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0yMDAzMjUxOTE0MjRaFw0y
MDA2MjMxOTE0MjRaMBIxEDAOBgNVBAMTB25heXIudXMwggIiMA0GCSqGSIb3DQEB
AQUAA4ICDwAwggIKAoICAQDdStSc5KAsDovVgFF7gqnCVgUXtWxmnO/5kr+0ydAD
yvwR825vZDHywv21J4Caj26Ny1I/pYg8c5WW0hrcRNTxLjch71J7LabXE1Irhlut
vZysHxVVl5G76wpUv9EZPZrHW1fII5wIDhEhkyBsE2FWB315oI7cl0I0U16bCnJ0
KDr/KQ6nXG9ql5usSN57guPz2HYbnDpJogNs8zCYfrfIc3KCZkEFMdRYbgw0l36r
P2TNOlpBdMeJBJjcH8TS2Ap3mYNH8F32mkstaKPGxYi1/9dPJVj9/4bGx2Dxyt+k
xaTgXH9ny5+ITxko+59nePuSPA64XgDILNZwgTKeNZLWFe+zhUTSij+e4tAnq1dw
TWspp+iSEb+b6+zpSqB1CdFLDj2pybrDp8vZB3v5KWB4SnT9rrZY+CEvAyNG0gue
wueCtC/nusVNQqkS4hm6HyEgr+wV7AeKRR3tiK8CpwV0bCQEquHmyeFYt6BiGvHm
jff4Ah2u5V7u4WB0uEWLe/dhxAvoPtGAoS1grJteECWdTNm2bv3AOEVFi2RpfVyz
zy4Qt9gkzcHP9aHRvI1DpKwQftoP5CGtAj2pVaXg85Vff5l3VZTcG9TwwsQmOf5n
J3DFEge2YjCV9DOkkWOBAP2w45pkca5L15CqDtkRyOKG0f3W3gJ9CBBW02QXuvFJ
SwIDAQABo4IDDTCCAwkwDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUF
BwMBBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBSkDcacqnSfj8Gq
hs6bbP7imqlETjAfBgNVHSMEGDAWgBSoSmpjBH3duubRObemRWXv86jsoTBvBggr
BgEFBQcBAQRjMGEwLgYIKwYBBQUHMAGGImh0dHA6Ly9vY3NwLmludC14My5sZXRz
ZW5jcnlwdC5vcmcwLwYIKwYBBQUHMAKGI2h0dHA6Ly9jZXJ0LmludC14My5sZXRz
ZW5jcnlwdC5vcmcvMIGvBgNVHREEgacwgaSCDGNoYXQubmF5ci51c4IMZHJvcC5u
YXlyLnVzggtnaXQubmF5ci51c4IMaW1hcC5uYXlyLnVzggxtYWlsLm5heXIudXOC
DG1lZXQubmF5ci51c4IPbXRhLXN0cy5uYXlyLnVzggduYXlyLnVzgg1wYXN0ZS5u
YXlyLnVzggt2Y3MubmF5ci51c4ILd3d3Lm5heXIudXOCDHhtcHAubmF5ci51czAR
BggrBgEFBQcBGAQFMAMCAQUwTAYDVR0gBEUwQzAIBgZngQwBAgEwNwYLKwYBBAGC
3xMBAQEwKDAmBggrBgEFBQcCARYaaHR0cDovL2Nwcy5sZXRzZW5jcnlwdC5vcmcw
ggEEBgorBgEEAdZ5AgQCBIH1BIHyAPAAdgDwlaRZ8gDRgkAQLS+TiI6tS/4dR+OZ
4dA0prCoqo6ycwAAAXETVOpLAAAEAwBHMEUCIC8IqJETJKNM+jmyL328ll0FOymK
fSco1ZbguaMhuV2+AiEA9UgTCiGcOQ/5UOi+HDQeXO2x3eqE8Aen3Ucj993ShAgA
dgCyHgXMi6LNiiBOh2b5K7mKJSBna9r6cOeySVMt74uQXgAAAXETVOo7AAAEAwBH
MEUCIBsXWrQgWyQgwsOY1P1u/cvu/mqbDxrFywPlxcsQ+FaHAiEA3XX2T7rhveSe
1mDQcxEUYIAF5VuwxA6+d5Uz1GAosx4wDQYJKoZIhvcNAQELBQADggEBAIy435NI
cZehzSNsDMMm9sCh5mQL1vr4OKci9Pv3wkJ5+4PSPNH9HgD5iryEXW5VYcEiW9gR
Qy10g7sbWYrQw2S0K8X2QnTSEowaOXxoMQO6r2qHT7G5xq8yitWp7bskXz0HZkmj
s5rVtZUyOnsfEFuYZr7ZpSR+u6oUuhi/iIiHLH6iUUZkOBIP7vFMxkdqQ+bT7OEn
VdL8w53Z3hcCF2lbddCZG7QBE+mlKb0XloA2pP8k4K9hn0Yc3ryWIq+YNpyVPprQ
BbcnS8n0V9smpO/1PbxmhQGXKfTNSaFnG6VxjOaKaI34NPtfPOAzaCJYNfj/O1Bd
eADeD8IJia8Uvi0=
-----END CERTIFICATE-----
2020-04-06 10:04:39,618 - DEBUG - Event triggered: ssl_cert
2020-04-06 10:04:39,623 - ERROR - day is out of range for month
Traceback (most recent call last):
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/xmlstream/xmlstream.py", line 1492, in _process
if not self.__read_xml():
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/xmlstream/xmlstream.py", line 1564, in __read_xml
self.__spawn_event(xml)
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/xmlstream/xmlstream.py", line 1632, in __spawn_event
handler.prerun(stanza_copy)
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/xmlstream/handler/callback.py", line 64, in prerun
self.run(payload, True)
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/xmlstream/handler/callback.py", line 76, in run
self._pointer(payload)
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/features/feature_starttls/starttls.py", line 64, in _handle_starttls_proceed
if self.xmpp.start_tls():
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/xmlstream/xmlstream.py", line 889, in start_tls
cert.verify(self._expected_server_name, self._der_cert)
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/xmlstream/cert.py", line 133, in verify
not_before, not_after = extract_dates(raw_cert)
File "/home/admin1/.local/lib/python2.7/site-packages/sleekxmpp/xmlstream/cert.py", line 115, in extract_dates
not_after = datetime.strptime(not_after, '%Y%m%d%H%M%SZ')
File "/usr/lib/python2.7/_strptime.py", line 458, in _strptime
datetime_date(year, 1, 1).toordinal() + 1
ValueError: day is out of range for month
2020-04-06 10:04:39,625 - DEBUG - reconnecting...
2020-04-06 10:04:39,625 - DEBUG - Event triggered: session_end
2020-04-06 10:04:39,625 - DEBUG - SEND (IMMED): </stream:stream>
2020-04-06 10:04:39,626 - INFO - Waiting for </stream:stream> from server
^C
Aborted!
|
ValueError
|
def detect_language(lang=None, detect_fallback=True):
"""
returns the language (if it's retrievable)
"""
# We want to only use the 2 character version of this language
# hence en_CA becomes en, en_US becomes en.
if not isinstance(lang, six.string_types):
if detect_fallback is False:
# no detection enabled; we're done
return None
if hasattr(ctypes, "windll"):
windll = ctypes.windll.kernel32
try:
lang = locale.windows_locale[windll.GetUserDefaultUILanguage()]
# Our detected windows language
return lang[0:2].lower()
except (TypeError, KeyError):
# Fallback to posix detection
pass
try:
# Detect language
lang = locale.getdefaultlocale()[0]
except ValueError as e:
# This occurs when an invalid locale was parsed from the
# environment variable. While we still return None in this
# case, we want to better notify the end user of this. Users
# receiving this error should check their environment
# variables.
logger.warning("Language detection failure / {}".format(str(e)))
return None
except TypeError:
# None is returned if the default can't be determined
# we're done in this case
return None
return None if not lang else lang[0:2].lower()
|
def detect_language(lang=None, detect_fallback=True):
"""
returns the language (if it's retrievable)
"""
# We want to only use the 2 character version of this language
# hence en_CA becomes en, en_US becomes en.
if not isinstance(lang, six.string_types):
if detect_fallback is False:
# no detection enabled; we're done
return None
if hasattr(ctypes, "windll"):
windll = ctypes.windll.kernel32
try:
lang = locale.windows_locale[windll.GetUserDefaultUILanguage()]
# Our detected windows language
return lang[0:2].lower()
except (TypeError, KeyError):
# Fallback to posix detection
pass
try:
# Detect language
lang = locale.getdefaultlocale()[0]
except TypeError:
# None is returned if the default can't be determined
# we're done in this case
return None
return None if not lang else lang[0:2].lower()
|
https://github.com/caronc/apprise/issues/126
|
(main:220) - Bazarr is being restarted...
Bazarr starting...
Traceback (most recent call last):
File "bazarr/main.py", line 75, in <module>
update_notifier()
File "/Users/USER/bazarr/bazarr/bazarr/notifier.py", line 13, in update_notifier
a = apprise.Apprise()
File "/Users/USER/bazarr/bazarr/bazarr/../libs/apprise/Apprise.py", line 78, in __init__
self.locale = AppriseLocale()
File "/Users/USER/bazarr/bazarr/bazarr/../libs/apprise/AppriseLocale.py", line 111, in __init__
self.lang = AppriseLocale.detect_language(language)
File "/Users/USER/bazarr/bazarr/bazarr/../libs/apprise/AppriseLocale.py", line 208, in detect_language
lang = locale.getdefaultlocale()[0]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 543, in getdefaultlocale
return _parse_localename(localename)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 475, in _parse_localename
raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8
|
ValueError
|
def notify(self, title, body, **kwargs):
"""
Perform Email Notification
"""
from_name = self.from_name
if not from_name:
from_name = self.app_desc
self.logger.debug("Email From: %s <%s>" % (self.from_addr, from_name))
self.logger.debug("Email To: %s" % (self.to_addr))
self.logger.debug("Login ID: %s" % (self.user))
self.logger.debug("Delivery: %s:%d" % (self.smtp_host, self.port))
# Prepare Email Message
if self.notify_format == NotifyFormat.HTML:
email = MIMEText(body, "html")
email["Content-Type"] = "text/html"
else:
email = MIMEText(body, "text")
email["Content-Type"] = "text/plain"
email["Subject"] = title
email["From"] = "%s <%s>" % (from_name, self.from_addr)
email["To"] = self.to_addr
email["Date"] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
email["X-Application"] = self.app_id
# bind the socket variable to the current namespace
socket = None
try:
self.logger.debug("Connecting to remote SMTP server...")
socket = smtplib.SMTP(
self.smtp_host,
self.port,
None,
timeout=self.timeout,
)
if self.secure:
# Handle Secure Connections
self.logger.debug("Securing connection with TLS...")
socket.starttls()
if self.user and self.password:
# Apply Login credetials
self.logger.debug("Applying user credentials...")
socket.login(self.user, self.password)
# Send the email
socket.sendmail(self.from_addr, self.to_addr, email.as_string())
self.logger.info('Sent Email notification to "%s".' % (self.to_addr,))
except (SocketError, smtplib.SMTPException, RuntimeError) as e:
self.logger.warning(
"A Connection error occured sending Email "
"notification to %s." % self.smtp_host
)
self.logger.debug("Socket Exception: %s" % str(e))
# Return; we're done
return False
finally:
# Gracefully terminate the connection with the server
if socket is not None: # pragma: no branch
socket.quit()
return True
|
def notify(self, title, body, **kwargs):
"""
Perform Email Notification
"""
from_name = self.from_name
if not from_name:
from_name = self.app_desc
self.logger.debug("Email From: %s <%s>" % (self.from_addr, from_name))
self.logger.debug("Email To: %s" % (self.to_addr))
self.logger.debug("Login ID: %s" % (self.user))
self.logger.debug("Delivery: %s:%d" % (self.smtp_host, self.port))
# Prepare Email Message
if self.notify_format == NotifyFormat.HTML:
email = MIMEText(body, "html")
email["Content-Type"] = "text/html"
else:
email = MIMEText(body, "text")
email["Content-Type"] = "text/plain"
email["Subject"] = title
email["From"] = "%s <%s>" % (from_name, self.from_addr)
email["To"] = self.to_addr
email["Date"] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
email["X-Application"] = self.app_id
try:
self.logger.debug("Connecting to remote SMTP server...")
socket = smtplib.SMTP(
self.smtp_host,
self.port,
None,
timeout=self.timeout,
)
if self.secure:
# Handle Secure Connections
self.logger.debug("Securing connection with TLS...")
socket.starttls()
if self.user and self.password:
# Apply Login credetials
self.logger.debug("Applying user credentials...")
socket.login(self.user, self.password)
# Send the email
socket.sendmail(self.from_addr, self.to_addr, email.as_string())
self.logger.info('Sent Email notification to "%s".' % (self.to_addr,))
except (SocketError, smtplib.SMTPException, RuntimeError) as e:
self.logger.warning(
"A Connection error occured sending Email "
"notification to %s." % self.smtp_host
)
self.logger.debug("Socket Exception: %s" % str(e))
# Return; we're done
return False
finally:
# Gracefully terminate the connection with the server
socket.quit()
return True
|
https://github.com/caronc/apprise/issues/15
|
ERROR:root:notification exception
Traceback (most recent call last):
File "/home/xxxx/.local/lib/python3.5/site-packages/apprise/Apprise.py", line 259, in notify
notify_type=notify_type):
File "/home/xxxx/.local/lib/python3.5/site-packages/apprise/plugins/NotifyEmail.py", line 292, in notify
socket.quit()
UnboundLocalError: local variable 'socket' referenced before assignment
|
UnboundLocalError
|
def do_EI(self, obj):
"""End inline image object"""
if isinstance(obj, PDFStream) and "W" in obj and "H" in obj:
iobjid = str(id(obj))
self.device.begin_figure(iobjid, (0, 0, 1, 1), MATRIX_IDENTITY)
self.device.render_image(iobjid, obj)
self.device.end_figure(iobjid)
return
|
def do_EI(self, obj):
"""End inline image object"""
if "W" in obj and "H" in obj:
iobjid = str(id(obj))
self.device.begin_figure(iobjid, (0, 0, 1, 1), MATRIX_IDENTITY)
self.device.render_image(iobjid, obj)
self.device.end_figure(iobjid)
return
|
https://github.com/pdfminer/pdfminer.six/issues/441
|
Traceback (most recent call last):
File "pdf2txt.py", line 188, in <module>
sys.exit(main())
File "pdf2txt.py", line 182, in main
outfp = extract_text(**vars(A))
File "pdf2txt.py", line 56, in extract_text
pdfminer.high_level.extract_text_to_fp(fp, **locals())
File "***/lib/python3.6/site-packages/pdfminer/high_level.py", line 86, in extract_text_to_fp
interpreter.process_page(page)
File "***/lib/python3.6/site-packages/pdfminer/pdfinterp.py", line 895, in process_page
self.render_contents(page.resources, page.contents, ctm=ctm)
File "***/lib/python3.6/site-packages/pdfminer/pdfinterp.py", line 908, in render_contents
self.execute(list_value(streams))
File "***/lib/python3.6/site-packages/pdfminer/pdfinterp.py", line 933, in execute
func(*args)
File "***/lib/python3.6/site-packages/pdfminer/pdfinterp.py", line 840, in do_EI
if 'W' in obj and 'H' in obj:
TypeError: a bytes-like object is required, not 'str'
|
TypeError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.