I try to code a Find & Replace method with Python in LibreOffice's Calc to replace all the ".+" with "&" (in a single column - not so important) - unfortunately, even a standard Find & Replace method seems to be impossible (to me). That's what I have up to now:
import uno
def search()
desktop = XSCRIPTCONTEXT.getDesktop()
document = XSCRIPTCONTEXT.getDocument()
ctx = uno.getComponentContext()
sm = ctx.ServiceManager
dispatcher = sm.createInstanceWithContext("com.sun.star.frame.DispatchHelper", ctx)
model = desktop.getCurrentComponent()
doc = model.getCurrentController()
sheet = model.Sheets.getByIndex(0)
replace = sheet.createReplaceDescriptor()
replace.SearchRegularExpression = True
replace.SearchString = ".+$"
replace.ReplaceString ="&"
return None
And what happens: totally nothing! I will be happy and thankful for every hint, sample code and motivating words!
This code changes all non-empty cells in column A to &:
def calc_search_and_replace():
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
sheet = model.Sheets.getByIndex(0)
COLUMN_A = 0
cellRange = sheet.getCellRangeByPosition(COLUMN_A, 0, COLUMN_A, 65536);
replace = cellRange.createReplaceDescriptor()
replace.SearchRegularExpression = True
replace.SearchString = r".+$"
replace.ReplaceString = r"\&"
cellRange.replaceAll(replace)
Notice that the code calls replaceAll to actually do something. Also, from the User Guide:
& will insert the same string found with the Search RegExp.
So the replace string needs to be literal -- \&.
Related
I am writing a JavaScript crawler application.
The application needs to open JavaScript files and find some specific code in order to do some stuff with them.
I am using regular expressions to find the code of interest.
Consider the following JavaScript code:
let nlabel = rs.length ? st('string1', [st('string2', ctx = 'ctx2')], ctx = 'ctx1') : st('Found {0}', [st(this.param)]);
As you can see there is the st function which is called three times in the same line. The first two calls have an extra parameter named ctx but the third one doesn't have it.
What I need to do is to have 3 re matches as below:
Match 1
Group: function = "st('"
Group: string = "string1"
Group: ctx = "ctx1"
Match 2
Group: function = "st('"
Group: string = "string2"
Group: ctx = "ctx2"
Match 3
Group: function = "st('"
Group: string = "Found {0}"
Group: ctx = (None)
I am using the regex101.com to test my patterns and the pattern that gives the closest thing to what I am looking for is the following:
(?P<function>st\([\"'])(?P<string>.+?(?=[\"'](\s*,ctx\s*|\s*,\s*)))
You can see it in action here.
However, I have no idea how to make it return the ctx group the way I want it.
For your reference I am using the following Python code:
matches = []
code = "let nlabel = rs.length ? st('string1', [st('string2', ctx = 'ctx2')], ctx = 'ctx1') : st('Found {0}', [st(this.param)], ctx = 'ctxparam'"
pattern = "(?P<function>st\([\"'])(?P<string>.+?(?=[\"'](\s*,ctx\s*|\s*,\s*)))"
for m in re.compile(pattern).finditer(code):
fnc = m.group('function')
msg = m.group('string')
ctx = m.group('ctx')
idx = m.start()
matches.append([idx, fnc, msg, ctx])
print(matches)
I have the feeling that re alone isn't capable to do exactly what I am looking for but any suggestion/solution which gets closer is more than welcome.
I am trying to create rules to move emails from a long list of senders to specific folders. For example, if I receive an email from john#email.com, I want it to be moved from "Inbox" to "workstuff\John" (john is a subfolder of workstuff).
I'm using comtypes.clients and python to do this because I found a similar post ( Setting a property using win32com ), in which one of the answers uses comtypes.clients in python.
I am also using https://learn.microsoft.com/en-us/office/vba/outlook/how-to/rules/create-a-rule-to-move-specific-e-mails-to-a-folder as a guideline.
import comtypes.client
o = comtypes.client.CreateObject("Outlook.Application")
rules = o.Session.DefaultStore.GetRules()
rule = rules.Create("Test", 0)
condition = rule.Conditions
condition.From.Recipients.Add(str("fabracht"))
condition.From.Recipients.ResolveAll
#.From.Recipients("fabracht#gmail.com")
condition.Enabled = True
root_folder = o.GetNamespace('MAPI').Folders.Item(1)
dest_folder = root_folder.Folders["Evergreen1"].Folders["Chemistry"]
move = rule.Actions.MoveToFolder
move.__MoveOrCopyRuleAction__com__set_Enabled(True)
move.__MoveOrCopyRuleAction__com__set_Folder(dest_folder)
rules.Save()
I've been able to create the rule, which shows up in outlook. But the rule is missing the "from" part. Basically it says:
" Apply this rule after the message arrives
Move it to the john folder "
I expected the rule to be:
" Apply this rule after the message arrives
From john#email.com
Move it to the john folder "
The article mentioned in your post contains the following code for dealing with the From part:
'Specify the condition in a ToOrFromRuleCondition object
'Condition is if the message is from "Eugene Astafiev"
Set oFromCondition = oRule.Conditions.From
With oFromCondition
.Enabled = True
.Recipients.Add ("Eugene Astafiev")
.Recipients.ResolveAll
End With
The code should look like the following:
import comtypes.client
o = comtypes.client.CreateObject("Outlook.Application")
rules = o.Session.DefaultStore.GetRules()
rule = rules.Create("Test", 0)
condition = rule.Conditions
condition.From.Recipients.Add(str("fabracht"))
condition.From.Recipients.ResolveAll
oFromCondition = oRule.Conditions.From
oFromCondition.Enabled = True
oFromCondition.Recipients.Add("john#email.com")
oFromCondition.Recipients.ResolveAll
#.From.Recipients("fabracht#gmail.com")
condition.Enabled = True
root_folder = o.GetNamespace('MAPI').Folders.Item(1)
dest_folder = root_folder.Folders["Evergreen1"].Folders["Chemistry"]
move = rule.Actions.MoveToFolder
move.__MoveOrCopyRuleAction__com__set_Enabled(True)
move.__MoveOrCopyRuleAction__com__set_Folder(dest_folder)
rules.Save()
Using python 3, I made the following script consisting of a model class containing hundreds of bytearrays and in the same script outside of model class i am printing some of these out to verify they are correct. When i print the values some of values are not what i expected.(i put coded comments to identify these in the code below)
Here is a shortend version of my script with some of the bytearrays
`
class Model:
def __init__(self):
# weird values:
self.bp_diastole_118 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02\x3b')
self.bp_diastole_120 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02\x3c')
self.bp_diastole_122 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02\x3d')
self.bp_diastole_124 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02\x3e')
self.bp_diastole_126 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02\x3f')
self.bp_diastole_128 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02\x40')
self.bp_diastole_160 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02\x50')
# correct values:
self.pupil_r_normal = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc3')
self.pupil_r_dilated = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc4')
self.pupil_r_constriced = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc5')
self.pupil_r_reaction_on = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc6')
self.pupil_r_reaction_off = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc7')
m = Model()
print('--------------weird value------------------')
print('bp_diastole_118 = {}'.format(m.bp_diastole_118))
print('bp_diastole_120 = {}'.format(m.bp_diastole_120))
print('bp_diastole_122 = {}'.format(m.bp_diastole_122))
print('bp_diastole_124 = {}'.format(m.bp_diastole_124))
print('bp_diastole_126 = {}'.format(m.bp_diastole_126))
print('bp_diastole_128 = {}'.format(m.bp_diastole_128))
print('bp_diastole_160 = {}'.format(m.bp_diastole_160))
print('-------------correct value--------------------')
print('pupil_r_normal = {}'.format(m.pupil_r_normal))
print('pupil_r_dilated = {}'.format(m.pupil_r_dilated))
print('pupil_r_constriced = {}'.format(m.pupil_r_constriced))
print('pupil_r_reaction_on = {}'.format(m.pupil_r_reaction_on))
print('pupil_r_reaction_off = {}'.format(m.pupil_r_reaction_off))
here is what is printed to the console:
`
--------------weird value------------------
bp_diastole_118 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02;')
bp_diastole_120 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02<')
bp_diastole_122 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02=')
bp_diastole_124 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02>')
bp_diastole_126 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02?')
bp_diastole_128 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02#')
bp_diastole_160 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02P')
-------------correct value--------------------
pupil_r_normal = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc3')
pupil_r_dilated = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc4')
pupil_r_constriced = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc5')
pupil_r_reaction_on = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc6')
pupil_r_reaction_off = bytearray(b'\xff\x01\x02\x01\x01\x00\x03\xc7')
As you can see the good values print exactly what i would expect and are identical to the values i initialized. However if you look at what was printed from the weird values you can see the last 3 characters do not match the values i initialized.
i.e.
initialized:
self.bp_diastole_118 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02\x3b')
is not the same as printed:
bp_diastole_118 = bytearray(b'\xff\x01\x02\x01\x01\x00\x02;')
Does anybody know why this is happening and how I could remedy the problem?
you are seeing the utf representation of the hex value you set for example utf('0x3b') == ';'
The problem I found is x3b through x50 they seem to be outputting the last part as special character with x50 being P. If you test using bytearray(b'\x3b') it will display the ending for you
Is it possible to get the associated FbxNode from the enum ENodeId ?
for example if i want to get the FbxNode from the Character::eLeftHand
I tried to use Character::GetCharacterLink(ENodeId, FbxCharacterLink)
then extracting the FbxNode from FbxCharacterLink simply by calling FbxCharacterLink::mNode
However this function returns for most ENodeIds False, so no FbxCharacterLink is created.
character = myScene.GetCharacter(0)
lefthand = character.eLeftHand
lefthand_node = FbxCharacterLink()
character.GetCharacterLink(lefthand, lefthand_node) # False
lefthand_node = lefthand_node.mNode
when I was scripting inside Motionbuilder using Python and Pyfbxsdk, it was very easy, no matter how the skeleton objects are named, I can get the FBXObject of it
m = character.GetModel(self.BodyNodeObject[o])
and BodyNodeObject is generated with
def BodyNodes(self):
for i in dir(FBBodyNodeId):
if i[0] == 'k':
try:
self.BodyNodeObject[BodyNodesId[i]] = getattr(FBBodyNodeId, i)
except:
pass
BodyNodesId is simply a dictionary
BodyNodesId = OrderedDict({
'kFBChestNodeId':'Spine1',
'kFBHeadNodeId':'Head',
'kFBHipsNodeId':'Hips',
'kFBLeftAnkleNodeId':'LeftFoot',
'kFBLeftCollarNodeId':'LeftShoulder',
'kFBLeftElbowNodeId':'LeftForeArm',
...
})
this worked for me
from fbx import *
for i in range(myscene.GetCharacterCount()):
character = myscene.GetCharacter(i)
node = character.eHips
link = FbxCharacterLink()
while (character.GetCharacterLink(node, link)):
print node, link.mNode.GetName()
node = character.ENodeId(int(node+1))
I have a python script that successfully does a search and replace in an OpenOffice Writer document using PyUNO. I wanna to ask how to get the coordinate of found text?
import string
search = document.createSearchDescriptor()
search.SearchString = unicode('find')
#search.SearchCaseSensitive = True
#search.SearchWords = True
found = document.findFirst(search)
if found:
#log.debug('Found %s' % find)
## any code here help to get the coordinate of found text?
pass
This is some StarBASIC code to find the page number of a search expression in a Writer document:
SUB find_page_number()
oDoc = ThisComponent
oViewCursor = oDoc.getCurrentController().getViewCursor()
oSearchFor = "My Search example"
oSearch = oDoc.createSearchDescriptor()
With oSearch
.SearchRegularExpression = False
.SearchBackwards = False
.setSearchString(oSearchFor)
End With
oFirstFind = oDoc.findFirst(oSearch)
If NOT isNull(oFirstFind) Then
oViewCursor.gotoRange(oFirstFind, False)
MsgBox oViewCursor.getPage()
Else
msgbox "not found: " & oSearchFor
End If
Hope this helps you