I have a Jython script that is used to set up a JDBC datasource on a Websphere 7.0 server. I need to set several properties on that datasource. I am using this code, which works, unless value is '-'.
def setCustomProperty(datasource, name, value):
parms = ['-propertyName', name, '-propertyValue', value]
AdminTask.setResourceProperty(datasource, parms)
I need to set the dateSeparator property on my datasource to just that - a dash. When I run this script with setCustomProperty(ds, 'dateSeparator', '-') I get an exception that says, "Invalid property: ". I figured out that it thinks that the dash means that another parameter/argument pair is expected.
Is there any way to get AdminTask to accept a dash?
NOTE: I can't set it via AdminConfig because I cannot find a way to get the id of the right property (I have multiple datasources).
Here is a solution that uses AdminConfig so that you can set the property value to the dash -. The solution accounts for multiple data sources, finding the correct one by specifying the appropriate scope (i.e. the server, but this could be modified if your datasource exists within a different scope) and then finding the datasource by name. The solution also accounts for modifying the existing "dateSeparator" property if it exists, or it creates it if it doesn't.
The code doesn't look terribly elegant, but I think it should solve your problem :
def setDataSourceProperty(cell, node, server, ds, propName, propVal) :
scopes = AdminConfig.getid("/Cell:%s/Node:%s/Server:%s/" % (cell, node, server)).splitlines()
datasources = AdminConfig.list("DataSource", scopes[0]).splitlines()
for datasource in datasources :
if AdminConfig.showAttribute(datasource, "name") == ds :
propertySet = AdminConfig.list("J2EEResourcePropertySet", datasource).splitlines()
customProp = [["name", propName], ["value", propVal]]
for property in AdminConfig.list("J2EEResourceProperty", propertySet[0]).splitlines() :
if AdminConfig.showAttribute(property, "name") == propName :
AdminConfig.modify(property, customProp)
return
AdminConfig.create("J2EEResourceProperty", propertySet[0], customProp)
if (__name__ == "__main__"):
setDataSourceProperty("myCell01", "myNode01", "myServer", "myDataSource", "dateSeparator", "-")
AdminConfig.save()
Please see the Management Console preferences settings. You can do what you are attempting now and you should get to see the Jython equivalent that the Management Console is creating for its own use. Then just copy it.
#Schemetrical solution worked for me. Just giving another example with jvm args.
Not commenting on the actual answer because I don't have enough reputation.
server_name = 'server1'
AdminTask.setGenericJVMArguments('[ -serverName %s -genericJvmArguments "-agentlib:getClasses" ]' % (server_name))
Try using a String instead of an array to pass the parameters using double quotes to surround the values starting with a dash sign
Example:
AdminTask.setVariable('-variableName JDK_PARAMS -variableValue "-Xlp -Xscm250M" -variableDescription "-Yes -I -can -now -use -dashes -everywhere :-)" -scope Cell=MyCell')
Related
I can successfully add a printer using the pycups module, and can print a test page, but how can I modify the default options in ppd?
The default values and options list for all options can be easily obtained with the following code, but when I try to modify the default values, it doesn't work.
ppd = cups.PPD(ppdfile)
groups = ppd.optionGroups
for group in groups:
for opt in group.options:
print (opt.keyword + ":" + opt.defchoice)
print (list (map (lambda x: x["text"], opt.choices)))
Below is my code to modify the options,After the operation is completed, it does not work.
ppd.markOption('StpColorPrecision','Normal')
ppd.markOption('PageSize:','w432h576-div2')
I found a lot of information, but there are no related problems. Only this is related to the introduction of custom size, but the author did not give a reply.
set custom default page size
I am accessing an Intersystems cache 2017.1.xx instance through a python process to get various attributes about the database in able to monitor the database.
One of the items I want to monitor is license usage. I wrote a objectscript script in a Terminal window to access license usage by user:
s Rset=##class(%ResultSet).%New("%SYSTEM.License.UserListAll")
s r=Rset.Execute()
s ncol=Rset.GetColumnCount()
While (Rset.Next()) {f i=1:1:ncol w !,Rset.GetData(i)}
But, I have been unable to determine how to convert this script into a Python equivalent. I am using the intersys.pythonbind3 import for connecting and accessing the cache instance. I have been able to create python functions that accessing most everything else in the instance but this one piece of data I can not figure out how to translate it to Python (3.7).
Following should work (based on the documentation):
query = intersys.pythonbind.query(database)
query.prepare_class("%SYSTEM.License","UserListAll")
query.execute();
# Fetch each row in the result set, and print the
# name and value of each column in a row:
while 1:
cols = query.fetch([None])
if len(cols) == 0: break
print str(cols[0])
Also, notice that InterSystems IRIS -- successor to the Caché now has Python as an embedded language. See more in the docs
Since the noted query "UserListAll" is not defined correctly in the library; not SqlProc. So to resolve this issue would require a ObjectScript with the query and the use of #Result set or similar in Python to get the results. So I am marking this as resolved.
Not sure which Python interface you're using for Cache/IRIS, but this Open Source 3rd party one is worth investigating for the kind of things you're trying to do:
https://github.com/chrisemunt/mg_python
I am a newbie in Python. I have to extract emails from Outlook and get all attributes/properties of the emails.
Retrieving properties one by one, for the attributes/properties that I know they exist works fine (.Subject, .Body, etc.).
But, I need to get all possible attributes. That's where my problem is.
I have been looking for hours, the only answers I found were using:
vars()
dir()
inspect.getmembers(obj)
__dict__
etc.
Which does not give me the list of properties like:
.Subject
.Body
.SentOn
etc.
Could someone help ?
Here is the extract of my test Notebook :
####### Retrieve email from Outlook #######
import win32com.client
objOutlookMAPI=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
### Define folder
objOlFolder = objOutlookMAPI.GetDefaultFolder(6)
### Retrieve ant print email
objOlMessages = objOlFolder.Items
# objMessage : class 'win32com.client.CDispatch'
objMessage = objOlMessages.GetLast()
print(objMessage.Subject)
> Are you going to Las Vegas for Black Hat, DefCon, Bsides, or Hacking Diversity? Either or join us on our adventures!
vars(objMessage)
> {'_builtMethods_': {},
'_enum_': None,
'_lazydata_': (<PyITypeInfo at 0x0000021EC7B7D170 with obj at 0x0000021EC7B4B2F8>,
<PyITypeComp at 0x0000021EC7B7D620 with obj at 0x0000021EC7B4B058>),
'_mapCachedItems_': {},
'_oleobj_': <PyIDispatch at 0x0000021EC7B7D290 with obj at 0x0000021EC7B4AAA8>,
'_olerepr_': <win32com.client.build.LazyDispatchItem at 0x21ec8a7ba90>,
'_unicode_to_string_': None,
'_username_': 'GetLast'}
dir(objMessage)
#import inspect
#inspect.getmembers(objMessage)
> [`'_ApplyTypes_'`,
`'_FlagAsMethod'`,
`'_LazyAddAttr_'`,
`'_NewEnum'`,
`'_Release_'`,
`'__AttrToID__'`,
`'__LazyMap__'`,
`'__bool__'`,
`'__call__'`,
`'__class__'`,
`'__delattr__'`,
`'__dict__'`,
`'__dir__'`,
`'__doc__'`,
`'__eq__'`,
`'__format__'`,
`'__ge__'`,
`'__getattr__'`,
`'__getattribute__'`,
`'__getitem__'`,
`'__gt__'`,
`'__hash__'`,
`'__init__'`,
`'__init_subclass__'`,
`'__int__'`,
`'__le__'`,
`'__len__'`,
`'__lt__'`,
`'__module__'`,
`'__ne__'`,
`'__new__'`,
`'__reduce__'`,
`'__reduce_ex__'`,
`'__repr__'`,
`'__setattr__'`,
`'__setitem__'`,
`'__sizeof__'`,
`'__str__'`,
`'__subclasshook__'`,
`'__weakref__'`,
`'_builtMethods_'`,
`'_enum_'`,
`'_find_dispatch_type_'`,
`'_get_good_object_'`,
`'_get_good_single_object_'`,
`'_lazydata_'`,
`'_make_method_'`,
`'_mapCachedItems_'`,
`'_oleobj_'`,
`'_olerepr_'`,
`'_print_details_'`,
`'_proc_'`,
`'_unicode_to_string_'`,
`'_username_'`,
`'_wrap_dispatch_'`]
For posterity here, I found what I needed in the AppointmentItem object on this page:
Outlook Visual Basic for Applications (VBA) reference
Just expand that object on the left side of the page, and then expand properties. Found everything I needed there. Also a MeetingItem object, still in the process of figuring out the difference (which sounds like it's obvious, but a lot of the appointments I'm getting back are actually meetings (i.e. have attendees).
I found a way to do it, actually:
The plan is to create a macro in a second presentation that you call from within python and that is, with the help of tlbinf32.dll, able to get all members of an object.
The Second Presentation
To start, you want to download the tlbinf32.dll.
FOR 64-bit SYSTEMS: Follow this guide to properly set up the 32-bit-DLL! I also had problems with the HP Print Scan Doctor Service: I needed to disable that service and uninstall HP Smart. (and reboot)
Create a new .pptm file (pptx with macros) and open it (I named it GetMembersUtil.pptm)
In that presentation, create a new macro (the name is irrelevant) and edit it (View->Macros)
Add a reference to your tlbinf32.dll that you just downloaded (Tools->References)
Paste the following function after the macro
Function GetMembers(obj)
' Declare vars
Dim TLI
Dim TypeInfo
Dim Members
' Create new ArrayList since we don't know how many Members obj has
Set Members = CreateObject("System.Collections.ArrayList")
' Initialize tlbinf
Set TLI = CreateObject("TLI.TLIApplication")
Set TypeInfo = TLI.InterfaceInfoFromObject(obj)
' iterate over each Member
For Each MemberInfo In TypeInfo.Members
Members.Add MemberInfo.Name
Next
' Convert ArrayList back to native vba Array because you can't return an ArrayList
GetMembers = Members.ToArray()
End Function
this function takes an object as input and returns all the members of that object
Save your presentation in the local directory of your python file
The Python Side
To be able to use the macro we need to make sure that the presentation we just created is openend
def vba_get_members(app: win32com.client.CDispatch, obj: win32com.client.CDispatch) -> tuple[str, ...]:
# os.path.abspath is very important
ensure_opened(app, os.path.abspath("GetMembersUtil.pptm"))
return app.Run("GetMembersUtil.pptm!GetMembers", obj)
def ensure_opened(app: win32com.client.CDispatch, file_path):
# check if presentation is already opened
for presentation in app.Presentations:
pp_filepath = os.path.join(presentation.Path, presentation.Name)
if pp_filepath == file_path:
# presentation already opened
break
else:
# presentation wasn't already opened
app.Presentations.Open(file_path)
I'm trying to create an OrientDB graph database using PyOrient, and I can't find enough documentation to allow me to get Functions working. I've been able to create a function using record_create into the ofunction cluster, but although it doesn't crash, it doesn't appear to work either.
Here's my code:
#!/usr/bin/python
import pyorient
ousername="user"
opassword="pass"
client = pyorient.OrientDB("localhost", 2424)
session_id = client.connect( ousername, opassword )
db_name="database"
client.db_create( db_name, pyorient.DB_TYPE_GRAPH, pyorient.STORAGE_TYPE_PLOCAL )
# Set up the schema of the database
client.command( "create class URL extends V" )
client.command( "CREATE PROPERTY URL.url STRING")
client.command( "CREATE PROPERTY URL.id INTEGER")
client.command( "CREATE SEQUENCE urlseq")
client.command( "CREATE INDEX urls ON URL (url) UNIQUE")
# Get the id numbers of all the clusters
info=client.db_reload()
clusters={}
for c in info:
clusters[c.name]=c.id
print(clusters)
# Construct a test function
# All this should do is create a new URL vertex. Eventually it will check for uniqueness of url, etc.
code="INSERT INTO URL SET id = sequence('urlseq').next(), url='?'"
addURL_func = { '#OFunction': { 'name': 'addURL', 'code':'orient.getGraph().command("sql","%s",[urlparam]);' % code, 'language':'javascript', 'parameters':'urlparam', 'idempotent':False } }
client.record_create( clusters['ofunction'], addURL_func )
# Assume allURLs contains the list of URLs I want to store
for url in allURLs:
client.command("select addURL('%s')" % url)
vs = client.command("select * from URL")
for v in vs:
print(v.url)
Doing all the select addURL bits runs happily, but doing select * from URL simply times out. Presumably because (as I've discovered by examining the database in Studio) there are still no URL vertices. Although why that should timeout rather than returning an empty list or giving a useful error message, I'm not sure.
What am I doing wrong, and is there an easier way to create Functions through PyOrient?
I don't want to just write the Functions in Studio, because I am prototyping and want them written from the Python code rather than being lost every time I drop the mangled experimental graph!
I've mainly been using the OrientDB wiki page to find out about OrientDB functions, and the PyOrient github page as almost my only source of documentation for that.
Edit: I've been able to create a working Function in SQL (see my own answer below) but I still can't create a working Javascript Function which creates a vertex. My current best attempt is:
code2="""var g=orient.getGraph();g.command('sql','CREATE VERTEX URL SET id = sequence(\\"urlseq\\").next(), url = \\"'+urlparam+'\\"',[urlparam]);"""
myFunction2 = 'CREATE FUNCTION addURL2 "' + code2 + '" parameters [urlparam] idempotent false language javascript'
client.command(myFunction2)
which runs without crashing when called from PyOrient, but doesn't actually create any vertices. But if I call it from Studio, it works!?! I have no idea what's going on.
OK, after a lot of hacking and Googling, I've got it working:
code="CREATE VERTEX URL SET id = sequence('urlseq').next(), url = :urlparam;"
myFunction = 'CREATE FUNCTION addURL "' + code + '" parameters [urlparam] idempotent false language sql'
client.command(myFunction)
The key here seems to be the use of a colon before parameter names in OrientDB's version of SQL. I couldn't find any reference to this anywhere in the OrientDB docs, but someone online had discovered it somehow.
I'm answering my own question in the hope that this will help others struggling wth ODB's poor documentation!
You could try something like :
code="var g=orient.getGraph();\ng.command(\\'sql\\',\\'%s\\',[urlparam]);"
myFunction = "CREATE FUNCTION addURL '" + code + "' parameters [urlparam] idempotent false language javascrip"
client.command(myFunction);
UPDATE
I used this code (version 2.2.5) and it worked for me
code="var g=orient.getGraph().command(\\'sql\\',\\'%s\\',[urlparam]);"
myFunction = "CREATE FUNCTION addURL '" + code + "' parameters [urlparam] idempotent false language javascrip"
client.command(myFunction);
Hope it helps
Using WMI within Python to request data from other servers. I know my credentials are correct, as I can hard-code them in the file and connect without issues. However, my string formatting for variables doesn't seem to be working.
I've tried both of these with no luck:
wmi_sql = wmi.WMI(SQLServer_raw, user="%s\\%s", password="%s") % (sql_domain, sql_user, sql_pass)
and
wmi_sql = wmi.WMI(SQLServer_raw, user="{0}\\{1}", password="{2}").format(sql_domain, sql_user, sql_pass)
Tried moving the format() call inside, but it didn't work either:
wmi_sql = wmi.WMI(SQLServer_raw, user="{0}\\{1}", password="{2}".format(sql_domain, sql_user, sql_pass))
You've got the string formatters in the wrong place. They need to be used for each string, not the result of the call. As written, python thinks you want to call wmi.WMI and then apply the formatting to whatever is returned.
Try:
wmi_sql = wmi.WMI(SQLServer_raw, user="%s\\%s" % (sql_domain, sql_user),
password=sql_pass)
In one and two you are executing wmi.WMI() and then doing the formatting on the return type. In the third example you are formatting the value of the password but providing three parameters to it hoping it would build user variable. If you really want to build user and password dynamically do this:
usr ="{0}\\{1}".format(sql_domain,ql_user)
wmi.WMI(SQLServer_raw, user=usr, password=sql_pass)