How to add regex matches to list in VB.net - regex

I am having a Regex and I want the matches to be added to my previous List. The list (called "Items") has already some entries. (It got the entries from a listbox1 and added is now a datasource of the listbox1)
This is my source:
Dim Items As List(Of String)
<some other code here>
For Each Bam As Match In Treffer
If hashtagz = False Then
ListBox1.Items.Add(Bam.Groups(1).ToString)
ElseIf hashtagz = True And FirstHashtags = True Then
ListBox1.Items.Add(Bam.Groups(1).ToString)
ElseIf hashtagz = True And FirstHashtags = False Then
Items.Add(Bam.Groups(1).ToString)
Console.WriteLine(Bam.Groups(1).ToString)
End If
Next
The last part is important (the last if loop with hashtagz = true and Firsthashtags = False)
I also added the console.writeline to see what is going on. In the console, I get all the new scraped and correct information. In the Items list however, I just get a duplicate of what has been already stored in there instead of adding and updating my list with the new regex matches.
edit Additional information: The whole if condition is in a timer, so it runs again and again. At first it will add entries to a listbox. Then (now important!) it will do the Items.Add(Bam.Groups(1).ToString). It seems to add the new entries the FIRST time THAT part of the code gets executed, but after it is being run trhough again trhough a timer, it will just add the previous entries again and again

Dim Items As New List(Of String)
Dim hashtagz As Boolean
Dim FirstHashtags As Boolean
' Other code here
For Each Bam As Match In Treffer
Select Case True
Case Not hashtagz
ListBox1.Items.Add(Bam.Groups(1).ToString)
Case FirstHashtags
ListBox1.Items.Add(Bam.Groups(1).ToString)
Case Items.Contains(Bam.Groups(1).ToString)
' Already Exists
Case Else
Items.Add(Bam.Groups(1).ToString)
Console.WriteLine(Bam.Groups(1).ToString)
End Select
Next

