I am trying to extract the content of an array member at index i into a variable and then append it to a file.
How do I do that ?
Here is what I tried but it will not take the content of cgi[i]
firstrun(){
GuiControlGet, cgiDelay,,_cgiDelay
returnCode:=[]
for i in cgi {
msg := "http://" ip "/Nexus.cgi?session=" session "&action=" firstRunCgi[i] "&tokenoverride=1"
sendToHttp(msg)
getRespond()
returnCode[i]:=parseReturnCode()
if (returnCode[i] !=0){
addTextToGui("Setting 1st run Fail #: " i "`terrorCode: " returnCode[i] "`t"firstRunCgi[i])
txt = `ncgi[i],skipped
FileAppend, %txt%, cgiLog.txt
cgi[i] :=""
}
else{
; addTextToGui("Setting 1st run OK #: " i "`terrorCode: " returnCode[i] "`t"firstRunCgi[i])
}
Sleep (cgiDelay)
}
}
now sure why and how but this fixed it:
txt := "`n" cgi[i] ",skipped"
FileAppend, %txt%, cgiLog.csv
See here: AutoHotKey: How to access array with counter variable
In your Example you posted: For i in cgi the variable i contains your Key/Index, so you can access a Value in cgi Array with the Key/Index by: value := cgi[i]
Alternatatively you can declare two variables to hold both your Key/Index and Value directly in your For loop like so:
cgi := ["Hello", "World"]
For i, v in cgi ; Notice the comma
MsgBox % "This is the Key/Index: " i
. "`nThis is the Value from the For loop: " v
. "`nThis Value was accessed using Key/Index: " cgi[i]
Related
My script returns an empty array in another empty array (or I guess it's not empty because there is another empty array within the other array).
I have an if condition that checks if the outer array is empty. It says it's not empty because it contains an empty array. I need help to get it return false. I believe the best method would be to check if the inner array is empty, but I'm not sure where the inner array is created.
Here's the code for the method that checks if the array is empty:
def directory_check(directory_list, save_to_file, today_date, output_file, output_extension, results_file_output)
if directory_list.empty? == false
# changes the working directory to the file output directory for the file
Dir.chdir(save_to_file)
# writes the array contents into a new file
file_name = output_file + "_" + today_date + output_extension
puts Time.now.to_s + " > " + "Saving contents to: " + results_file_output + file_name
puts ""
File.open(file_name, "a+") do |f|
directory_list.each { |element| f.puts(element) }
end
else
puts Time.now.to_s + " > " + "This directory does not contain any subdirectories that are older than 24 hours"
exit
end
end
The directory_list returns [[]], and empty? returns false.
I have another method that stores items into an array, but I cannot figure out why there is an array within an array:
def store_directories(directories, folder_to_exclude)
# updates search directory for each value for the directories hash
subdir_list = Array.new
directories.each do |element|
directory = "#{element}"
puts Time.now.to_s + " > " + "Updating search directory: " + directory
Dir.chdir(directory)
# outputs only subdirectories with a creation date of older than 24 hours, except for folders names 'Archive'
Dir.glob("*.*").map(&File.method(:realpath))
puts Time.now.to_s + " > " + "Gathering subdirectories..."
puts ""
# Stores the contents of the query into an array and appends to the list for each iteration of the array
subdir_list << Dir.glob("*").map(&File.method(:realpath)).reject {|files|
(not File.directory?(files) &&
(File.mtime(files) < (Time.now - (60*1440))) &&
(not files == directory + folder_to_exclude))
}
puts ""
puts "Adding new folders to the list..."
puts ""
puts "Excluding: " + directory + folder_to_exclude
puts ""
puts subdir_list
puts " "
end
return subdir_list
end
I'm passing an array of directories into the store_directories method.
The directory_list returns [[]], and empty? returns false.
it's working properly and it returns correct value, as your directory_list is not empty array, it contain empty array. You need to use Array#flatten
> [[]].flatten.empty?
#=> true
Trying to read from a txt file and have the results be displayed in the message box. I plan on copying and pasting lines of 1000 and deleting them from the array, later in my code. For now I'd like to be able to see that the file can be read into the array and be displayed:
Local $List
FileReadToArray( "C:/Users/Desktop/recent_list.txt", $List [, $iFlags = $FRTA_COUNT [, $sDelimiter = ""] ])
MsgBox( 0, "Listing", $List )
I get an error:
>"C:\Program Files (x86)\AutoIt3\SciTE\..\autoit3.exe" /ErrorStdOut "C:\Users\Documents\Test.au3"
"FileReadToArray" has no other parameters than the file to read! You have used the function call from "_FileReadToArray".
The square brackets in the function line means: This parameters are optional! If you want to use them with the default values, its not required to write them in the function call.
And "FileReadToArray" reads the content of a file into an array. Thats why your call should look like so:
Local $arList = FileReadToArray("C:/Users/Desktop/recent_list.txt")
; to show every line in a MsgBox you must iterate
; through the result array
For $i = 0 To UBound($arList) -1
; MsgBox is not sensefull with hundred of lines in file!
; MsgBox(0, 'Line ' & $i+1, $arList[$i])
; better way - console output
ConsoleWrite('['& $i+1 & '] ' & $arList[$i] & #CRLF)
Next
I want to use an expression like
#{ %$hashref{'key_name'}[1]
or
%$hashref{'key_name}->[1]
to get - and then test - the second (index = 1) member of an array (reference) held by my hash as its "key_name" 's value. But, I can not.
This code here is correct (it works), but I would have liked to combine the two lines that I have marked into one single, efficient, perl-elegant line.
foreach my $tag ('doit', 'source', 'dest' ) {
my $exists = exists( $$thisSectionConfig{$tag});
my #tempA = %$thisSectionConfig{$tag} ; #this line
my $non0len = (#tempA[1] =~ /\w+/ ); # and this line
if ( !$exists || !$non0len) {
print STDERR "No complete \"$tag\" ... etc ... \n";
# program exit ...
}
I know you (the general 'you') can elegantly combine these two lines. Could someone tell me how I could do this?
This code it testing a section of a config file that has been read into a $thisSectionConfig reference-to-a-hash by Config::Simple. Each config file key=value pair then is (I looked with datadumper) held as a two-member array: [0] is the key, [1] is the value. The $tag 's are configuration settings that must be present in the config file sections being processed by this code snippet.
Thank you for any help.
You should read about Arrow operator(->). I guess you want something like this:
foreach my $tag ('doit', 'source', 'dest') {
if(exists $thisSectionConfig -> {$tag}){
my $non0len = ($thisSectionConfig -> {$tag} -> [1] =~ /(\w+)/) ;
}
else {
print STDERR "No complete \"$tag\" ... etc ... \n";
# program exit ...
}
Heyho
I want to repeat a program after runnning a task. At the start of the program I ask some questions, than the code jumps into the task. If the task is done the questions sholud ask again..
Each Question reads some infos at the serial port. If i get the infos ten times ich will restart the programm.. but the window closes and i must start the file..
What can i do?
import serial
import struct
import datetime
print("\n")
print("This tool reads the internal Bus ")
print("-----------------------------------------------------------------------")
COM=input("Check your COM Port an fill in with single semicolon (like: 'COM13' ): ")
ser = serial.Serial(
port=COM,
baudrate=19200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
print("\n")
print("Please choose an option: ")
print("Polling of measured values and the operating status (1)")
print("Reading Parameter memory (2)")
print("Reading Fault memory (3)")
print("EXIT (4)")
print("\n")
i=input("Reading: ")
while(i==1):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x14\x75\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(46))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Values: ,")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
loop=1
#-----------------------------------------------------------------------
while(i==2):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x13\x00\x00\x74\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(11))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Parameters: , ")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
#---------------------------------------------------------------------
while(i==3):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x12\x00\x00\x73\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(11))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Fault: , ")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
#----------------------------------------------------------------------
while(i==4):
file.close()
ser.close()
sys.exit(0)
file.close()
ser.close()
First, you should use If/Elif/Else statements instead of while loops.
while(i==1):
should be
if(i==1)0:
This is a simple program I wrote that you can follow:
# setup a simple run_Task method (prints number of times through the loop already)
def run_task(count):
print "Ran a certain 'task'", count,"times"
# count is a variable that will count the number of times we pass through a loop
count = 0
# loop through 10 times
while(count<10):
# ask questions
q1 = raw_input("What is your name?")
q2 = raw_input("What is your favorite color?")
# run a 'task'
run_task(count)
I have a small text file that I would like to extract some values using autohotkey.
Example of text file's content:
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
My current code:
FileReadLine, datetime, C:\File.txt, 1
datedsp := SubStr(datetime, 7)
Sleep 500
FileReadLine, study, C:\File.txt, 2
studydsp := SubStr(study, 7)
Sleep 500
FileReadLine, image, C:\File.txt, 3
imgdsp := SubStr(image, 7)
Sleep 500
FileReadLine, notes, C:\File.txt, 5
notesdsp := SubStr(notes, 7)
Sleep 500
MsgBox %datedsp%
MsgBox %studydsp%
MsgBox %imgdsp%
MsgBox %notesdsp%
All I want to do is to grab the value of each of those lines and assign it to variables. For example, studydsp value would be G58500411, imagedsp value would be 6.24, datedsp value would be 2014-12-02 12:06:47.
Is there anyway to achieve this in a better way?
Possible issues with this code:
I am unable to get the string from the date line perhaps due to a space at
the beginning(?)
I can't get the SubStr value of either date (refer to 1st issue) or
study (perhaps because of special characters?)
You can use FileRead and RegExMatch
var:="
(
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
)"
;~ FileRead, var, C:\file.txt
pos:=1
while pos := RegExMatch(var, "\s?(.*?):(.*?)(\v|\z)", m, pos+StrLen(m))
%m1% := m2
msgbox % "Date holds " date
. "`nStudy holds " Study
. "`nImage holds " Image
. "`nTlbar holds " Tlbar
. "`nNotes holds " Notes
Just remove the var part and uncomment the fileread line, at least thats one way to do it to :)
hope it helps
Basically the same as #blackholyman's answer, but using an object based approach by building a value map:
fileCont =
(
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
)
valueMap := {}
; Alternatively, use: Loop, Read, C:\file.txt
Loop, Parse, fileCont, `r`n
{
RegExMatch(A_LoopField, "(.*?):(.*)", parts)
; Optionally make keys always lower case:
; StringLower, parts1, parts1
valueMap[Trim(parts1)] := Trim(parts2)
}
msgbox % "Date = " valueMap["Date"]
. "`nImage = " valueMap["Image"]
; We can also iterate over the map
out := ""
for key, val in valueMap
{
out .= key "`t= " val "`n"
}
msgbox % out