Altair: NoMatchingVersions when saving maps with selenium - python

I am trying to create a series and save them iteratively.
The creation works well but while saving I get the following error:
---------------------------------------------------------------------------
NoMatchingVersions Traceback (most recent call last)
<ipython-input-103-e75c3f4b4fa5> in <module>
29 chart=(background + chart).configure_view(stroke='white')
30 filename = f"{scenario}.svg"
---> 31 save(chart, filename, method='selenium', webdriver=driver)
~\Anaconda3\lib\site-packages\altair_saver\_core.py in save(chart, fp, fmt, mode, method, **kwargs)
75 saver = Saver(spec, mode=mode, **kwargs)
76
---> 77 saver.save(fp=fp, fmt=fmt)
78
79
~\Anaconda3\lib\site-packages\altair_saver\savers\_saver.py in save(self, fp, fmt)
86 raise ValueError(f"Got fmt={fmt}; expected one of {self.valid_formats}")
87
---> 88 content = self.mimebundle(fmt).popitem()[1]
89 if isinstance(content, dict):
90 with maybe_open(fp, "w") as f:
~\Anaconda3\lib\site-packages\altair_saver\savers\_saver.py in mimebundle(self, fmts)
66 f"invalid fmt={fmt!r}; must be one of {self.valid_formats}."
67 )
---> 68 bundle.update(self._mimebundle(fmt))
69 return bundle
70
~\Anaconda3\lib\site-packages\altair_saver\savers\_selenium.py in _mimebundle(self, fmt)
249
250 def _mimebundle(self, fmt: str) -> Mimebundle:
--> 251 out = self._extract(fmt)
252 mimetype = fmt_to_mimetype(
253 fmt,
~\Anaconda3\lib\site-packages\altair_saver\savers\_selenium.py in _extract(self, fmt)
209 js_resources = {
210 "vega.js": get_bundled_script("vega", self._vega_version),
--> 211 "vega-lite.js": get_bundled_script("vega-lite", self._vegalite_version),
212 "vega-embed.js": get_bundled_script(
213 "vega-embed", self._vegaembed_version
~\Anaconda3\lib\site-packages\altair_viewer\_scripts.py in get_bundled_script(package, version)
36 f"package {package!r} not recognized. Available: {list(listing)}"
37 )
---> 38 version_str = find_version(version, listing[package])
39 content = pkgutil.get_data("altair_viewer", f"scripts/{package}-{version_str}.js")
40 if content is None:
~\Anaconda3\lib\site-packages\altair_viewer\_utils.py in find_version(version, candidates, strict_micro)
190 if not matches:
191 raise NoMatchingVersions(
--> 192 f"No matches for version={version!r} among {candidates}"
193 )
194 return str(matches[-1])
NoMatchingVersions: No matches for version='4.8.1' among ['4.0.2']
I am using selenium and altair_saver:
from altair_saver import save
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'pathtochromedriver/chromedriver_win32/chromedriver.exe')
for i, scenario in enumerate(scenario_columns):
chart=makechart(scenario, i)
filename = f"{scenario}.svg"
save(chart, filename, method='selenium', webdriver=driver)
Here `scenario` is a string without special characters.

You need to update the altair_viewer package to a newer version:
$ pip install -U altair_viewer
(This error was improved in https://github.com/altair-viz/altair_viewer/pull/33, so shouldn't be as mysterious when it comes up in the future).

Related

create_collection() got an unexpected keyword argument 'embedding_fn'

I was trying to use the langchain library to create a question answering system. But when I try to search in the document using the chromadb library it gives this error:
TypeError: create_collection() got an unexpected keyword argument 'embedding_fn'
Here's the code am working on
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.document_loaders import TextLoader
from langchain.vectorstores import Chroma
loader = TextLoader('./info.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
docsearch = Chroma.from_documents(texts, embeddings).
The last line generates the error.
This is the complete error message:
TypeError Traceback (most recent call last)
Input In [36], in <cell line: 1>()
----> 1 docsearch = Chroma.from_documents(texts, embeddings)
File ~\anaconda3\lib\site-packages\langchain\vectorstores\chroma.py:212, in Chroma.from_documents(cls, documents, embedding, ids, collection_name, persist_directory, **kwargs)
210 texts = [doc.page_content for doc in documents]
211 metadatas = [doc.metadata for doc in documents]
--> 212 return cls.from_texts(
213 texts=texts,
214 embedding=embedding,
215 metadatas=metadatas,
216 ids=ids,
217 collection_name=collection_name,
218 persist_directory=persist_directory,
219 )
File ~\anaconda3\lib\site-packages\langchain\vectorstores\chroma.py:178, in Chroma.from_texts(cls, texts, embedding, metadatas, ids, collection_name, persist_directory, **kwargs)
151 #classmethod
152 def from_texts(
153 cls,
(...)
160 **kwargs: Any,
161 ) -> Chroma:
162 """Create a Chroma vectorstore from a raw documents.
163
164 If a persist_directory is specified, the collection will be persisted there.
(...)
176 Chroma: Chroma vectorstore.
177 """
--> 178 chroma_collection = cls(
179 collection_name=collection_name,
180 embedding_function=embedding,
181 persist_directory=persist_directory,
182 )
183 chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids)
184 return chroma_collection
File ~\anaconda3\lib\site-packages\langchain\vectorstores\chroma.py:65, in Chroma.__init__(self, collection_name, embedding_function, persist_directory)
60 logger.warning(
61 f"Collection {collection_name} already exists,"
62 " Do you have the right embedding function?"
63 )
64 else:
---> 65 self._collection = self._client.create_collection(
66 name=collection_name,
67 embedding_fn=self._embedding_function.embed_documents
68 if self._embedding_function is not None
69 else None,
70 )
TypeError: create_collection() got an unexpected keyword argument 'embedding_fn'
The create_collection method of chromadb.Client was changed 2 days ago and the embedding_fn parameter was renamed to embedding_function:
https://github.com/chroma-core/chroma/commit/6ce2388e219d47048e854be72be54617df647224
The source code for the langchain.vectorstores.chroma.Chroma class as of version 0.0.87 seems to have been updated already (3 hours before you asked the question) to match the chromadb library:
https://github.com/hwchase17/langchain/commit/34cba2da3264ccc9100f7efd16807c8d2a51734c
So you should be able to fix the problem by installing the newest version of LangChain.

AttributeError: module 'PIL.TiffTags' has no attribute 'LONG8'

I am trying to open an image with skimage.io.imread but I have the error in title.
For example:
skimage.io.imread('myimage.png')
My environment; skimage:
import skimage
print(skimage.__version__)
0.19.2
and PIL:
import PIL
PIL.__version__
8.0.1
This is the entire traceback:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-52-1b9f5663f4c8> in <module>
----> 1 skimage.io.imread('qrcode-caracciolo.png')
/usr/local/lib/python3.9/site-packages/skimage/io/_io.py in imread(fname, as_gray, plugin, **plugin_args)
51
52 with file_or_url_context(fname) as fname:
---> 53 img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
54
55 if not hasattr(img, 'ndim'):
/usr/local/lib/python3.9/site-packages/skimage/io/manage_plugins.py in call_plugin(kind, *args, **kwargs)
205 (plugin, kind))
206
--> 207 return func(*args, **kwargs)
208
209
/usr/local/lib/python3.9/site-packages/skimage/io/_plugins/imageio_plugin.py in imread(*args, **kwargs)
8 #wraps(imageio_imread)
9 def imread(*args, **kwargs):
---> 10 return np.asarray(imageio_imread(*args, **kwargs))
/usr/local/lib/python3.9/site-packages/imageio/__init__.py in imread(uri, format, **kwargs)
94 )
95
---> 96 return imread_v2(uri, format=format, **kwargs)
97
98
/usr/local/lib/python3.9/site-packages/imageio/v2.py in imread(uri, format, **kwargs)
199 imopen_args["legacy_mode"] = True
200
--> 201 with imopen(uri, "ri", **imopen_args) as file:
202 return file.read(index=0, **kwargs)
203
/usr/local/lib/python3.9/site-packages/imageio/core/imopen.py in imopen(uri, io_mode, plugin, format_hint, legacy_mode, **kwargs)
212
213 try:
--> 214 plugin_instance = candidate_plugin(request, **kwargs)
215 except InitializationError:
216 # file extension doesn't match file type
/usr/local/lib/python3.9/site-packages/imageio/config/plugins.py in partial_legacy_plugin(request)
106
107 def partial_legacy_plugin(request):
--> 108 return LegacyPlugin(request, legacy_plugin)
109
110 clazz = partial_legacy_plugin
/usr/local/lib/python3.9/site-packages/imageio/core/legacy_plugin_wrapper.py in __init__(self, request, legacy_plugin)
66 )
67 if self._request.mode.io_mode == IOMode.read:
---> 68 if not self._format.can_read(request):
69 raise InitializationError(
70 f"`{self._format.name}`" f" can not read `{source}`."
/usr/local/lib/python3.9/site-packages/imageio/core/format.py in can_read(self, request)
242 Get whether this format can read data from the specified uri.
243 """
--> 244 return self._can_read(request)
245
246 def can_write(self, request):
/usr/local/lib/python3.9/site-packages/imageio/plugins/pillow_legacy.py in _can_read(self, request)
262
263 def _can_read(self, request):
--> 264 Image = self._init_pillow()
265 if request.mode[1] in (self.modes + "?"):
266 if self.plugin_id in Image.OPEN:
/usr/local/lib/python3.9/site-packages/imageio/plugins/pillow_legacy.py in _init_pillow(self)
256
257 if self.plugin_id in ("PNG", "JPEG", "BMP", "GIF", "PPM"):
--> 258 Image.preinit()
259 else:
260 Image.init()
/usr/local/lib/python3.9/site-packages/PIL/Image.py in preinit()
365 assert JpegImagePlugin
366 except ImportError:
--> 367 pass
368 try:
369 from . import PpmImagePlugin
/usr/local/lib/python3.9/site-packages/PIL/JpegImagePlugin.py in <module>
42 import warnings
43
---> 44 from . import Image, ImageFile, TiffImagePlugin
45 from ._binary import i16be as i16
46 from ._binary import i32be as i32
/usr/local/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in <module>
425
426
--> 427 class ImageFileDirectory_v2(MutableMapping):
428 """This class represents a TIFF tag directory. To speed things up, we
429 don't decode tags unless they're asked for.
/usr/local/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in ImageFileDirectory_v2()
706 (TiffTags.DOUBLE, "d", "double"),
707 (TiffTags.IFD, "L", "long"),
--> 708 (TiffTags.LONG8, "Q", "long8"),
709 ],
710 )
AttributeError: module 'PIL.TiffTags' has no attribute 'LONG8'