After using more than 7 hours today (and a few hours yesterday, I am a newbie in VB) of testing, going through my code and building in some outputs to see where the problem is...
My concept is correct, there are no logical errors in the flow of my programm, as one can see from the console.writeline(Bam.Groups(1).ToString . I tested everything and ended up putting in a richtextbox and its like this now
For Each Bam As Match In Treffer
If hashtagz = False Then
ListBox1.Items.Add(Bam.Groups(1).ToString)
ElseIf hashtagz = True And FirstHashtags = True Then
ListBox1.Items.Add(Bam.Groups(1).ToString)
ElseIf hashtagz = True And FirstHashtags = False Then
Items.Add(Bam.Groups(1).ToString)
RichTextBox1.Text = RichTextBox1.Text + Bam.Groups(1).ToString & vbNewLine
End If
Next
The adding procedure seems to be looking correct with the richtextbox, but when I want to add to the Items list, it just gives out the duplicates of the previous entries instead of adding to it. The .add seems to work only the FIRST time running through that line of code, after the second time it just gives out the duplicate of the entries.
I am still trying to figure out WHY that is and I will trying to understand the posts above. Maybe someone else has also an explanation, jsut in case the others were wrong
Edit I have been experimenting still with all this, I have a function that grabs the last entry of my item list and prints out a part of it. When I do that, the print seems correct and updated. So it seems like the list IS actually being updated somehow since the "getting a part of the latest entry of list" is working and always updated. But when I want to show or save the content of the item list, that's when I get the duplicates and the updated and newest entries are not being shown!

Alright guys, I am back again after testing.
The code I posted above was correct. The real reason behind the mistake was in a few other parts of the code, which resulted in partially duplicated output of the entries of the list etc.
I lost track of the variables and the procedures my program was doing. Any hints or tips for me on how to keep track of the code on what it does and having everything in mind or how to properly structure code etc. so that I won't get lost again and again in the code?
This case can be closed, sorry for the inconvenience.

Related

Replace empty elements on a list with None

n_available_markets=[playlist['tracks']['items'][i]['track']['available_markets']
for i in range(len(playlist['tracks']['items']))]
for i in n_available_markets:
if i=="[]":
i==None
n_available_markets
I was working with the Spotify API and I found that some values when I created the list were empty [[],['NZ','ES']] so I was wondering how I could change this empty values into None and I tried the code attached above(the first 2 lines are just to retrieve the available markets data) but it did not make any change.
This should do the trick:
n_available_markets = [p['track']['available_markets'] if len(p['track']['available_markets'])>0 else None for p in playlist['tracks']['items']]

This cell duplicates image in that cell in spreadsheet?

Very simple. Cell A1 has an image in it, which I supply through Insert:Picture:From File...
Now I want Cell A3 to automatically show the same picture. I simply can't find a way-- certainly the "=" doesn't work. At this point, I don't care if the images are "links" or embedded, I just want it to work. Can it? Thx.
Edit, 09-01-17, based on Jim K's idea, here's macro code I have installed:
REM ***** BASIC *****
Private oListener as Object
Private cellA1 as Object
Sub AddListener
Dim Doc, Sheet, Cell as Object
Doc = ThisComponent
Sheet = Doc.Sheets.getByName("Sheet1")
cellA1 = Sheet.getCellrangeByName("A1")
'create a listener
oListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener")
'register the listener
cellA1.addModifyListener(oListener)
End Sub
Sub Modify_disposing(oEv)
End Sub
Sub RmvListener
cellA1.removeModifyListener(oListener)
End Sub
' macro jumps here when oListener detects modification of Sheet
Sub Modify_modified(oEv)
Doc = ThisComponent
Sheet = Doc.Sheets.getByIndex(0)
originCell = Sheet.getCellByPosition(0,0)
originValue = originCell.Value
if originValue then
print "originValue is " & originValue
else
print "originValue zero"
end if
End Sub
The problem, ironically, is that it works. It works for integers and {non-value}, I mean an empty cell.
So any integer not zero prints TRUE, zero prints FALSE, and empty cell prints FALSE.
But that's where it quits working-- any kind of string "asdf" also returns FALSE.
Maybe that could be fixed, but there's something a lot worse: When I paste an image in the cell, or use the Insert/Image/From File... menu, or Cut an existing image... Nothing happens! The Sheet Modified business does not trigger the expected routine.
Any hope? Thx.
As you discovered, the solution in my comment does not work, because the Content changed event will not trigger when images are added. I looked into other events as well, but they did not work either.
So instead, we can set up a function that runs periodically. Each time it runs, it checks the count of images, and if any have been added or removed, it calls update_copied_images() below, which currently simply reports the value of cell A1, as in your code.
As explained here, I have not gotten a timer loop to work in Basic without crashing, so we can use Python instead (a better language, so this is not a drawback in my opinion).
import time
from threading import Thread
import uno
COLUMN_A, COLUMN_B, COLUMN_C = 0, 1, 2
FIRST_ROW = 0
def start_counting_images(action_event=None):
t = Thread(target = keep_counting_images)
t.start()
def keep_counting_images():
oDoc = XSCRIPTCONTEXT.getDocument()
oSheet = oDoc.getSheets().getByIndex(0)
oDrawPage = oSheet.getDrawPage()
messageCell = oSheet.getCellByPosition(COLUMN_C, FIRST_ROW)
messageCell.setString("Starting...")
prevCount = -1
while hasattr(oDoc, 'calculateAll'): # keep going until document is closed
count = oDrawPage.Count
if prevCount == -1 or prevCount != count:
prevCount = count
messageCell.setString("Number of Images: " + str(prevCount))
update_copied_images(oSheet)
time.sleep(1)
def update_copied_images(oSheet):
originCell = oSheet.getCellByPosition(COLUMN_A, FIRST_ROW)
originString = originCell.getString()
messageCell = oSheet.getCellByPosition(COLUMN_B, FIRST_ROW)
if len(originString):
messageCell.setString("originString '" + originString + "'")
else:
messageCell.setString("originString length is zero")
g_exportedScripts = start_counting_images,
To run, go to Tools -> Macros -> Run Macro, find the .py file under My Macros where you put this code, and run start_counting_images.

How to manage looping on this list on Applscript?

The list is in the form of:-
0:
https://url
1:
https://url
..... And so on.
How could I loop on this list. So I could fetch the number first without ":" and type it somewhere then fetch the url that comes after that number and type it elsewhere. Then end repeat if the list is over.
Or should I use records instead?
I am still a beginner using AppleScript. I tried many commands I mixed up but the computer keeps running the script nonestop and the activity monitor shows the applescript using 100% of the processor and huge amount of ram.
Appreciate any help.
Thank you
You didn't define what your list really looks like very well so I made an assumption on my answer below. If I was wrong, hopefully my answer will at least point you in the right direction. (or if I've gotten it wrong, but you can choose to reformat it to the way I suggested, that could still help)
on run
set theList to {"0:http://apple.com", "1:http://google.com"} -- my guess at what your list looks like.
repeat with anItem in theList
set anItem to anItem as string
set itemParts to myParseItem(anItem)
set tID to the_integer of itemParts as integer
set tURL to the_url of itemParts as string
end repeat
end run
on myParseItem(theItem)
set AppleScript's text item delimiters to ":"
set delimitedList to every text item of theItem
set newString to (items 2 thru -1 of delimitedList as string)
set AppleScript's text item delimiters to {""}
set theInt to item 1 of delimitedList
set theURL to newString as string
return {the_integer:theInt, the_url:theURL}
end myParseItem

