Python Error (ValueError: _getfullpathname: embedded null character) - python-3.x

I don't know How to fix it please help, I have tried everything mentioned in the post Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC) but no luck. I'm a newbie to the python and am self learning specific details would greatly be appreciated.
Console:
Traceback (most recent call last):
from matplotlib import pyplot
File "C:\Users\...\lib\site-packages\matplotlib\pyplot.py", line 29, in <module>
import matplotlib.colorbar
File "C:\Users\...\lib\site-packages\matplotlib\colorbar.py", line 34, in <module>
import matplotlib.collections as collections
File "C:\Users\...\lib\site-packages\matplotlib\collections.py", line 27, in <module>
import matplotlib.backend_bases as backend_bases
File "C:\Users\...\lib\site-packages\matplotlib\backend_bases.py", line 62, in <module>
import matplotlib.textpath as textpath
File "C:\Users\...\lib\site-packages\matplotlib\textpath.py", line 15, in <module>
import matplotlib.font_manager as font_manager
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1421, in <module>
_rebuild()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1406, in _rebuild
fontManager = FontManager()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1044, in __init__
self.ttffiles = findSystemFonts(paths) + findSystemFonts()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 313, in findSystemFonts
for f in win32InstalledFonts(fontdir):
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 231, in win32InstalledFonts
direc = os.path.abspath(direc).lower()
File "C:\Users\...\lib\ntpath.py", line 535, in abspath
path = _getfullpathname(path)
ValueError: _getfullpathname: embedded null character
Python:
importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing dataset
dataset = pd.read_csv('Position_Salaries.csv')
x = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values
#Linear Regression
from sklearn.linear_model import LinearRegression
reg_lin = LinearRegression()
reg_lin = reg_lin.fit(x,y)
#ploynomial Linear Regression
from sklearn.preprocessing import PolynomialFeatures
reg_poly = PolynomialFeatures(degree = 3)
x_poly = reg_poly.fit_transform(x)
reg_poly.fit(x_poly,y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(x_poly,y)
#Visualizing Linear Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,reg_lin.predict(x), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
#Visualizing Polynomial Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,lin_reg_2.predict(reg_poly.fit_transform(x)), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

To find this in font_manager py:
direc = os.path.abspath(direc).lower()
change it into:
direc = direc.split('\0', 1)[0]
and save to apply in your file.

I don't think you applied the patch in Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC) correctly: if you had, there shouldn't be a mention of direc = os.path.abspath(direc).lower() in your error stack, since the patch removed it.
To be clear, here is the entire win32InstalledFonts() method in C:\Anaconda\envs\py35\Lib\site-packages\matplotlib\font_manager.py (or wherever Anaconda is installed) after the patch is applied, with matplotlib 2.0.0:
def win32InstalledFonts(directory=None, fontext='ttf'):
"""
Search for fonts in the specified font directory, or use the
system directories if none given. A list of TrueType font
filenames are returned by default, or AFM fonts if *fontext* ==
'afm'.
"""
from six.moves import winreg
if directory is None:
directory = win32FontDirectory()
fontext = get_fontext_synonyms(fontext)
key, items = None, {}
for fontdir in MSFontDirectories:
try:
local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
except OSError:
continue
if not local:
return list_fonts(directory, fontext)
try:
for j in range(winreg.QueryInfoKey(local)[1]):
try:
''' Patch fixing [Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC)](https://stackoverflow.com/a/34007642/395857)
key, direc, any = winreg.EnumValue( local, j)
if not is_string_like(direc):
continue
if not os.path.dirname(direc):
direc = os.path.join(directory, direc)
direc = os.path.abspath(direc).lower()
'''
key, direc, any = winreg.EnumValue( local, j)
if not is_string_like(direc):
continue
if not os.path.dirname(direc):
direc = os.path.join(directory, direc)
direc = direc.split('\0', 1)[0]
if os.path.splitext(direc)[1][1:] in fontext:
items[direc] = 1
except EnvironmentError:
continue
except WindowsError:
continue
except MemoryError:
continue
return list(six.iterkeys(items))
finally:
winreg.CloseKey(local)
return None

The actual cause of the issue appears to be in os.path.abspath(). A better solution might be to edit <python dir>\Lib\ntpaths.py as detailed in Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC)
Basically, add a ValueError: exception handler to the Windows version of the abspath() function. This is lower down on the call stack and could save you from encountering this issue in other places.

Related

ValueError: Could not locate a VISA implementation. Install either the IVI binary or pyvisa-py

