Openoffice3.1 pyuno confusing errors - python

I'm trying to get the sample and other sample codes i find for pyuno running with openoffice 3.1.1 and python 2.5 with no luck.
Unfortunately, pyuno does not give any clues about what goes wrong.
In [1]: import uno
In [2]: local = uno.getComponentContext()
In [3]: resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
---------------------------------------------------------------------------
com.sun.star.uno.RuntimeException Traceback (most recent call last)
/opt/openoffice.org/basis3.1/program/ in ()
com.sun.star.uno.RuntimeException: : 'tuple' object has no attribute 'getTypes', traceback follows
no traceback available
below is the output of execution of /opt/openoffice.org/basis3.1/program/officehelper.py
which basically boots the headless office instance and returns a related context object.
den#ev:/opt/openoffice.org/basis3.1/program > python officehelper.py
Traceback (most recent call last):
File "officehelper.py", line 42, in
from com.sun.star.connection import NoConnectException
File "uno.py", line 273, in _uno_import
RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
RuntimeError: pyuno.getClass: expecting one string argument
pyuno takes only 1 argument and it hasto be a string, as defined in http://udk.openoffice.org/source/browse/udk/pyuno/source/module/pyuno_module.cxx?rev=1.14&view=markup
i could not manage to get pyuno.getClass work anyway.
any suggestions about how to get pyuno working?

In [1]: import uno
In [2]: local = uno.getComponentContext()
In [3]: resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
OOP gone wrong, imho. i know its OT, but i tried getting uno to work before, and gave up. this is pure Steve Yegge Prose (read up on http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html).
when you translate those lines into a more speakable form, they come out roughly as:
"Let 'local' be the result of calling method 'get component context' of 'uno'. Let the 'service manager' be the attribute 'service manager' of 'local'. Let 'resolver' be the result of calling the 'service manager' method 'create instance with context', using arguments 'com sun star bridge uno url resolver' and 'local'."
omg. no surprise something is wrong with a program that is so atrociously over-specific, convoluted, and self-referential while being not self-aware... you call a sub-method of 'local' and that sub-method has to be told what 'local' means? say what? hats off to the fearless developers who can cut through this. happy debugging.
ADDED:
thx for comment and points.
the pyuno problem i cannot do anything about in fact, but i encourage to persue a patient trytrytry approach with a clear deadline.
i also suggest to file an outright B.U.G. with the pyuno people (if they are in fact active—i got the impression that this was a rather silent project) because of the nonsense error message: the method in question appears to request one string argument, and it gets one, and it complains it did. this is so not helpful to the degree it becomes reasonable to declare a code fault.
in this kind of situation i often look into the sources. but you already did that, right?
i hate people to ask back ‘why do you want to do this?’ when i ask for help. however, sometimes someone (maybe you) does come up with another workable path in the process, one that does not include a solution to the particular problem, but helps to solve the superordinate one. so, if i may ask: what is the big picture?

Related

What causes this Attribute Error encountered when implementing LangChain's OpenAI LLM wrapper?

This is my first post here. I'm building a Python window application with PyQt5 that implements interactions with the OpenAI completions endpoint. So far, any code that I've written myself has performed fine, and I was reaching the point where I wanted to start implementing long-term memory for conversational interactions. I started by just running my own chain of prompts for categorizing and writing topical subjects and summaries to text files, but I decided it best to try exploring open source options to see how the programming community is managing things. This led me to LangChain, which seems to have some popular support behind it and already implements many features that I intend.
However, I have not had even the tiniest bit of success with it yet. Even the most simple examples don't perform, regardless of what context I'm implementing it in (within a class, outside a class, in an asynchronous loop, to the console, to my text browsers within the main window, whatever) I always get the same error message.
The simplest possible example:
import os
from langchain.llms import OpenAI
from local import constants #For API key
os.environ["OPENAI_API_KEY"] = constants.OPENAI_API_KEY
davinci = OpenAI(model_name= 'text-davinci-003', verbose=True, temperature=0.6)
text = "Write me a story about a guy who is frustrated with Python."
print("Prompt: " + text)
print(davinci(text))
It capably instantiates the wrapper and prints the prompt to the console, but at any point a command is sent through the wrapper's functions to receive generated text, it encounters this AttributeError.
Here is the traceback:
Traceback (most recent call last):
File "D:\Dropbox\Pycharm Projects\workspace\main.py", line 16, in <module>
print(davinci(text))
File "D:\Dropbox\Pycharm Projects\workspace\venv\lib\site-packages\langchain\llms\base.py", line 255, in __call__
return self.generate([prompt], stop=stop).generations[0][0].text
File "D:\Dropbox\Pycharm Projects\workspace\venv\lib\site-packages\langchain\llms\base.py", line 128, in generate
raise e
File "D:\Dropbox\Pycharm Projects\workspace\venv\lib\site-packages\langchain\llms\base.py", line 125, in generate
output = self._generate(prompts, stop=stop)
File "D:\Dropbox\Pycharm Projects\workspace\venv\lib\site-packages\langchain\llms\openai.py", line 259, in _generate
response = self.completion_with_retry(prompt=_prompts, **params)
File "D:\Dropbox\Pycharm Projects\workspace\venv\lib\site-packages\langchain\llms\openai.py", line 200, in completion_with_retry
retry_decorator = self._create_retry_decorator()
File "D:\Dropbox\Pycharm Projects\workspace\venv\lib\site-packages\langchain\llms\openai.py", line 189, in _create_retry_decorator
retry_if_exception_type(openai.error.Timeout)
AttributeError: module 'openai.error' has no attribute 'Timeout'
I don't expect that there is a fault in the LangChain library, because it seems like nobody else has experienced this problem. I imagine I may have some dependency issue? Or I do notice that others using the LangChain library are doing so in a notebook development environment, and my lack of familiarity in that regard is making me overlook some fundamental expectation of the library's use?
Any advice is welcome! Thanks!
What I tried: I initially just replaced my own function for managing calls to the completion endpoint with one that issued the calls through LangChain's llm wrapper. I expected it to work as easily as my own code had, but I received that error. I then stripped everything apart layer by layer attempting to instantiate the wrapper at every scope of the program, then I attempted to make the calls in an asynchronous function through a loop that waited to completion, and no matter what, I always get that same error message.
I think it might be something about your current installed versions of Python, OpenAI, and/or LangChain. Maybe try using a newer version of Python and OpenAI. I'm new to Python and these things but hopefully I could help.