Connecting to Sharepoint

I would like to CRUD files on Sharepoint. To do this I'm trying to follow the basic example on Office365-REST-Python-Client:
from office365.sharepoint.client_context import ClientContext
settings = {
'url': 'https://*****.sharepoint.com/sites/*****',
'user_credentials': {
'username': '*****#gmail.com',
'password': '*****',
},
}
ctx = ClientContext(settings["url"]).with_user_credentials(settings.get('user_credentials').get('username'),
settings.get('user_credentials').get('password'))
web = ctx.web.get().execute_query()
print(web.properties["Url"])
which gives me an Error:
IndexError Traceback (most recent call last)
<ipython-input-23-c5907526ff22> in <module>
12 settings.get('user_credentials').get('password'))
13
---> 14 web = ctx.web.get().execute_query()
15 print(web.properties["Url"])
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\client_object.py in execute_query(self)
31
32 def execute_query(self):
---> 33 self.context.execute_query()
34 return self
35
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\client_runtime_context.py in execute_query(self)
136 def execute_query(self):
137 if self.has_pending_request:
--> 138 self.pending_request().execute_query()
139
140 def add_query(self, query, to_begin=False):
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\client_request.py in execute_query(self)
72 request = self.build_request()
73 self.beforeExecute.notify(request)
---> 74 response = self.execute_request_direct(request)
75 response.raise_for_status()
76 self.process_response(response)
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\odata\odata_request.py in execute_request_direct(self, request)
32 def execute_request_direct(self, request):
33 self.ensure_media_type(request)
---> 34 return super(ODataRequest, self).execute_request_direct(request)
35
36 def build_request(self):
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\client_request.py in execute_request_direct(self, request_options)
84 :type request_options: office365.runtime.http.request_options.RequestOptions
85 """
---> 86 self.context.authenticate_request(request_options)
87 if request_options.method == HttpMethod.Post:
88 if request_options.is_bytes or request_options.is_file:
D:\Anaconda\envs\hplc\lib\site-packages\office365\sharepoint\client_context.py in authenticate_request(self, request)
151
152 def authenticate_request(self, request):
--> 153 self._auth_context.authenticate_request(request)
154
155 def _build_modification_query(self, request):
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\authentication_context.py in authenticate_request(self, request)
82 """Authenticate request
83 :type request: RequestOptions"""
---> 84 self._provider.authenticate_request(request)
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\providers\saml_token_provider.py in authenticate_request(self, request)
71 """
72 logger = self.logger(self.authenticate_request.__name__)
---> 73 self.ensure_authentication_cookie()
74 logger.debug_secrets(self._cached_auth_cookies)
75 cookie_header_value = "; ".join(["=".join([key, str(val)]) for key, val in self._cached_auth_cookies.items()])
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\providers\saml_token_provider.py in ensure_authentication_cookie(self)
78 def ensure_authentication_cookie(self):
79 if self._cached_auth_cookies is None:
---> 80 self._cached_auth_cookies = self.get_authentication_cookie()
81 return True
82
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\providers\saml_token_provider.py in get_authentication_cookie(self)
91 user_realm = self._get_user_realm()
92 if user_realm.IsFederated:
---> 93 token = self._acquire_service_token_from_adfs(user_realm.STSAuthUrl)
94 else:
95 token = self._acquire_service_token()
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\providers\saml_token_provider.py in _acquire_service_token_from_adfs(self, adfs_url)
134 headers={'Content-Type': 'application/soap+xml; charset=utf-8'})
135 dom = minidom.parseString(response.content.decode())
--> 136 assertion_node = dom.getElementsByTagNameNS("urn:oasis:names:tc:SAML:1.0:assertion", 'Assertion')[0].toxml()
137
138 try:
IndexError: list index out of range
Any ideas? It doesn't feel like an authentication problem.
It might be too late answer, but maybe it will help someone who faced with same problem and will find this question.
I had the same issue on version 2.3.9, but in version 2.1.4 there is no such problem, so you can try to use older versions.
Also there is an issue in GH repo: https://github.com/vgrem/Office365-REST-Python-Client/issues/304

