Loading 'A' lua module from 'B' lua module using package.cpath package.path - module

Applying this example of module in HighResolutionTimer, enter link description here, I just encounter some issue attempting to call by B module the A minimalist module that use a HighResTimer.dll build under Msys2 with gcc.
I got the error:
And the corresponding text:
./TimerTest.lua default arch : x86 arch updated : x64 == testing require from TimerTest.lua default arch : x86 arch updated : x64
execution time: 150.9933ms == end testing require from TimerTest.lua
C:\msys64\mingw32\bin\lua.exe: ./TimerTest.lua:33: attempt to index a
boolean value (local 'foo') stack traceback:
./TimerTest.lua:33: in main chunk
[C]: in ?
You can see that a first call to the minimalist inner test HighRestimer.lua which add package.cpath the Timer.dll is working on and well outputing number of elapsed ms.
This is the code:
#!/mingw64/bin/lua
------------------------------------
---HighResTimer.lua by Cody Duncan
---Wraps the High Resolution Timer Functions in
--- HighResTimer.so
------------------------------------
--
--
-- code to make script compatible within or without vim
--
--
---- init_packages {{{
basebase = 'foobar/'
function init_packages()
base = basebase .. 'lua/packages/'
arch = 'x86'
print('default arch : ' .. arch)
arch = os.getenv('MSYSTEM_CARCH') == 'x86_64' and 'x64' or 'x86'
print('arch updated : ' .. arch)
--assuming that Timer.dll got distinguished name from lua module HighResTimer.lua
package.cpath = package.cpath .. ';' .. base .. 'HighResTimer/' .. arch .. '/?.dll'
end
init_packages()
---- }}}
local timer = require("Timer") --load up the module
timer.readHiResTimerFrequency()
---- api functions {{{
----call this before code that is being measured for execution time
function start()
timer.storeTime();
end
----call this after code that is being measured for execution time
function stop()
timer.storeTime();
end
----once the prior two functions have been called, call this to get the
----time elapsed between them in nanoseconds
function getNanosElapsed()
return timer.getNanoElapsed();
end
-- }}}
---- inner unit test {{{
----
function innertest()
start();
for i = 0, 3000000 do io.write("") end --do essentially nothing 3million times.
stop();
----divide nanoseconds by 1 million to get milliseconds
executionTime = getNanosElapsed()/1000000;
if inVim == true then
print("execution time: ", executionTime, "ms\n");
else
io.write("execution time: ", executionTime, "ms\n");
end
end
innertest()
-- }}}
-- vim: set ft=lua ff=dos fdm=marker ts=2 :expandtab:
This 'A' module execution works well, displaying some inner result test in milliseconds. The problem comes when i call this 'A' lua module from a 'B' lua module with this code:
#!/mingw32/bin/lua
------------------------------------
---TimerTest.lua by Cody Duncan
---
---HighResTimer.lua and Timer.so must
--- be in the same directory as
--- this script.
------------------------------------
--
---- init_packages {{{
basebase = 'foobar/'
function init_packages()
base = basebase .. 'lua/packages/'
arch = 'x86'
print('default arch : ' .. arch)
arch = os.getenv('MSYSTEM_CARCH') == 'x86_64' and 'x64' or 'x86'
print('arch updated : ' .. arch)
package.path = package.path .. ';' .. base .. 'HighResTimer/' .. arch .. '/?.lua'
end
init_packages()
---- }}}
print(' == testing require from TimerTest.lua')
require('HighResTimer')
print(' == end testing require from TimerTest.lua')
local foo = require("HighResTimer")
foo.start();
-- for i = 0, 3000000 do io.write("") end --do essentially nothing 3million times.
-- foo.stop();
--divide nanoseconds by 1 million to get milliseconds
-- executionTime = getNanosElapsed()/1000000;
-- io.write("execution time: ", executionTime, "ms\n");
-- vim: set ft=lua ff=dos fdm=marker ts=2 :expandtab:
The require 'A' Highrestimer.lua seems to not causing troubleshoot but the mine after local foo =... cause the error.
Notice that in 'A' module i use package.cpath in some particular way to load dll meanwhile i use package.path in the 'B' module TimerTest.lua.

