Beginner AppleScript Writer having trouble with idle handler - excel

I have been exploring coding recently and I really enjoy grinding a problem down. I am getting comfortable with AppleScript now and I think it is a good option for what I want to do in the future with coding. My gut tells me that Automator would be less efficient RAM wise and I don't like how it is sectioned off; to constraining and confusing. I like the sandbox feature of a scripting language. I built a pretty good script for a web crawler that opens an online stock portfolio and prunes the market price of cryptocurrencies. I plan on utilizing technological decision making labs to create a cryptocurrency forecasting workbook for my hopes and dreams to make money some day, if ever :[ I have day dreams of making a live excel file that builds plots with hourly fluctuations in the trading.
To make it a full fledged automated system I need some sort of way to loop the script or schedule it to run on a schedule to get lots of data points for the mathematical models I hope to formulate from the data. I have tried really hard to make the idle handler work but it just doesn't operate like the tutorials describe. It seems you can't use "on idle" with certain commands and I get an error every gosh darn time I use the thing. I found a help page that showed how to incorporate a "beep" function to make sure the idle loop is running and when I compile and save as an "always running App" it doesn't play the beep so I guess that's another problem I haven't figured out. I get the beep to work sometimes but with my final draft of my program now I can't get it to work. I have tried inserting it ever so carefully within tell statements because I have found it works with them sometimes. And I guess you can't have the idle handler span the entire script; it needs to be called in one command structures tree to work. But I still haven't had the App run the script from idle with all the work I've put in looking into this solution. Anybody that has the hush hush on the idle handler secrets can do their best to try to explain the inner workings of the script to me but I find that it takes me a long time to learn coding because it is a lot of very technical reading with precious few opportunities to forge your own learning. Coding is a lot of boiler plate rehashes and I assume I will be chipping away at writing code long into my grey hair days with what I've learned so far.
But if you could use this question to collect some reading material on how to take a moderately well written script to run in 30 minute increments in the background of a laptop that can handle most computing loads fairly well it would be most appreciated. I'm not against Automator; it's just hard in it's own right with all the things you have to know to get it to work. As I said, any info about the idle handler and how to get it to work would be helpful. Also, if it is possible to write code in AppleScript to generate plots in Microsoft Excel, I like making models for shirts and googles.
I guess I will share what I've worked on for the last chunk of a weeks worth of grinding the tutorials offered currently online for free. Any critiques or suggestions on how to make the script I've got so far better is greatly appreciated and I don't mind if you snatch something you like if I did a good jerb. This is a web crawling cryptocurrency stock analyzer currently. It follows 3 currencies and writes data to an excel file with year, month, day, and seconds to collect a mass of data for a stronger mathematical model. I studied technological forecasting techniques that apply seasonality to data so the forecasts are better than just using the trend line function in excel, though with the variability with cryptocurrency I wouldn't put much salt on a long term prediction of market prices. I just want to be watching for those oh so gut wrenching stock crashes for a chance to limp in to the game with what little money I can scrounge together for sustenance.
--Boiler plate code to manipulate the HTML to let us pull the market price of the stock.--
--3 sets of modifiers for the 3 stocks--
to extractTextBitcoin(searchTextBitcoin, startTextBitcoin, endTextBitcoin)
set tid to AppleScript's text item delimiters
set startTextBitcoin to ">"
set searchTextBitcoin to {"priceValue___11gHJ", 0 & searchTextBitcoin}
set AppleScript's text item delimiters to startTextBitcoin
set endItemsBitcoin to text item -1 of searchTextBitcoin
set AppleScript's text item delimiters to endTextBitcoin
set beginningToEndBitcoin to text item 1 of endItemsBitcoin
set AppleScript's text item delimiters to startTextBitcoin
set endTextBitcoin to (text items 2 thru -1 of beginningToEndBitcoin) as record
set AppleScript's text item delimiters to tid
end extractTextBitcoin
to extractTextLitecoin(searchTextLitecoin, startTextLitecoin, endTextLitecoin)
set tid to AppleScript's text item delimiters
set startTextLitecoin to ">"
set searchTextLitecoin to {"priceValue___11gHJ", 0 & searchTextLitecoin}
set AppleScript's text item delimiters to startTextLitecoin
set endItemsLitecoin to text item -1 of searchTextLitecoin
set AppleScript's text item delimiters to endTextLitecoin
set beginningToEndLitecoin to text item 1 of endItemsLitecoin
set AppleScript's text item delimiters to startTextLitecoin
set endTextLitecoin to (text items 2 thru -1 of beginningToEndLitecoin) as record
set AppleScript's text item delimiters to tid
end extractTextLitecoin
to extractTextDogecoin(searchTextDogecoin, startTextDogecoin, endTextDogeecoin)
set tid to AppleScript's text item delimiters
set startTextDogecoin to ">"
set searchTextDogecoin to {"priceValue___11gHJ", 0 & searchTextDogecoin}
set AppleScript's text item delimiters to startTextDogecoin
set endItemsDogecoin to text item -2 of searchTextDogecoin
set AppleScript's text item delimiters to endTextDogeecoin
set beginningToEndDogecoin to text item 1 of endItemsDogecoin
set AppleScript's text item delimiters to startTextDogecoin
set endTextDogeecoin to (text items 2 thru -1 of beginningToEndDogecoin) as record
set AppleScript's text item delimiters to tid
end extractTextDogecoin
--A tell statement to open the webpage where the stocks are measured--
tell application "Safari"
activate
do shell script "open https://coinmarketcap.com/currencies/bitcoin/"
end tell
delay 2
--A function that differentiates the data on the web page by class and number. It
--also uses JavaScript to write the data to a useable format.
to getInputByClassBitcoin(theClass, num)
tell application "Safari"
set input to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
end tell
return input
end getInputByClassBitcoin
--The function with the class and number criteria manually pulled from the web page--
getInputByClassBitcoin("priceValue___11gHJ", 0)
--Setting the instataneous stock price to a variable to input in Excel--
set BitcoinPrice to getInputByClassBitcoin("priceValue___11gHJ", 0)
on FinalFuction(BitcoinPrice)
set FinalFuction to extractTextBitcoin(BitcoinPrice, "<div class=>", "</div>")
return FinalFuction(BitcoinPrice)
end FinalFuction
tell application "Safari"
activate
do shell script "open https://coinmarketcap.com/currencies/litecoin/"
end tell
delay 2
to getInputByClassLitecoin(theClass, num)
tell application "Safari"
set token to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
end tell
return token
end getInputByClassLitecoin
getInputByClassLitecoin("priceValue___11gHJ", 0)
set LitecoinPrice to getInputByClassLitecoin("priceValue___11gHJ", 0)
on ReturnFuction(LitecoinPrice)
set ReturnFuction to extractTextLitecoin(LitecoinPrice, "<div class=>", "</div>")
return ReturnFuction(LitecoinPrice)
end ReturnFuction
tell application "Safari"
activate
do shell script "open https://coinmarketcap.com/currencies/dogecoin/"
end tell
delay 2
to getInputByClassDogecoin(theClass, num)
tell application "Safari"
set blast to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
end tell
return blast
end getInputByClassDogecoin
getInputByClassDogecoin("priceValue___11gHJ", 0)
set DogecoinPrice to getInputByClassDogecoin("priceValue___11gHJ", 0)
on EndFuction(DogecoinPrice)
set EndFuction to extractTextDogecoin(DogecoinPrice, "<div class=>", "</div>")
return EndFuction(DogecoinPrice)
end EndFuction
--Opens the compiled Excel workbook, negates user input, finds the next available--
--cell to input data, and fills the fields with Year, Month, Day, Time, and Price--
tell application "Microsoft Excel"
open "/Users/clusterflux/Desktop/ㅇㅅㅇBITCOINㅇㅅㅇ.xlsx"
set display alerts to false
delete active sheet
first row index of (get end (last cell of column 9) direction toward the top)
set LastRow to first row index of (get end (last cell of column 9) direction toward the top)
--write date and time for each market reading to excel file
set value of cell ("I" & LastRow + 1) to "=YEAR(TODAY())"
set value of cell ("J" & LastRow + 1) to "=MONTH(TODAY())"
set value of cell ("K" & LastRow + 1) to "=DAY(TODAY())"
set value of cell ("L" & LastRow + 1) to (time string of (current date))
set value of cell ("M" & LastRow + 1) to BitcoinPrice
set workbookName to ("ㅇㅅㅇBITCOINㅇㅅㅇ.xlsx") as string
set destinationPath to (path to desktop as text) & workbookName
save active workbook in destinationPath
end tell
tell application "Microsoft Excel"
open "/Users/clusterflux/Desktop/ㅇㅅㅇLITECOINㅇㅅㅇ.xlsx"
set display alerts to false
delete active sheet
first row index of (get end (last cell of column 5) direction toward the top)
set LastRow to first row index of (get end (last cell of column 5) direction toward the top)
set value of cell ("C" & LastRow + 1) to "=YEAR(TODAY())"
set value of cell ("D" & LastRow + 1) to "=MONTH(TODAY())"
set value of cell ("E" & LastRow + 1) to "=DAY(TODAY())"
set value of cell ("F" & LastRow + 1) to (time string of (current date))
set value of cell ("G" & LastRow + 1) to LitecoinPrice
set workbookName to ("ㅇㅅㅇLITECOINㅇㅅㅇ.xlsx") as string
set destinationPath to (path to desktop as text) & workbookName
save active workbook in destinationPath
end tell
on idle
return 3
beep
tell application "Microsoft Excel"
open "/Users/clusterflux/Desktop/ㅇㅅㅇDOGECOINㅇㅅㅇ.xlsx"
set display alerts to false
delete active sheet
first row index of (get end (last cell of column 5) direction toward the top)
set LastRow to first row index of (get end (last cell of column 5) direction toward the top)
set value of cell ("C" & LastRow + 1) to "=YEAR(TODAY())"
set value of cell ("D" & LastRow + 1) to "=MONTH(TODAY())"
set value of cell ("E" & LastRow + 1) to "=DAY(TODAY())"
set value of cell ("F" & LastRow + 1) to (time string of (current date))
set value of cell ("G" & LastRow + 1) to DogecoinPrice
set workbookName to ("ㅇㅅㅇDOGECOINㅇㅅㅇ.xlsx") as string
set destinationPath to (path to desktop as text) & workbookName
save active workbook in destinationPath
end tell
end idle
Sorry in advance if my formatting isn't up to snuff. I'm still a newbie.