what is the problem ?: application.connect() error

I am a beginner developer who started to study automation by using pywinauto.
An overflow error occurs when using application.connect () to connect to an already open program.
But application.start() works fine....
Please help me if someone know this part.
The source code and error contents are as follows.
Source code:
import pywinauto
app = pywinauto.application.Application()
app.connect(title_re='Calculator')
Error:
OverflowError Traceback (most recent call last)
in
1 import pywinauto
2 app = pywinauto.application.Application()
----> 3 app.connect(title_re='Calculator')
d:\Anaconda3\lib\site-packages\pywinauto\application.py in connect(self, **kwargs)
972 ).process_id
973 else:
--> 974 self.process = findwindows.find_element(**kwargs).process_id
975 connected = True
976
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in find_element(**kwargs)
82 so please see :py:func:find_elements for the full parameters description.
83 """
---> 84 elements = find_elements(**kwargs)
85
86 if not elements:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in find_elements(class_name, class_name_re, parent, process, title, title_re, top_level_only, visible_only, enabled_only, best_match, handle, ctrl_index, found_index, predicate_func, active_only, control_id, control_type, auto_id, framework_id, backend, depth)
279 return title_regex.match(t)
280 return False
--> 281 elements = [elem for elem in elements if _title_match(elem)]
282
283 if visible_only:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in (.0)
279 return title_regex.match(t)
280 return False
--> 281 elements = [elem for elem in elements if _title_match(elem)]
282
283 if visible_only:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in _title_match(w)
275 def _title_match(w):
276 """Match a window title to the regexp"""
--> 277 t = w.rich_text
278 if t is not None:
279 return title_regex.match(t)
d:\Anaconda3\lib\site-packages\pywinauto\win32_element_info.py in rich_text(self)
81 def rich_text(self):
82 """Return the text of the window"""
---> 83 return handleprops.text(self.handle)
84
85 name = rich_text
d:\Anaconda3\lib\site-packages\pywinauto\handleprops.py in text(handle)
86 length += 1
87
---> 88 buffer_ = ctypes.create_unicode_buffer(length)
89
90 ret = win32functions.SendMessage(
d:\Anaconda3\lib\ctypes_init_.py in create_unicode_buffer(init, size)
286 return buf
287 elif isinstance(init, int):
--> 288 buftype = c_wchar * init
289 buf = buftype()
290 return buf
OverflowError: cannot fit 'int' into an index-sized integer
import pywinauto
app = pywinauto.Application(backend='uia').start('calc.exe')
try this if you are having problem you have to say the backennd is a uia it working fine for me.

ValueError: Value must be one of {'doubleAccounting', 'double', 'singleAccounting', 'single'}

After writing the following code I get the following error. Help would be appreciated in understanding why openpyxl which is designed to work with EXCEL cannot open a basic excel file. Thank you in advance for your help.
import openpyxl
from openpyxl import workbook
from openpyxl import load_workbook
wb = load_workbook(file_name, read_only= True)
ValueError Traceback (most recent call last)
<ipython-input-7-9ebd7e3bdd2c> in <module>()
4
5
----> 6 wb = load_workbook(file_name, read_only= True)
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\reader\excel.py in load_workbook(filename, read_only, keep_vba, data_only, guess_types, keep_links)
199 wb.loaded_theme = archive.read(ARC_THEME)
200
--> 201 apply_stylesheet(archive, wb) # bind styles to workbook
202
203 # get worksheets
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py in apply_stylesheet(archive, wb)
171 return wb
172 node = fromstring(src)
--> 173 stylesheet = Stylesheet.from_tree(node)
174
175 wb._cell_styles = stylesheet.cell_styles
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py in from_tree(cls, node)
97 for k in attrs:
98 del node.attrib[k]
---> 99 return super(Stylesheet, cls).from_tree(node)
100
101
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py in from_tree(cls, node)
70 if hasattr(desc, 'from_tree'):
71 #descriptor manages conversion
---> 72 obj = desc.from_tree(el)
73 else:
74 if hasattr(desc.expected_type, "from_tree"):
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\sequence.py in from_tree(self, node)
84
85 def from_tree(self, node):
---> 86 return [self.expected_type.from_tree(el) for el in node]
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\sequence.py in <listcomp>(.0)
84
85 def from_tree(self, node):
---> 86 return [self.expected_type.from_tree(el) for el in node]
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py in from_tree(cls, node)
87 attrib[tag] = obj
88
---> 89 return cls(**attrib)
90
91
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\styles\fonts.py in __init__(self, name, sz, b, i, charset, u, strike, color, scheme, family, size, bold, italic, strikethrough, underline, vertAlign, outline, shadow, condense, extend)
85 if underline is not None:
86 u = underline
---> 87 self.u = u
88 if strikethrough is not None:
89 strike = strikethrough
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\nested.py in __set__(self, instance, value)
34
35 value = self.from_tree(value)
---> 36 super(Nested, self).__set__(instance, value)
37
38
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\base.py in __set__(self, instance, value)
143 if value == 'none':
144 value = None
--> 145 super(NoneSet, self).__set__(instance, value)
146
147
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\base.py in __set__(self, instance, value)
128 def __set__(self, instance, value):
129 if value not in self.values:
--> 130 raise ValueError(self.__doc__)
131 super(Set, self).__set__(instance, value)
132
ValueError: Value must be one of {'single', 'double', 'singleAccounting', 'doubleAccounting'}
I have tried taking out the read_only part etc. The error has to do with Excel styles. I am using Excel 2016 and the file type is xlxs.
I've found a bug in an Excel processing library called RubyXL, which writes an invalid value to the .xslx file: https://github.com/weshatheleopard/rubyXL/issues/405
Excel tolerates the invalid underline style ement <u val="1"/> written by RubyXL, by interpreting it as a single-underline style, but openpyxl does not tolerate it.
Maybe your file has been corrupted by RubyXL or by another tool with a similar problem?
I've resolved this temporarily by comment the two lines in
"python3.8/site-packages/openpyxl/descriptors/base.py"" file
I just run the code in debug mode, so I can save the change forcedly.

Categories

Resources