When defining a variable in a julia function, I get an error about an undefined variable on that line - function

Problem
I'm writing a Julia script, and in the function there is a while loop. Inside the while loop there is a variable. That line is throwing errors about the variable being undefined when in fact that is the very line defining the variable.
The code
The error is on line 65
function cleanTexLoop(fileName::String)
f = open(fileName, "r")
while ! eof(f)
line = readline(f), <-- line 65
#line = sentenceFilter(line)
println(line)
end
close(f)
end
The function opens a file which IS getting passed into a loop. The loop runs until the end of file. While looping the file is read line by line. Each time it is read the line is stored in variable line and the file advances. In the proper version, that one line (66) isn't commented out, however for debugging it is. line is then taken as input into a filter which modifies the line before storing it again as line. The final version of this script will have four filters, but for now, I'd be happy to get this to run with just zero filters.
(Note that a user has kindly pointed out the comma that after hours of looking at the code continued to allude me. I'm waiting for that user to write up an answer)
The error message
cleanTexLoop("test.tex")
ERROR: UndefVarError: line not defined
Stacktrace:
[1] cleanTexLoop(::String) at /home/nero/myScripts/latexCleaner.jl:65
[2] macro expansion at ./REPL.jl:97 [inlined]
[3] (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at > ./event.jl:73
Previous working version
I had previous written another version of this which works in entirety, however I needed to make some substantial changes to its structure in order to better suit future plans. Note that some of the names aren't up to the normal naming convention. Namely, I use "!" when no variables are actually being changed.
function CleanTexLoop(fileName::String,regX::String,sub::String)
f = open(fileName, "r")
while ! eof(f)
println(applySub!(f,regX,sub))
end
close(f)
end
function applySub!(file::IOStream,regX::String,sub::String)
return replace(
readline(file),
Base.Regex(regX),
Base.SubstitutionString(sub)
)
end
A simple loop which demonstrates why this should work
x = 0
while x < 4
y = x
println(y)
x = x+1
end
As expected, this prints zero to one, and is, as far as I can tell, representative of what I am doing. In both cases I am passing some variable into the loop which, through some action, defines another variable inside the loop which is then printed. Why this works, and the other doesn't is beyond me.
What I've seen on Google.
From looking this problem up, it appears as if this problem arrises when defining variables outside of a loop, or similar environment, as a result of them failing to be passed into the environment. However, this isn't what's happening in my case. In my case the variable is being defined for the first time.

As mentioned in the comments, the problem was an errant comma.

Related

It is possible to obtain the mean of different files to make some computations with it after?

I have a code to calculate the mean of the first five values of each column of a file, for then use these values as a reference point for all set. The problem is that now I need to do the same but for many files. So I will need to obtain the mean of each file to then use these values again with the originals files. I have tried in this way but I obtain an error. Thanks.
%%% - Loading the file of each experiment
myfiles = dir('*.lvm'); % To load every file of .lvm
for i = 1:length(myfiles) % Loop with the number of files
files=myfiles(i).name;
mydata(i).files = files;
mydata(i).T = fileread(files);
arraymean(i) = mean(mydata(i));
end
The files that I need to compute are more or less like this:
Delta_X 3.000000 3.000000 3.000000
***End_of_Header***
X_Value C_P1N1 C_P1N2 C_P1N3
0.000000 -0.044945 -0.045145 -0.045705
0.000000 -0.044939 -0.045135 -0.045711
3.000000 -0.044939 -0.045132 -0.045706
6.000000 -0.044938 -0.045135 -0.045702
Your first line results in 'myfiles' being a structure array with components that you will find defined when you type 'help dir'. In particular, the names of all the files are contained in the structure element myfiles(i).name. To display all the file names, type myfiles.name. So far so good. In the for loop you use 'fileread', but fileread (see help fileread) returns the character string rather than the actual values. I have named your prototype .lvm file DinaF.lvm and I have written a very, very simple function to read the data in that file, by skipping the first three lines, then storing the following matrix, assumed to have 4 columns, in an array called T inside the function and arrayT in the main program
Here is a modified script, where a function read_lvm has been included to read your 'model' lvm file.
The '1' in the first line tells Octave that there is more to the script than just the following function: the main program has to be interpreted as well.
1;
function T=read_lvm(filename)
fid = fopen (filename, "r");
%% Skip by first three lines
for lhead=1:3
junk=fgetl(fid);
endfor
%% Read nrow lines of data, quit when file is empty
nrow=0;
while (! feof (fid) )
nrow=nrow + 1;
thisline=fscanf(fid,'%f',4);
T(nrow,1:4)=transpose(thisline);
endwhile
fclose (fid);
endfunction
## main program
myfiles = dir('*.lvm'); % To load every file of .lvm
for i = 1:length(myfiles) % Loop with the number of files
files=myfiles(i).name;
arrayT(i,:,:) = read_lvm(files);
columnmean(i,1:4)=mean(arrayT(i,:,:))
end
Now the tabular values associated with each .lvm file are in the array arrayT and the mean for that data set is in columnmean(i,1:4). If i>1 then columnmean would be an array, with each row containing the files for each lvm file. T
This discussion is getting to be too distant from the initial question. I am happy to continue to help. If you want more help, close this discussion by accepting my answer (click the swish), then ask a new question with a heading like 'How to read .lvm files in Octave'. That way you will get the insights from many more people.

What is this line getting from a different file (TCL)?

I am including the relevant code below, and I can explain what I know it is doing up to this point:
proc rshm {where {i 0}} {
global ob
set what "???"
set ob(last_rshm_failed) "yes"
if {![info exists ob(shm)]} {
return "0.0"
}
if {[info exists ob(shm_puts_exist_in_progress)]} {
return "0.0"
}
shm_puts "g $where $i"
gets $ob(shm) istr
set what [lindex $istr 0]
set ob(last_rshm_failed) "no"
if {[string equal $what "?"]} {
set ob(last_rshm_failed) "yes"
puts stderr $istr
return "0.0"
}
set what [lindex $istr 3]
return $what
}
From looking at the rest of the program, I have concluded that the first two if statements are checking for errors elsewhere and are designed to terminate the procedure if the errors trigger.
Elsewhere in the program, the place (of interest) that the function gets called is in the form: rshm ft_xdev
Using print statements, I found that ft_xdev passes into the procedure as shm_puts "g ft_xdev 0".
The line that is throwing me off is the line: gets $ob(shm) istr
The call to $ob(shm) is another file (originally a binary program, but the readable version is in C...), but upon looking at this file, there is no reference to anything called "istr".
Would someone mind helping me out with what this line is getting from the other file? If needed, I can provide more code from the program.
The code:
gets $ob(shm) istr
will pass the contents of the ob(shm) variable (which should be a channel handle that is at least open for reading) and the string istr (which is used to name a variable in this case) into the gets command. The istr will be a local variable in this case because it hasn't been explicitly stated to be otherwise.
The gets command, when given two arguments, will read a line of text from the channel (first arg) and write that line of text to the variable (second arg). It then yields as result the number of characters read or -1 if there was a recoverable error condition such as end-of-file. You're ignoring the result. (Critical errors would become exceptions.) This is all documented on the manual page for gets.
tl;dr: Reads a line of text from the $ob(shm) channel and stores it in istr.
This procedure will return the 3rd index of $istr ([lindex $istr 3]) if its not empty or does not fail on the prior checks.
The contents of $istr are obtained from grabbing the next line of the open file channel $ob(shm) (if the channel is already open and $ob(shm_puts_exist_in_progress) does not exist).
If shm_puts "g $where $i" impacts the $ob in any way, it would be important to include the procedure shm_puts since it may impact $istr, but I suspect the contents of shm_puts are not relevant to $istr.
Finally if $istr starts with a ? then it aborts this procedure displaying the contents of $istr to stderr. That is, if a line of the file starts with ?, then the procedure aborts.
All procedure aborts (ie IF checks) do not retain the contents of $istr, since its a local variable not a global one, so checking the contents of $istr must be done within this procedure and after the gets command.

printing the output of shell command from python subprocess

I am running a shell script which emits lots of line while executing...they are just status output rather than the actual output....
I want them to be displayed on a JTextArea. I am working on jython. The piece of my code looks like:
self.console=JTextArea(20,80)
cmd = "/Users/name/galaxy-dist/run.sh"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
self.console.append(p.stdout.read())
This will wait until the command finishes and prints the output. But I want to show the realtime out put to mimic the console. Anybody have the idea ?
You're making things more complicated than they need to be. The Popen docs state the following about the stream arguments:
With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. [my emphasis]
Therefore, if you want the subprocess' output to go to your stdout, simply leave those arguments blank:
subprocess.Popen(cmd, shell=True)
In fact, you aren't using any of the more advanced features of the Popen constructor, and this particular example doesn't need any parsing by the shell, so you can simplify it further with the subprocess.call() function:
subprocess.call(cmd)
If you still want the return code, simply set a variable equal to this call:
return_code = subprocess.call(cmd)

Trying to redirect output of a command to a variable

>> set signal_name [get_fanout abc_signal]
{xyz_blah_blah}
>> echo $signal_name
#142
>> set signal_name [get_fanout abc_signal]
{xyz_blah_blah}
>> echo $signal_name
#144
>>
I tried other stuff like catch etc, and every where, it returns #number. My goal is to be able to print the actual value instead of the number - xyz_blah_blah.
I am new to tcl. Want to understand, if this is an array or a pointer to an array or something like that. When I try the exact same thing with a different command, which returns just a value, then it works. This is a new command which returns value in parenthesis.
Please help. Thanks.
Every Tcl command produces a result value, which you capture and use by putting the call of the command in [square brackets] and putting the whole lot as part of an argument to another command. Thus, in:
set signal_name [get_fanout abc_signal]
the result of the call to get_fanout is used as the second argument to set. I suggest that you might also like to try doing this:
puts "-->[get_fanout abc_signal]<--"
It's just the same, except this time we're concatenating it with some other small string bits and printing the whole lot out. (In case you're wondering, the result of puts itself is always the empty string if there isn't an error, and set returns the contents of the variable.)
If that is still printing the wrong value (as well as the right one beforehand, without arrow marks around it) the real issue may well be that get_fanout is not doing what you expect. While it is possible to capture the standard output of a command, doing so is a considerably more advanced technique; it is probably better to consider whether there is an alternate mechanism to achieve what you want. (The get_fanout command is not a standard part of the Tcl language library or any very common add-on library like Tk or the Tcllib collection, so we can only guess at its behavior.)

Calling an internal "function" in CMD script not updating the variable

In this NT cmd shell\"batch file" I scrabbled together the other day, I'm using the call command to run sections of the script like functions--as I have done many times before in other scripts. But one of this is behaving strange and I can't figure out what might be wrong...
The problem is that the first time the function is called it properly returns the errorcode and sets the (global) variable %RESULT%, but every time it's called again later it fails to update the variable with the new errorcode.
Here's a stripped-down version of the code in question:
:FACL
REM run fileacl.exe with given OPTIONS (%1)
REM uses global variables %TARGET% and %LOGPATH%, sets global %RESULT%
setlocal
set _OPTIONS_=%*
fileacl.exe "%TARGET%" %_OPTIONS_% /SILENT >%LOGPATH%\temp.out 2>%LOGPATH%\temp.err
set _RESULT_=%ERRORLEVEL%
if defined DEBUG echo INSIDE FUNCTION: _RESULT_ = %_RESULT_%
endlocal & set RESULT=%_RESULT_% & goto :EOF
The function is called in lines like this:
call :FACL /LINE
if defined DEBUG echo AFTER TEST #1: RESULT = %RESULT%
...
call :FACL /INHERIT /REPLACE /FORCE
if defined DEBUG echo AFTER FIX #2: RESULT = %RESULT%
You see those if defined DEBUG... lines there? They show me that inside the function, subsequent calls are succeeding and thus printing out the expected %_RESULT_% of 0, but the global %RESULT% remains the same. Here's some example output:
TEST #1:
INSIDE FUNCTION: _RESULT_ = 107 <-- that's what I expect for the first call
AFTER TEST #1: RESULT = 107 <-- the variable was properly set after the first call
FIX #2:
INSIDE FUNCTION: _RESULT_ = 0 <-- command succeeded :)
AFTER FIX #2: RESULT = 107 <-- variable didn't change :(
RETEST:
INSIDE FUNCTION: _RESULT_ = 0 <-- succeeded again
AFTER RETEST: RESULT = 107 <-- still didn't change
You may ask: what else have you tried? Okay:
Removed the setlocal\endlocal tricks and just used the global %RESULT% variable
Explicitly undefined %RESULT% and %_RESULT_% (e.g. set RESULT=) before each time the function is called
...all with the same results. Is there something I'm missing here?
Can't be sure, because we can't see the actual code in context. But the behavior you are describing is to be expected if the FIX 2 CALL and ECHO are within a parenthesized block - perhaps as part of an IF statement or FOR loop.
If that is the case, then you need to use delayed expansion within the parentheses since the entire block is parsed prior to execution and the %RESULT% is expanded at parse time.
Use SET EnableDelayedExpansion to enable delayed expansion, and use !RESULT! instead of %RESULT% to get the value of RESULT at execution time instead of at parse time.