Find-Replace text contained in textboxes and tables

I'm hoping I can get come help from a programmer.
What I want to do is to translate a word report generated by a software, so I turned to macros. I already have a word file containing the original word/phrases and the translated ones.
I 'stole' the code to translate from some forum online, which works great with normal text. My problem is that the text of the report I want to translate is within various "text boxes" and "tables".
I was able to manually remove the tables, but keep the text. This totally ruined the formatting, but I can deal with that latter.
Now, unfortunately I cannot do the same with textboxes. There is no 'delete, but keep the text" function for textboxes.
I can send you the macro code, the original report automatically generated by the software and the file to get all translated words from.
I really appreciate your time.
Ok. This is code that translates normal text.
Sub Translate()
Dim oChanges As Document, oDoc As Document
Dim oTable As Table
Dim oRng As Range
Dim rFindText As Range, rReplacement As Range
Dim i As Long
Dim sFname As String
'Change the path in the line below to reflect the path of the table document
sFname = "C:\Users\user\Desktop\Dictionary.doc"
Set oDoc = ActiveDocument
Set oChanges = Documents.Open(FileName:=sFname, Visible:=False)
Set oTable = oChanges.Tables(1)
For i = 1 To oTable.Rows.Count
Set oRng = oDoc.Range
Set rFindText = oTable.Cell(i, 1).Range
rFindText.End = rFindText.End - 1
Set rReplacement = oTable.Cell(i, 2).Range
rReplacement.End = rReplacement.End - 1
With oRng.Find
.ClearFormatting
.Replacement.ClearFormatting
Do While .Execute(findText:=rFindText, _
MatchWholeWord:=True, _
MatchWildcards:=False, _
Forward:=True, _
Wrap:=wdFindContinue) = True
oRng.Text = rReplacement
Loop
End With
Next i
oChanges.Close wdDoNotSaveChanges
End Sub
I'm guessing you'd need to see the format of the document that is being translated, which contains all the tables and text boxes. But it is too large and I'm not sure if I can send it as an attachment here somehow. (sorry, its my first time on this forum). Any advise?
Thanks a lot
JD

VB.net - Get the "real" character on PreviewKeyDown/KeyPress Event from e.Key

I'm facing some difficulties building my inputfilter for a TextBox (WFP, but this should not matter here)
I need to suppress all inputs, but:
-Digits (Integer - no floats, groups)
-Basic Math Symbols: (,),+,-,*,/
Yes, the goal is to have a kind of formula evaluation. This part works well with the Sriptcontrol-Method
(from: http://www.vb-tips.com/Eval.aspx)
I also found several leads to filter by Regex (sorry, can't remember the source...):
Regex("[\d\(\)\+\-\*\/]")
Now the problem is, that e.g. the Character '+' never shows up in the e.Key Argument
Pressing NumPad-'+' gives me
e.Key=85
e.Key.Tostring=Add
Trying from Keyboard '+'
e.Key=141
e.Key.ToString=OemPlus
So the Regex will never find a match to these allowed chars.
Since Windows recognizes the Key I hit and places the Character I see on my Keyboard, I guess, there MUST be a way to catch "exactly" the Key, which the user means to hit :-)
Also I needed to suppress any modifier-chars (such as AltGr+2: square on my german layout)
Here my Code Pasted (might be a little bit messy due to experimenting around)
Private Sub tb_PreviewKeyDown(sender As System.Object, e As System.Windows.Input.KeyEventArgs) Handles TB0.PreviewKeyDown
Dim s As TextBox = sender
Debug.WriteLine(e.Key.ToString & " -" & e.Key)
Dim rx As New Regex("[\d\(\)\+\-\*\/]|Add|Subtract|Divide|Multiply|Return|Tab|Back")
If Not rx.IsMatch(e.Key.ToString) Then
e.Handled = True
Return
End If
If e.Key = Key.Enter Or e.Key = Key.Tab Then
If s.Text.Trim = "" Then Return
If Not IsNumeric(s.Text) Then
Try
Dim ev As New MSScriptControl.ScriptControl
ev.Language = "VBScript"
ev.AllowUI = False
ev.Reset()
s.Text = CStr(Math.Round(CDbl(ev.Eval(s.Text))))
s.SelectAll()
Catch ex As Exception
s.SelectAll()
e.Handled = True
Return
End Try
End If
s.SelectAll()
End If
End Sub
Any hints on this are highly appreciated.
Thanks in advance,
Daniel
The comment of Hans Passant solved my issue!