Here is a different AppleScript approach which allows you to retrieve your Bitcoin Price values without the need for opening Safari, using JavaScript, Automator, or using text item delimiters. This may not be exactly what you’re looking for but at least it offers a different approach using much less code. Hopefully you can adapt some of it to your needs.
The first 3 properties in the code define the regular expressions which will be used in the do shell script commands, which will extract the dollar values from the HTML source code.
For example, to quickly explain what property eGrepBitcoinPrice : "priceValue___11gHJ\”>\\$\\d{2},\\d{3}.\\d{2}” means… we will be searching for text inside the HTML which contains “priceValue___11gHJ” followed by a “>” followed by “$” followed by any 2 digits followed by a “,” followed by any 3 digits followed by a “.” and followed by any 2 digits
Because I do not have Microsoft Excel, I could not include those commands in the code. However, I did create a quick logging function which writes the prices to a plain text file on your Desktop “Price Log.txt”. This functionality can easily be disabled or removed. The log commands are all wrapped up within a script object called script logCommands which can be removed or commented out along with any other lines in the code which contain my logCommands's.
Here is a snapshot of the log file
Save this following AppleScript code in Script Editor.app as a “stay open” application. Being that it is a “stay open” application, when the applet is launched outside of Script Editor.app, only what is within the explicit on run handler will run only one time. The rest of the magic happens within the on idle handler… and everything within this handler will run every 300 seconds. If you want the commands to repeat every 30 minutes, just set the return value to 1800.
property eGrepBitcoinPrice : "priceValue___11gHJ\">\\$\\d{2},\\d{3}.\\d{2}"
property eGrepLitecoinPrice : "priceValue___11gHJ\">\\$\\d{3}.\\d{2}"
property eGrepDogecoinPrice : "priceValue___11gHJ\">\\$\\d{1}.\\d{5}"
property currentBitcoinPrice : missing value
property currentLitecoinPrice : missing value
property currentDogecoinPrice : missing value
property logToTextFile : missing value
on run -- Executed Only Once.. When This Script Applet Is Launched
activate
set logToTextFile to (display dialog ¬
"Enable Quick Log Mode?" buttons {"No", "Yes"} ¬
default button 2 with title "Log Mode")
if button returned of logToTextFile = "Yes" then
my logCommands's beginLog()
getPrices()
else
getPrices()
return {currentBitcoinPrice, currentDogecoinPrice, currentLitecoinPrice}
end if
end run
on idle
getPrices()
if button returned of logToTextFile = "Yes" then my logCommands's writeToLog()
(* within this idle handler is where you will place
The bulk of your additional code. All of your Excel
Code Goes Here*)
return 300 -- In Seconds, How Often To Run Code In This Idle Handler
end idle
---------- PLACE ALL ADDITIONAL HANDLERS BENEATH THIS LINE ----------
on getPrices()
set currentBitcoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/bitcoin/markets/' " & ¬
"| grep -Eo " & quoted form of eGrepBitcoinPrice & " | cut -c 21-"
set currentLitecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/litecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepLitecoinPrice & " | cut -c 21-"
set currentDogecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/dogecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepDogecoinPrice & " | cut -c 21-"
end getPrices
on quit -- Executed Only When The Script Quits
if button returned of logToTextFile = "Yes" then my logCommands's endLog()
continue quit -- Allows The Script To Quit
end quit
script logCommands
property pathToPriceLog : POSIX path of (path to desktop as text) & "Price Log.txt"
on beginLog()
set startTime to ("Start Time... " & (current date) as text) & ¬
" Price Scanning At 5 Minute Intervals"
do shell script "echo " & startTime & " >> " & ¬
quoted form of pathToPriceLog
end beginLog
on writeToLog()
do shell script "echo " & "Bitcoin:" & quoted form of currentBitcoinPrice & ¬
" Dogecoin:" & quoted form of currentDogecoinPrice & ¬
" Litecoin:" & quoted form of currentLitecoinPrice & ¬
" " & quoted form of (time string of (current date)) & ¬
" >> " & quoted form of pathToPriceLog
end writeToLog
on endLog()
set endTime to quoted form of "End Time... " & (current date) as text
do shell script "echo " & endTime & " >> " & ¬
quoted form of pathToPriceLog
do shell script "echo " & " " & " >> " & ¬
quoted form of pathToPriceLog
end endLog
end script
Unfortunately “stay open” applications and scripts when launched from within Script Editor.app, will not execute what is within the idle handler. So the “stay open” application needs to be launched from within Finder, like any other applications, to observe the results of the idle commands as they are happening. This was the main reason I included a logging to file function… so I could observe the results of the idle commands in real time.
Contrary to what a lot of people think, most “stay open” applications use very little system resources.
UPDATED APPLESCRIPT CODE DUE TO CHANGED URL SOURCE CODE
property eGrepBitcoinPrice : "priceValue\\ \">\\$\\d{2},\\d{3}.\\d{2}"
property eGrepLitecoinPrice : "priceValue\\ \">\\$\\d{3}.\\d{2}"
property eGrepDogecoinPrice : "priceValue\\ \">\\$\\d{1}.\\d{4}"
property currentBitcoinPrice : missing value
property currentLitecoinPrice : missing value
property currentDogecoinPrice : missing value
property logToTextFile : missing value
on run -- Executed Only Once.. When This Script Applet Is Launched
activate
set logToTextFile to (display dialog ¬
"Enable Quick Log Mode?" buttons {"No", "Yes"} ¬
default button 2 with title "Log Mode")
if button returned of logToTextFile = "Yes" then
my logCommands's beginLog()
getPrices()
else
getPrices()
return {currentBitcoinPrice, currentDogecoinPrice, currentLitecoinPrice}
end if
end run
on idle
getPrices()
try
if button returned of logToTextFile = "Yes" then my logCommands's writeToLog()
on error errMsg number errNum
my logCommands's writeToLog()
end try
(* within this idle handler is where you will place
The bulk of your additional code. All of your Excel
Code Goes Here*)
return 300 -- In Seconds, How Often To Run Code In This Idle Handler
end idle
---------- PLACE ALL ADDITIONAL HANDLERS BENEATH THIS LINE ----------
on getPrices()
set currentBitcoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/bitcoin/markets/' " & ¬
"| grep -Eo " & quoted form of eGrepBitcoinPrice & " | cut -c 14-"
set currentLitecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/litecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepLitecoinPrice & " | cut -c 14-"
set currentDogecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/dogecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepDogecoinPrice & " | cut -c 14-"
end getPrices
on quit -- Executed Only When The Script Quits
if button returned of logToTextFile = "Yes" then my logCommands's endLog()
continue quit -- Allows The Script To Quit
end quit
script logCommands
property pathToPriceLog : POSIX path of (path to desktop as text) & "Price Log.txt"
on beginLog()
set startTime to ("Start Time... " & (current date) as text) & ¬
" Price Scanning At 5 Minute Intervals"
do shell script "echo " & startTime & " >> " & ¬
quoted form of pathToPriceLog
end beginLog
on writeToLog()
do shell script "echo " & "Bitcoin:" & quoted form of currentBitcoinPrice & ¬
" Dogecoin:" & quoted form of currentDogecoinPrice & ¬
" Litecoin:" & quoted form of currentLitecoinPrice & ¬
" " & quoted form of (time string of (current date)) & ¬
" >> " & quoted form of pathToPriceLog
end writeToLog
on endLog()
set endTime to quoted form of "End Time... " & (current date) as text
do shell script "echo " & endTime & " >> " & ¬
quoted form of pathToPriceLog
do shell script "echo " & " " & " >> " & ¬
quoted form of pathToPriceLog
end endLog
end script