Related

$? tcsh script issue

I am confused with a tcsh shell script issue. (for work, no choice in shell, I'm stuck with it)
The enableThingN items below are shell enviroment variables set by other things before running this csh script, using tcsh shell. These are not set within the same script here at all, only evaluated here.
Error message is:
enableThing1: Undefined variable.
Code is:
if ( ( $?enableThing1 && ($enableThing1 == 1) ) || \
( $?enableThing2 && ($enableThing2 == 1) ) || \
( $?enableThing3 && ($enableThing3 == 1) ) || \
( $?enableThing4 && ($enableThing4 == 1) ) ) then
set someScriptVar = FALSE
else
set someScriptVar = TRUE
endif
So, as I understand things, the first part of the big if condition is to check if enableThing1 is defined at all or not, using the $?enableThing1 magic. If it is defined, then move on and check the value is 1 or something else. If not defined, then skip the ==1 part of the check for the same shell variable, and move on to see if enableThing2 is defined at all or not, and so on.
As it seems like I am checking for existence, and intend to avoid checking value if it is not defined at all, where have I gone wrong?
I have searched here on stackoverflow and on Google at large, but there are few results and don't get me to an answer, such as:
https://stackoverflow.com/questions/16975968/what-does-var-mean-in-csh
An if statement to check the value of the variable requires that the variable exists.
if ( ( $?enableThing1 && ($enableThing1 == 1) ) || \
# ^ this will fail if the variable is not defined.
So the if condition turns into
if ( ( 0 && don'tknowaboutthis ) || \
and it falls flat.
Assuming you don't want an if ladder, and functionality to add to this list of variables to check for, you can try the following solution:
#!/bin/csh -f
set enableThings = ( enableThing1 enableThing2 enableThing3 enableThing4 ... )
# setting to false initially
set someScriptVar = FALSE
foreach enableThing ($enableThings)
# since we can't use $'s in $? we'll have to do something like this.
set testEnableThing = `env | grep $enableThing`
# this part is for checking if it exists or not, and if it's enabled or not
if (($testEnableThing != "") && (`echo $testEnableThing | cut -d= -f2` == 1 )) then
# ^ this is to check if the variable is defined ^ this is to take the part after the =
# d stands for delimiter
# for example, the output of testEnableThing, if it exists, would be enableThing1=1
# then we take that and cut it to get the value of the variable, in our example it's 1
# if it exists and is enabled, set your someScriptVar
set someScriptVar = TRUE
# you can put a break here since it's irrelevant to check
# for other variables after this becomes true
break
endif
end
This works because we are only working with one variable, "testEnableThing", which is always defined due to the way this works. It can be a blank string, but it will be defined so our if statement won't fall flat.
Hope this solves it for you.

Fortran read() reads last line twice?

So, suppose I'm trying to read in a file the length of which I don't know before hand. We can use iostat and a while loop to break when we need to, but I'm having an issue with this. Namely, the code I've written reads the last line twice. I'm sure there is an obvious solution, but I can't seem to figure it out. I don't really understand how either the read() or iostat functions work entirely (I'm pretty new at fortran), but I can't glean much from documentation so I'm hoping someone here can help.
Here is the (relevant bit of) code I've written:
filename = 'test.txt'
iostat_1 = 0
iostat_2 = 0
open(newunit = lun, file = filename, status = 'old', iostat = iostat_1)
if (iostat_1 == 0) then
do while(iostat_2 == 0)
if(iostat_2 == 0) then
read(lun,*,iostat = iostat_2) dum, real_1,real_2,int_1
print *, dum, real_1,real_2,int_1
endif
enddo
endif
So, supposing my input file is
1 1.0 1.0 1
2 2.0 2.0 1
3 3.0 3.0 1
4 4.0 4.0 4
Then the output to the terminal from the print statement will be
1 1.0 1.0 1
2 2.0 2.0 1
3 3.0 3.0 1
4 4.0 4.0 4
4 4.0 4.0 4
So keep in mind the following: The main purpose here is to be able to read in a file with an arbitrary number of lines. I'm not interested in a solution involving reading the number of lines first.
Thanks for the help!
UPDATE Okay I just solved the problem. That being said, I'm wondering if there is a solution less clumsy than mine. Here is what I did to fix the issue
! Body of ReInsert
filename = 'rpriov3.dat'
iostat_1 = 0
iostat_2 = 0
open(newunit = lun, file = filename, status = 'old', iostat = iostat_1)
if (iostat_1 == 0) then
do while(iostat_2 == 0)
if(iostat_2 == 0) then
read(lun,*,iostat = iostat_2) dum, real_1,real_2,int_1
if(iostat_2 == 0) then !<---- Added this nested if statement
print *, dum, real_1,real_2,int_1
endif
print *, iostat_2
endif
enddo
endif
As you found out, when you set an iostat parameter, the read command doesn't overwrite the variables it asks for.
Your solution is, as you already noticed, somewhat convoluted.
Firstly:
do while (condition)
if (condition) then
...
end if
end do
In this case, the inner if statement is complete surplus. The loop doesn't run unless condition is true, so unless the evaluation of condition itself doesn't change the result 1), the if clause will always be executed.
The second thing I'd look at is: What should happen if the open fails? In most cases, I want to print an error and quit:
open(..., iostat=ios)
if (ios /= 0) then
print*, "Error opening file"
STOP 1
end if
do while (...)
...
end do
Even if you don't want to exit the program in case of an error in open, there are usually ways to make the code more readable than eternal nesting. For example, you could ask the user for a filename again and again (in its own loop) for a file name, until either the file opens, or the user enters some quit message.
ios = 1
do while (ios /= 0)
write(*, *, advance='no') "Enter filename (or 'quit') :"
read(*, *) filename
if ( trim(filename) == "quit" ) STOP
open(newunit=lun, file=filename, ..., iostat=ios)
end do
Finally there's the most inner if block. Since you want to exit the loop anyway when you reach an error, you can use the exit statement inside a loop to exit it immediately without executing the rest of the loop block:
do
read(..., iostat=ios) ...
if (ios /= 0) exit
print *, ....
end do
This is an infinite loop with an explicit exit as soon as it encounters a read error (usually, but not necessarily an EOF). Since the print statement is after the exit, it won't be executed in case of such an error.
1) What I mean by that is something like this C snippet i++ < 10, which both tests i against 10 and increments it.

iSpin LTL property evaluation only with activated "assertion violations"?

I am trying to get used to iSpin/Promela. I am using:
Spin Version 6.4.3 -- 16 December 2014,
iSpin Version 1.1.4 -- 27 November 2014,
TclTk Version 8.6/8.6,
Windows 8.1.
Here is an example where I try to use LTL. The verification of the LTL property should produce an error if the two steps in the for loop are non-atomic:
1 #define ten ((n !=10) && (finished == 2))
2
3 int n = 0;
4 int finished = 0;
5 active [2] proctype P() {
6 //assert(_pid == 0 || _pid == 1);
7
8 int t = 0;
9 byte j;
10 for (j : 1 .. 5) {
11 atomic {
12 t = n;
13 n = t+1;
14 }
15 }
16 finished = finished+1;
17 }
18
19 ltl alwaysten {[] ! ten }
In the verification tap I just want to test the LTL property, so I disable all safety properties and activate "use claim". The claim name is "alwaysten".
But it seems that the LTL property is just evaluated if I activate "assertion violations". Why? A collegue is using iSpin v1.1.0 and he does not need to activate this? What am I doing wrong? I want to prove assertions and LTL properties independently...
Here is the trace:
pan: elapsed time 0.002 seconds
To replay the error-trail, goto Simulate/Replay and select "Run"
spin -a 1_2_ConcurrentCounters_8.pml
ltl alwaysten: [] (! (((n!=10)) && ((finished==2))))
C:/cygwin/bin/gcc -DMEMLIM=1024 -O2 -DXUSAFE -w -o pan pan.c
./pan -m10000 -E -a -N alwaysten
Pid: 6980
warning: only one claim defined, -N ignored
(Spin Version 6.4.3 -- 16 December 2014)
+ Partial Order Reduction
Full statespace search for:
never claim + (alwaysten)
assertion violations + (if within scope of claim)
acceptance cycles + (fairness disabled)
invalid end states - (disabled by -E flag)
State-vector 36 byte, depth reached 57, errors: 0
475 states, stored
162 states, matched
637 transitions (= stored+matched)
0 atomic steps
hash conflicts: 0 (resolved)
Stats on memory usage (in Megabytes):
0.024 equivalent memory usage for states (stored*(State-vector + overhead))
0.291 actual memory usage for states
64.000 memory used for hash table (-w24)
0.343 memory used for DFS stack (-m10000)
64.539 total actual memory usage
unreached in proctype P
(0 of 13 states)
unreached in claim alwaysten
_spin_nvr.tmp:8, state 10, "-end-"
(1 of 10 states)
pan: elapsed time 0.001 seconds
No errors found -- did you verify all claims?
This is because your LTL is translated into a claim with an assert statement. See the following automaton.
So, without checking for assertion violations, no error can be found.
(A possible explanation of different behaviors: previous versions of Spin might translate this differently, perhaps using accept instead of assert.)

How-to; Echo entire "goto" section

I am working on a text based adventure game for a few friends and I to work through in batch. I'd like to make the option to have an entire section of variables echoed when wanted. Below is the entry code. The first section, Variables, is not an accessed section, but creates variables prior to the game starting. The second section, stats, provides these variables echoed.
#ECHO OFF
::Variables
set Name=Und
set Gender=Und
set Age=Und
set Gold=0
set Hunger=Satisfied
set Illness=None
set Wounds=None
set CHP=10
set MHP=10
set CMP=0
set MMP=0
goto Start
::Stats
:Stats
cls
echo Name: %Name%
echo Gender: %Gender%
echo Age: %Age%
echo Gold: 0
echo.
echo Health
echo Hunger: %Hunger%
echo Illness: %Illness%
echo Wounds: %Wounds%
echo.
echo Stats
echo HP: %CHP%/%MHP%
echo MP: %CMP%/%MMP%
My current solution to this issue is using
set /p "situation"= :
if "%situation%"=="1" goto nextpart
if "%situation%"=="2" goto nextpart
if "%situation%"=="3" goto nextpart
if "%situation%"=="Stats" goto Stats.
The issue with this method, however, is that once in stats, I have no way to jump to the previous section. It would require me making an exit gateway to every possible section I've created. So the question:
Can I have a series of variables echoed without leaving the current section?
You can use Call:stats in place of goto:stats.
Like this it will comme back in the current section
Edit :
#echo off
set $var=1000
call:aff
echo done
exit/b
:aff
echo %$var%
You can get Lua here
There's a somewhat out of date version of the Lua book here.
Here's an example of how you could write this in Lua:
-- create a bunch of variables
Name = nil
Gender = nil
Age = nil
Gold = 0
Hunger = 'Satisfied'
Illness = 'None'
Wounds = 'None'
CHP = 10
MHP = 10
CMP = 0
MMP = 0
-- create a routine whose job it is to print the variables
function stats()
print(' Name: ' .. Name )
print('Gender: ' .. Gender )
print(' Age: ' .. Age )
print(' Gold: ' .. Gold )
print('Health' )
print(' Hunger: ' .. Hunger )
print('Illness: ' .. Illness )
print(' Wounds: ' .. Wounds )
print('' )
print('Stats' )
print(' HP: ' .. CHP .. '/' .. MHP )
print(' MP: ' .. CMP .. '/' .. MMP )
end
-- call the routine
stats()
This appears more verbose that your BAT code, but once your game logic starts to get complicated, using a real programming language will make it much easier and more rewarding.
The easy way to arrange a save/restore regime in batch is to reserve a prefix for the variables to be saved/restored. For instance, if you were to reserve $ for the variables of interest, then
set $>savefile
is all you'd need to save all of the $ variables to a file and
for /f "delims=" %%a in (savefile) do set %%a
would restore them.

Maximum likelihood programming in Stata

I am trying to learn ml programming in Stata. As a part of this I am running a program myprobit (the code is adopted from Maximum likelihood estimation with Stata by Gould, Pitblado, and Sribney).
capture program drop myprobit
program define myprobit
args todo b lnf g negH g1
tempvar xb lj
mleval `xb'=`b'
quietly{
gen double `lj'=normal(`xb') if $ML_y1==1
replace `lj'=normal(-`xb') if $ML_y1==0
mlsum `lnf'=ln(`lj')
if (`todo'==0|`lnf'>= .) exit
replace `g1'= normalden(`xb')/`lj' if $ML_y1==1
replace `g1'=-normalden(`xb')/`lj' if $ML_y1==0
mlvecsum `lnf' `g'=`g1', eq(1)
if (`todo'==1|`lnf'==>.)exit
mlmatsum `lnf' `negH'=`g1'*(`g1'+`xb'),eq(1,1)
}
end
sysuse cancer, clear
gen drug2=drug==2
gen drug3=drug==3
ml model d1 myprobit (died=drug2 drug3 age)
ml check
ml maximize
But, I got an error varlist required:
Here is a trace of its execution:
------------------------------------------------------------------------------
-> myprobit 1 __000000 __000001 __000002 __000003
- `begin'
= capture noisily version 11: myprobit 1 __000000 __000001 __000002 __000003
---------------------------------------------------------------------------------------------------------------------------------- begin myprobit ---
- args todo b lnf g negH g1
- tempvar xb lj
- mleval `xb'=`b'
= mleval __000005=__000000
- quietly{
- gen double `lj'=normal(`xb') if $ML_y1==1
= gen double __000006=normal(__000005) if died==1
- replace `lj'=normal(-`xb') if $ML_y1==0
= replace __000006=normal(-__000005) if died==0
- mlsum `lnf'=ln(`lj')
= mlsum __000001=ln(__000006)
- if (`todo'==0|`lnf'>= .) exit
= if (1==0|__000001>= .) exit
- replace `g1'= normalden(`xb')/`lj' if $ML_y1==1
= replace = normalden(__000005)/__000006 if died==1
varlist required
replace `g1'=-normalden(`xb')/`lj' if $ML_y1==0
mlvecsum `lnf' `g'=`g1', eq(1)
if (`todo'==1|`lnf'==>.)exit
mlmatsum `lnf' `negH'=`g1'*(`g1'+`xb'),eq(1,1)
}
------------------------------------------------------------------------------------------------------------------------------------ end myprobit ---
- `end'
= set trace off
------------------------------------------------------------------------------
Fix myprobit.
r(100);
end of do-file
Note: The program runs without an error if likelihood evaluator is changed to do.
Any suggestion in this regard will be highly appreciated.
You provided 5 arguments to your program, but 6 are needed. Hence local macro g1 is not defined, which bites when you try to replace the variable it names.
Stata is telling you some of this. The lines
- replace `g1'= normalden(`xb')/`lj' if $ML_y1==1
= replace = normalden(__000005)/__000006 if died==1
show that local macro g1 is interpreted as nothing, i.e. an empty string, so Stata complains because it expects a variable name after replace.
The line
if (`todo'==1|`lnf'==>.)exit
is also problematic, as the operator ==> should be >=.
These are the problems I noticed; there may be others.