can not find the reason for 'name not defined' in python code

Excuse the debugging question, new to coding in general. Cannot understand why my code suddenly wont run.
I have checked for typos which seems to not be my problem.
filepath = '/proper_noun.txt'
def pluralize(word):
proper_nouns = [line.strip() for line in open (filepath)]
for item in proper_nouns: ### print out the list once.
if (item==[-1]):
break;
currently working in google colab.
At this point, I'm just trying to return the items from 'proper_nouns' into a list to get the ball rolling. Any ideas?
print (proper_nouns)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-29-c6832e0493e8> in <module>()
----> 1 print (proper_nouns)
NameError: name 'proper_nouns' is not define
Thanks guys. I hope this question follows SOF etiquette
Since you are working on Google Colab, my guesss is that you accidentally don't run the code from the beginning (from example if you selected the code starting from for item in proper_nouns: and only run the selected part, or if you split your program in different cells), and therefore proper_nouns is not defined yet.
Please make sure you run everything and tell us if that was it.
EDIT: I just thought of another option: is the line print(proper_nouns) in the pluralize function? If not, the scope of proper_nouns being the function, it's normal that it is not defined outside of the function. To access it from the outside, you must either declare it outside the function, or return it.

CATIA V5 Automation with Python Script

I'm a Python beginner and am attempting to do some automation in CATIA (Dassault Systemes CAD pacakge) with it, but I've run into an issue that I've been unable to solve despite searching extensively for a solution.
I'm trying to mimic the behavior of this VBA macro that was written within CATIAs native editor interface:
Sub CATMain()
Dim drawingDocument1 As DrawingDocument
Set drawingDocument1 = CATIA.ActiveDocument
Dim selection1 As Selection
Set selection1 = drawingDocument1.Selection
selection1.Search "CATDrwSearch.DrwDimension,all"
For i = 1 To selection1.Count
Dim Dimension1 As DrawingDimension
Set Dimension1 = selection1.Item(i).Value
Dim DimDimValue As DrawingDimValue
Set DimDimValue = Dimension1.GetValue
DimDimValue.SetFormatPrecision 1, 0.001
Next
selection1.Clear
End Sub
To do so I wrote this Python script:
import win32com.client
CATIA = win32com.client.Dispatch('CATIA.Application')
ad = CATIA.ActiveDocument
sel = ad.Selection
sel.Search("CATDrwSearch.DrwDimension,all")
for i in range(1, sel.Count2+1):
aDim = sel.Item2(i).Value
aDimValue = aDim.GetValue
aDimValue.SetFormatPrecision(1,0.001)
sel.Clear
Everything works except for the last operation within the for loop which returns the error:
Traceback (most recent call last):
<bound method DrawingDimension.GetValue of <win32com.gen_py.CATIA V5
DraftingInterfaces Object Library.DrawingDimension instance at 0x67582896>>
File "C:/...", line 15, in <module>
aDimValue.SetFormatPrecision(1,0.001)
AttributeError: 'function' object has no attribute 'SetFormatPrecision'
Note that I used makepy to early bind the COM object otherwise Python doesn't recognize it (returns COMObject [unknown]), but from what I understand that shouldn't impact the script behavior.
I haven't been able to troubleshoot the error successfully because everything I can find suggests the object should have the attribute SetFormatPrecision. I've tried a bunch of other attributes that it should have as well, and none of them work. Because I'm trying to operate on a COM object, I'm not aware of a way to get a comprehensive list of legal attributes, or a way to get any information on the type of object I have stored in aDimValue
I inspected the makepy output file and it does include a function definition for SetFormatPrecision so my guess is I have a syntax issue, but I'm at a loss for what it is.
I know it's a narrowly focused question, but I'm hoping somebody with knowledge of CATIA Object Libraries sees this. And although I don't expect it, if somebody wants to go the extra mile, there's documentation on CATIAs Object Libraries here:
http://catiadoc.free.fr/online/CAAScdBase/CAAScdAutomationHome.htm
Drafting > Drafting Reference > DrawingDimValue
to get to the specific object I think I'm working with in aDimValue
Any help is appreciated. Thanks.
aDim.GetValue returns the function object, rather than calling the function. Use aDim.GetValue(). Same with sel.Clear() on the last line.