Related

VBA Datalabel.Top being assigned to a variable incorrectly

I am creating a chart, adding series on it, then I apply a data label to the last point of each series. I then run a routine which prevents overlaps from happening. In some conditions it works when I debug it however it does not work when I let it run normally. I think I have found the source of the error but don't know how to fix it.
First I apply data labels
'add data label to line
Worksheets(OutputSheetName).ChartObjects(1).Chart.SeriesCollection(x).Points(NumberOfSamples + 1).ApplyDataLabels
Worksheets(OutputSheetName).ChartObjects(1).Chart.SeriesCollection(x).Points(NumberOfSamples + 1).DataLabel.Text = Sheets(SheetName).Cells(PlotRow(x), TransistorNameY).Value & " " & Sheets(SheetName).Cells(PlotRow(x), DeviceTypeY).Value _
& " " & "[" & Sheets(SheetName).Cells(PlotRow(x), ColdCurrentY).Value & " " & "A" & "]"
'increasing data label width
Worksheets(OutputSheetName).ChartObjects(1).Chart.SeriesCollection(x).Points(NumberOfSamples + 1).DataLabel.Width = 200
Then I put data labels in an array.
Set sers = Worksheets(sh).ChartObjects(1).Chart.SeriesCollection
'if there are no plots on curve
If sers.Count = 0 Then
Exit Sub
End If
ReDim dLabels(1 To sers.Count)
For i = 1 To sers.Count
Set dLabels(i) = sers(i).Points(NumberOfSamples + 1).DataLabel
Debug.Print dLabels(i).Top
Next
When I look at the dLabels.Top using a watch, the value is correct. However when the dLabels.Top value is printed out in debug window the value does not match what is in the array. I have the dLabels array set as Datalabel
I then sort the top values going from highest first and start moving them to prevent overlap. Because of this when later I try to move the labels they are incorrect since they have wrong top position
Can anyone help? Not sure if this makes a difference but I do have a multi monitor setup.