I'm trying build an executable of a Python script that reads from a digital multimeter connected via RS232-USB. To build, I'm using cxfreeze.
For this, a setup.py file was written to management. When I run the Python script, everything happens normally. But the built executable doesn't run and shows: ValueError: Could not locate a VISA implementation. Install either the IVI binary or pyvisa-py.
I wrote a simpler code to test, including all the used packages of the main program, but the executable file shows the same error.
The code (test_pyvisa_implementation.py) is:
from matplotlib.figure import Figure
import tkinter as tk
from tkinter import *
import numpy as np
import time, warnings
import pyvisa as visa
from tkinter import filedialog
def port_send():
global ports
print(ports.get())
window = tk.Tk()
window.title("Testing pyvisa implementation")
baudRate = 19200
flowCtrl = visa.constants.VI_ASRL_FLOW_NONE
rm = visa.ResourceManager()
com = rm.list_resources()
if com == ():
com = ['No connection']
ports = tk.StringVar(window)
def refresh_port(ports):
ports.set('')
w['menu'].delete(0, 'end')
com = rm.list_resources()
print(com)
if com == ():
com = ['No connection']
for choices in com:
w['menu'].add_command(label=com, command=tk._setit(ports, choices))
w = tk.OptionMenu(window, ports, *com)
w.place(x = 50, y = 0)
refresh = tk.Button(window, text='refresh', command = lambda:refresh_port(ports))
refresh.place(x = 50, y = 80)
confirm = tk.Button(window, text="Confirm", command = lambda:port_send())
confirm.place(x = 50, y = 160)
window.mainloop()
The setup.py is:
import os
from cx_Freeze import setup, Executable
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
from tkinter import *
import numpy as np
import time, warnings
import pyvisa as visa
from tkinter import filedialog
base = None
executables = [
Executable("test_pyvisa_implementation.py", base=base)
]
buildOptions = dict(
packages = ['matplotlib.backends.backend_tkagg','matplotlib.figure',\
'tkinter','numpy','time','pyvisa'],
includes = [],
include_files = [],
excludes = []
)
setup(
name = "TESTING_PYVISA_IMPLEMENTATION",
version = "1.0",
description = "DEFAULT",
options = dict(build_exe = buildOptions),
executables = executables
)
The error is:
> Traceback (most recent call last):
File "/home/lcem/.platformio/penv/lib/python3.8/site-packages/cx_Freeze/initscripts/__startup__.py", line 113, in run
module_init.run(name + "__main__")
File "/home/lcem/.platformio/penv/lib/python3.8/site-packages/cx_Freeze/initscripts/Console.py", line 15, in run
exec(code, module_main.__dict__)
File "test_pyvisa_implementation.py", line 21, in <module>
File "/home/lcem/.platformio/penv/lib/python3.8/site-packages/pyvisa/highlevel.py", line 3015, in __new__
visa_library = open_visa_library(visa_library)
File "/home/lcem/.platformio/penv/lib/python3.8/site-packages/pyvisa/highlevel.py", line 2924, in open_visa_library
wrapper = _get_default_wrapper()
File "/home/lcem/.platformio/penv/lib/python3.8/site-packages/pyvisa/highlevel.py", line 2883, in _get_default_wrapper
raise ValueError(
ValueError: Could not locate a VISA implementation. Install either the IVI binary or pyvisa-py.
Even if I reinstall the pyvisa-py package, I still get the error.
Any suggestions what I can do?
My system information: Linux 5.4.0-90-generic #101-Ubuntu SMP Fri Oct 15 20:00:55 UTC 2021.

matplotlib is now giving an 'Unknown property' AttributeError since update to Python 3:

I am using astroplan to set up some astronomical observations. Previously, when I ran my code using Python 2.7, it plotted the target on the sky properly. Now, I have moved to Python 3.7 and I get an AttributError on the same code.
I took my larger code and stripped out everything that did not seem to trigger the error. Here below is code that will generate the complaint.
from astroplan import Observer, FixedTarget
import astropy.units as u
from astropy.time import Time
import matplotlib.pyplot as plt
from astroplan.plots import plot_sky
import numpy as np
time = Time('2015-06-16 12:00:00')
subaru = Observer.at_site('subaru')
vega = FixedTarget.from_name('Vega')
sunset_tonight = subaru.sun_set_time(time, which='nearest')
vega_rise = subaru.target_rise_time(time, vega) + 5*u.minute
start = np.max([sunset_tonight, vega_rise])
plot_sky(vega, subaru, start)
plt.show()
Expected result was a simple plot of the target, in this case, the star Vega, on the sky as seen by the Subaru telescope in Hawaii. The astroplan docs give a tutorial that shows how it was to look at the very end of this page:
https://astroplan.readthedocs.io/en/latest/tutorials/summer_triangle.html
Instead, I now get the following error:
Traceback (most recent call last):
File "plot_sky.py", line 16, in <module>
plot_sky(vega, subaru, start)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/astropy/utils/decorators.py", line 842, in plot_sky
func = make_function_with_signature(func, name=name, **wrapped_args)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/astropy/units/decorators.py", line 222, in wrapper
return_ = wrapped_function(*func_args, **func_kwargs)
File "/local/data/fugussd/rkbarry/.local/lib/python3.7/site-packages/astroplan/plots/sky.py", line 216, in plot_sky
ax.set_thetagrids(range(0, 360, 45), theta_labels, frac=1.2)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/projections/polar.py", line 1268, in set_thetagrids
t.update(kwargs)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/text.py", line 187, in update
super().update(kwargs)
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 916, in update
ret = [_update_property(self, k, v) for k, v in props.items()]
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 916, in <listcomp>
ret = [_update_property(self, k, v) for k, v in props.items()]
File "/usr1/local/anaconda_py3/ana37/lib/python3.7/site-packages/matplotlib/artist.py", line 912, in _update_property
raise AttributeError('Unknown property %s' % k)
AttributeError: Unknown property frac

Y = churn.iloc[:, 18].values

Trying to import my dataset(18 columns counting from 0) i got this error:
File "C:/Users/ASUS/PycharmProjects/PA/BestAcc.py", line 23, in
Y = churn.iloc[:, 18].values File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1472, in
getitem
return self._getitem_tuple(key) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 2013, in
_getitem_tuple
self._has_valid_tuple(tup) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 222, in
_has_valid_tuple
self._validate_key(k, i) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1957, in
_validate_key
self._validate_integer(key, axis) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 2009, in
_validate_integer
raise IndexError("single positional indexer is out-of-bounds") IndexError: single positional indexer is out-of-bounds
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
churn = pd.read_csv("HR.csv")
#import colums except the first one in the dataset
X = churn.iloc[:, 1:18].values
Y = churn.iloc[:, 18].values
iloc has been deprecated in later versions of pandas - I would suggest using loc instead -
X = churn.loc[:, churn.columns[1:18]]
Y = churn.loc[:, churn.columns[18]]

Import error in python 3.4.4

# Load the data
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn
oecd = pd.read_csv("oecd.csv", thousands=',')
gd_per_capita = pd.read_csv("gdp_per_capita.csv", thousands=',',delimiter='\t', encoding='latin1', na_values="n/a")
#Prepare the data
country_stats = prepare_country_stats(oecd, gdp_per_capita)
x = np.c_[country_stats["GDP per capita"]]
y = np.c[country_stats["Life satisfaction"]]
#Visualise the data
country_stats.plot(kind='scatter', x="GDP per capita", y='Life satisfaction')
plt.show()
# Select a linear model
model = sklearn.linear_model.LinearRegression()
# Train the code
model.fit(x,y)
# Make a prediction for Cyprus
x_new = [[22587]] # Cyprus GDP per capita
print(model.predict(x_new))
Whenever I try to run this code in Python 3.4.4 this throws up:
Traceback (most recent call last):
File "C:\Users\Ranjan.Ranjan-PC\Desktop\Hands-On\gdp.py", line 6, in <module>
import sklearn
File "C:\Python34\lib\site-packages\sklearn\__init__.py", line 134, in <module>
from .base import clone
File "C:\Python34\lib\site-packages\sklearn\base.py", line 10, in <module>
from scipy import sparse
File "C:\Python34\lib\site-packages\scipy\sparse\__init__.py", line 213, in <module>
from .csr import *
File "C:\Python34\lib\site-packages\scipy\sparse\csr.py", line 13, in <module>
from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, \
ImportError: DLL load failed: %1 is not a valid Win32 application.
sklearn has been installed though
What is wrong?

Python 2.7 Unrecognized Character G in format string during runtime

I have Python 2.7 Win 32 and have installed Matplotlib, Numpy, PyParsing, Dateutil. In IDLE I place in the code:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
def graphRawFX () :
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
delimiter=',',
converters={0:mdates.strpdate2num('%Y%m%d%H%M%S') }
fig = plt.figure(figsize=(10,7))
ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
ax1.plot(date,bid)
ax1.plot(date,ask)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
plt.grid(True)
plt.show()
I then proceed to enter:
rawGraphFX()
This results into the error below:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
graphRawFX()
File "C:/Users/Emanuel/Desktop/graph", line 16, in graphRawFX
ax1.plot(date,ask)
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 4137, in plot
for line in self._get_lines(*args, **kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 317, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 276, in _plot_args
linestyle, marker, color = _process_plot_format(tup[-1])
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 129, in _process_plot_format
'Unrecognized character %c in format string' % c)
ValueError: Unrecognized character G in format string
>>>
This is probably easy to fix but I need help since I'm getting frustrated over this.
There are at least two issues with these two lines:
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
The first of these lines sets date to a class instance that would convert strings to matplotlib style dates. However, you never supply the dates. You need to come up with date strings from somewhere and apply this function to them.
The second line of these lines makes two assignments. It first assigns np.loadtxt to True and unpack to 'GPBUSD1d.txt'. It consequently assigns bid to True and ask to 'GPBUSD1d.txt'. It is the latter that causes the Unrecognized character error when matplotlib tries to interpret the G in 'GPBUSD1d.txt' as some kind of format instruction. You probably intended something like:
bid, ask = np.loadtxt('GPBUSD1d.txt', unpack=True)
This would call the function np.loadtxt which would load the file GPBUSD1d.txt' and transpose ("unpack") it.

Resources