Why is there different behaviour from getpwuid and getgrgid?

In Python 2.7, 3.4 and 3.5, grp.getgrgid is capable of accepting a string:
from grp import getgrgid
print(getgrgid('0'))
However, pwd.getpwuid can't do the same:
from pwd import getpwuid
print(getpwuid('0'))
Traceback (most recent call last):
File "getpwuid_test.py", line 2, in <module>
print(getpwuid('0'))
TypeError: an integer is required
This is because inside Modules/pwdmodule.c, getpwuid uses PyNumber_ParseTuple with a converter that uses PyNumber_Index to get a Python integer, and that raises an exception on failure.
However, in Modules/grpmodule.c, grp_getgrgid uses PyNumber_Long (Or PyNumber_Int for an old enough Python) as a conversion first, and as the documentation says at https://docs.python.org/3/c-api/number.html, this is the equivalent of running int(o), which can convert a string to an integer. Only then is it given to PyNumber_Index, by way of a helper function _Py_Gid_Converter
What is the reason for this difference? Is it a deliberate choice based on some history?
The behaviour of getgrgid seems more helpful, and it's odd that it doesn't apply to both functions. Is this undesirable behaviour in getgrgid or getpwuid?
The short answer is because humans are fallible and mistakes happen. Some are doozies and get noticed quickly, others are minor and can go years without detection.
Thank you for helping make Python better!

Registering an Object on DBus using pythons Gio-Bindings

I'm working on a Python-Clone of an existing C-Project. The C-Project Connects to a custom DBus and offers a Object there for getting Callbacks.
I tried to replicate this using Python with code that basically boils down to:
def vtable_method_call_cb(connection, sender, object_path, interface_name, method_name, parameters, invocation, user_data):
print('vtable_method_call_cb: %s' % method_name)
connection = Gio.DBusConnection.new_for_address_sync(
"unix:abstract=gstswitch",
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT,
None,
None)
node_info = Gio.DBusNodeInfo.new_for_xml(introspection_xml)
vtable = Gio.DBusInterfaceVTable()
vtable.method_call(vtable_method_call_cb)
vtable.get_property(None)
vtable.set_property(None)
connection.register_object(
"/info/duzy/gst/switch/SwitchUI",
node_info.interfaces[0],
vtable,
None,
None)
The code fails when creating the vtable at the vtable.method_call call (but get_property fails, too, when I comment one call out) the following log/traceback:
** (process:18062): WARNING **: Field method_call: Interface type 2 should have is_pointer set
Traceback (most recent call last):
File "moo.py", line 69, in <module>
vtable.method_call(vtable_method_call_cb)
RuntimeError: unable to get the value
I was not able to find code using register_object() in python, so I'm unsure if this part of Gio should be usable or if it's just not complete.
This certainly not what you'll want to hear, but you have hit a 4 year old bug in the GDBus Python bindings that makes it impossible to register objects on the bus. A patch had been proposed quite some time ago, but every time it looked like it was actually going to land, some GNOME developer found something he/she did not like something about it, a new patch was proposed... and nothing happend for most of the next year. This cycle has already happend 3 times and I do not know if there is much hope that it will be broken anytime soon...
Basically the GNOME developers themselves more or less suggested that people use dbus-python until this issue is finally fixed, so I guess you should be heading here instead. :-/
BTW: I think you source code is wrong (aside from the fact that it won't work either way). To create the VTable you would actually be written something like this, I think:
vtable = Gio.DBusInterfaceVTable()
vtable.method_call = vtable_method_call_cb
vtable.get_property = None
vtable.set_property = None
But since the bindings are broken you are just trading an exception with an abort() here... :-(
If the patch actually makes it into python-gi in the current form the vtable would be dumped entirely (YEAH!) and connection.register_object call would become:
connection.register_object_with_closures(
"/info/duzy/gst/switch/SwitchUI",
node_info.interfaces[0],
vtable_method_call_cb, # vtable.method_call
None, # vtable.get_property
None) # vtable.set_property
Update
It appears this has now finally been fixed! You can now export object using g_dbus_connection_register_object_with_closures:
def vtable_method_call_cb(connection, sender, object_path, interface_name, method_name, parameters, invocation, user_data):
print('vtable_method_call_cb: %s' % method_name)
connection = Gio.DBusConnection.new_for_address_sync(
"unix:abstract=gstswitch",
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT,
None,
None)
node_info = Gio.DBusNodeInfo.new_for_xml(introspection_xml)
connection.register_object(
"/info/duzy/gst/switch/SwitchUI",
node_info.interfaces[0],
vtable_method_call_cb,
None,
None)

Categories