Cycle and Edit Through XML Children Based On Values

I have an interface to cycle through XML child and edit them. Something like this:
The XML file looks as such:
<?xml version="1.0"?>
<catalog>
<query id="bk100">
<question>Do we have Docker security?</question>
<answer>Yes</answer>
<comment>None</comment>
<genre>Cloud</genre>
</query>
<query id="bk101">
<question>Do we have cloud security</question>
<answer>Yes</answer>
<comment>None</comment>
<genre>SCPC</genre>
</query>
<query id="bk100">
<question>Do we have Kubernetos security?</question>
<answer>Yes</answer>
<comment>None</comment>
<genre>Cloud</genre>
</query>
</catalog>
I am reading and storing the children as such in Global variabes:
xmlUrl = ThisWorkbook.Path & "\Blah.xml"
oXMLFile.Load (xmlUrl)
Set QuestionNodes = oXMLFile.SelectNodes("/catalog/query/question/text()")
Now once the user selects a Genre from the intrface (using a combobox or whatever), for example SCPC - I want the next and previous buttons to allow the to just loop through the questions and answers (and edit them) in the Genre SCPC
so for example, a Pseudo-implementation for the ``Next button` would look like:
'Next XML Node Iterartor
Private Sub btnNextEntry_Click()
Interate Where GenreNodes(i).NodeValue = "SCPC"
txtQuestion.Value = QuestionNodes(i).NodeValue
Pause 'When the user clicks Next again, the Next Node Data Is Showed
End Sub
and similarly something for the Previous button. Obviously I am out of logic here how to achieve this. As I also need to have editing and save functionality, I thought it was good idea to use index based iteration, but with the Genre based filtering, it doesn't make a lot of sense now and I am stuck.
Any tips ideas how I can handle this? Thanks.
Using Set QuestionNodes = oXMLFile.SelectNodes("/catalog/query/question/text()") for the question list makes it more difficult to filter than it needs to be. It's easier to use a list of the query nodes and then access the child nodes as required.
So, if you wanted to list all of the nodes then use:
Dim queryNodes As IXMLDOMNodeList
' ...
Set queryNodes = oXmlFile.SelectNodes("/catalog/query")
and you could then work with the values of the child nodes like this:
Dim node As IXMLDOMNode
For Each node In queryNodes
Debug.Print "Q: " & node.SelectSingleNode("question").Text & vbCrLf & _
"A: " & node.SelectSingleNode("answer").Text & vbCrLf & _
"C: " & node.SelectSingleNode("comment").Text & vbCrLf & _
"G: " & node.SelectSingleNode("genre").Text & vbCrLf & vbCrLf
Next node
If you then wanted to only work with nodes where the genre is "SCPC" then, it's just a case of changing the queryNodes list, like this:
Set queryNodes = oXmlFile.SelectNodes("/catalog/query[genre='SCPC']")
The code to access the child nodes doesn't change just because we have filtered the list differently. All of the changes are contained in how we create the queryNodes list. The code to update queryNodes could be called from the event handler for the combobox that allows the user to choose a genre.
We could adapt the code for printing all of the node values into a sub which prints the values of a specific node (as suggested by Tim Williams in the comments):
Sub printNode(node As IXMLDOMNode)
Debug.Print "Q: " & node.SelectSingleNode("question").Text & vbCrLf & _
"A: " & node.SelectSingleNode("answer").Text & vbCrLf & _
"C: " & node.SelectSingleNode("comment").Text & vbCrLf & _
"G: " & node.SelectSingleNode("genre").Text & vbCrLf & vbCrLf
End Sub
To control which node is displayed via your interface, use the Item property of the queryNodes list. The first node is queryNodes.Item(0), the next is queryNodes.Item(1) and so on.
If we use a variable called position to keep track of where we are in the list then the Previous button in your interface should make position = position - 1 and your Next button should make position = position + 1.
So, once the user presses Previous or Next, we would update position and then call printNode queryNodes.Item(position). There is always the chance that we have gone beyond either the start or the end of the list and this can be checked with If Not queryNodes.Item(position) Is Nothing before we try to call printNode.
For your specific case, you would need a sub to populate the fields in your interface. To do this, rename printNode to loadNode and, instead of printing to the Debug window, copy the relevant text from each child node into the corresponding field in your interface.
A saveNode function would just be the reverse of that - copy the value of each field in your interface into the text property of the relevant child node

Applescript for turning desktop Gmail link into iOS Gmail app link

I'm looking to build an Applescript that will take a desktop Gmail message link as input, and output a URL that will work on iOS to open the same message in the iOS Gmail app.
Here's a typical Gmail URL:
https://mail.google.com/mail/u/1/?zx=tso6hataagpp#inbox/143c5ddc34313e1f
And here's what that same URL would need to look like to work on iOS:
googlegmail:///cv=143c5ddc34313e1f/accountId=2
A couple notes:
The important part (the thread identifier) is the last part of the string in the original desktop URL. That's what needs to go after cv= in the mobile URL. However because Gmail allows multiple account log-in, we also need to note the account ID number after the /u/, which on the desktop is 1, but for mobile is 2. It looks like the desktop URLs are numbered starting at 0, while the mobile URLs are numbered starting at 1, based on which account you logged into first. So we need to increment the account ID number by 1 for the iOS URL.
Also, I'm not sure what the "?zx=tso6hataagpp" is before #inbox; I find that sometimes my desktop Gmail URLs include that part, other times they don't (but still include #inbox). I don't think it matters though, since the important parts we want are at the end of the string, and the number after the always-consistent "mail.google.com/mail/u/".
Ideally the Applescript would look at the clipboard for a desktop Gmail URL, and if it found one, it would output that same URL, then a line break, then the iOS URL immediately following it, like so:
https://mail.google.com/mail/u/1/?zx=tso6hataagpp#inbox/143c5ddc34313e1f
googlegmail:///cv=143c5ddc34313e1f/accountId=2
Any Applescript gurus out there that can show me how to hack this together?
The simplest way I can think of is:
This gets fixed path components. i.e component 5 and the last item
--https://mail.google.com/mail/u/1/?zx=tso6hataagpp#inbox/143c5ddc34313e1f
set pathUrl to (the clipboard)
set pathComponents to words of pathUrl
if item 1 of pathComponents is "https" and item 2 of pathComponents is "mail.google.com" then
set composed to pathUrl & return & "googlegmail:///cv=" & last item of pathComponents & "/accountId=" & (((item 5 of pathComponents) as number) + 1)
end if
This makes sure it always get the component ( account) after the "u" regardless of where it is.
You could do the same for the message id. by using "inbox"
set composed to ""
--set pathUrl to "https://mail.google.com/mail/u/1/?zx=tso6hataagpp#inbox/143c5ddc34313e1f"
set pathUrl to (the clipboard)
set pathComponents to words of pathUrl
if item 1 of pathComponents is "https" and item 2 of pathComponents is "mail.google.com" then
repeat with i from 1 to number of items in pathComponents
set this_item to item i of pathComponents
if this_item is "u" then
set this_item to item (i + 1) of pathComponents
set composed to pathUrl & return & "googlegmail:///cv=" & last item of pathComponents & "/accountId=" & ((this_item as number) + 1)
exit repeat
end if
end repeat
end if
composed
Try the following - delegates the parsing to bash via do shell script.
# Get text from clipboard.
# Test with: "https://mail.google.com/mail/u/1/?zx=tso6hataagpp#inbox/143c5ddc34313e1f"
set hLink to (the clipboard as text)
# Parse the link to extract the information of interest.
set parseResult to do shell script ¬
"[[ " & quoted form of hLink & " =~ /u/([0-9]+)/.+#inbox/(.+)$ ]] &&
printf '%s\\n' \"${BASH_REMATCH[1]}\" \"${BASH_REMATCH[2]}\""
# Synthesize the Gmail for iOS link.
set gmLink to "googlemail:///cv=" & ¬
(paragraph 2 of parseResult) & "/accountId=" & (1 + (paragraph 1 of parseResult))
# Synthesize the result
set res to hLink & linefeed & gmLink
# Put the result back on the clipboard.
set the clipboard to res

Applescript file search using data from a spreadsheet

I am currently using this Applescript I found that searches for a file name and returns the file path in a text doc. This works fine for finding 1 or 2 files, but I would like to find 500 files that are spread over hundreds of folders. My ideal script would use data from an excel spreadsheet or csv, perform a search, find the file and make a copy of it in a designated folder on my desktop. Any help is appreciated.
Here is the script I found:
tell application "System Events"
activate
set thePattern to text returned of (display dialog "Search for" default answer "")
end tell
if thePattern = "" then return
try
set foundFiles to do shell script "mdfind -name " & quoted form of thePattern & " | /usr/bin/egrep -i " & quoted form of thePattern & "[^/]*/?$ | /usr/bin/grep -vi " & quoted form of thePattern & ".*" & quoted form of thePattern
on error
set foundFiles to "Nothing Returned"
end try
if foundFiles = "" then set foundFiles to "Nothing Returned"
tell application "TextEdit"
activate
delay 0.5
try
set theDoc to document 1
get text of theDoc
if result is not "" then
make new document
set theDoc to result
end if
on error
make new document
set theDoc to result
end try
set text of theDoc to foundFiles
end tell
You need to read the data from the text file, then turn it into a return or linefeed delimited list and do a repeat over the items of this list. Then turn each item (which is actually a line) into e.g. a tab delimited list and again do a (nested) repeat loop over the items of this list. If you know that e.g. item 3 is the file path, you can set a variable to item 3 of the line as text and use this variable in your shell script.
I think you need to show that you understand the concept of repeat loops by posting your own attempt of implementing this. If you do, I'll be happy to come back and help you with the next step.
Kind regards,
Mark

Applescript: search Google for iTunes track lyrics

I want a script to search Google for the lyrics of the currently playing song. Why doesn't the following work?
tell application "iTunes"
set trackArtist to artist of current track
set trackName to name of current track
end tell
set search to trackArtist & " - " & trackName & " lyrics"
open location "https://www.google.com/search?q=" & search
If I "return search", I can see the variable is set correctly. And if I replace "search" in the last line with "test lyrics" the browser opens as expected. But the script above performs no action whatsoever, nor does it return any errors.
I think you forgot that most browsers decode the URL in the address field and before requested they encode the URL again before. So what you need to do is encode the url too.
tell application "iTunes"
set trackArtist to artist of current track
set trackName to name of current track
end tell
open location "http://www.google.com/search?q=" & rawurlencode(trackArtist & " - " & trackName & " lyrics")
on rawurlencode(theURL)
set PHPScript to "<?php echo rawurlencode('%s');?>"
set theURL to do shell script "echo " & quoted form of theURL & " | sed s/\\'/\\\\\\\\\\'/g"
return do shell script "printf " & quoted form of PHPScript & space & quoted form of theURL & " | php"
end rawurlencode

Resources