Well, I'm trying to get the value of packets to be read by the recv with ioctlsocket(FIONREAD), But the function is not returning any value.
Look:
IOCtlSocket = Win32API.new('ws2_32', 'ioctlsocket', 'llp', 'i')
ret_val = -1
result = IOCtlSocket.call #descriptor, 0x4004667f, ret_val
if ret_val > 0
print "Há pacotes a receber"
end
ret_val does not change, no matter what value I place on it .
Anyone have tip's or a solution?
The last parameter is a pointer. Pointers are implemented as strings in Win32API. So you need to do the following:
IOCtlSocket = Win32API.new('ws2_32', 'ioctlsocket', 'llp', 'i')
ret_val_buf = " " * 4 #Prepare a 4-byte buffer
result = IOCtlSocket.call #descriptor, 0x4004667f, ret_val_buf
ret_val = ret_val_buf.unpack("L")
Related
I'm trying to write a method which will allow me to print out positions of a chess game for the top 8 positions.
I have a val mutable initial which is an array of 32 entries,each containing chesspiece * chesscolor * chessposition.
The chessposition is defined as:
chess_position = Alive of chessletter * int | Dead;;
Im trying to print out the positions on the first row of the board for now.
I have the following code:
class chess =
object
val mutable initial = ([|Rook,Black,Alive(A,8); (*... *)|])
method print =
for i = 0 to i = 7 do
for j = 0 to j = 32 do
if initial.(j) = (Pawn,White,Alive(A,i)) then tmp1="P" else
if initial.(j) = (Pawn,Black,Alive(A,i)) then tmp1="p" else
if initial.(j) = (Rook,White,Alive(A,i)) then tmp1="R" else
if initial.(j) = (Rook,Black,Alive(A,i)) then tmp1="r" else
if initial.(j) = (Knight,White,Alive(A,i)) then tmp1="N" else
if initial.(j) = (Knight,Black,Alive(A,i)) then tmp1="n" else
if initial.(j) = (Bishop,White,Alive(A,i)) then tmp1="B" else
if initial.(j) = (Bishop,Black,Alive(A,i)) then tmp1="b" else
if initial.(j) = (Queen,White,Alive(A,i)) then tmp1="Q" else
if initial.(j) = (Queen,Black,Alive(A,i)) then tmp1="q" else
if initial.(j) = (King,White,Alive(A,i)) then tmp1="K" else
if initial.(j) = (King,Black,Alive(A,i)) then tmp1="k" else
tmp1=".";
print_string tmp1;
done
done
end
In the case of normal chess starting positions where the row is white,this should print out:
RNBQKBNR
I'm getting an error of unbound value i and i cant understand why.
On a side note,any advice on classes and methods is appreciated since i'm trying to learn this and currently suck at it.
This line:
for i = 0 to i = 7 do
is not legitimate. It parses as this:
for i = 0 to (i = 7) do
The second expression compares i against 7 for equality. But at that point there is no i defined yet. i is only defined in the body of the for loop.
You want to say:
for i = 1 to 7 do
I have 4 variables which they contain some values.
I have already convert them in numbers with CDbl.
So I have something like that:
var1=CDbl(str1)
var2=CDbl(str2)
var3=CDbl(str3)
var4=CDbl(str4)
How can I find the smallest number between var1, var2, var3 and var4?
The following works. You just have to pass the values as an array.
Function FindSmallest(arr)
out = arr(0)
For i = 1 to UBound(arr)
If out > arr(i) Then
out = arr(i)
End If
Next
FindSmallest = out
End Function
WScript.Echo FindSmallest(Array(var1,var2,var3,var4))
I'm making a JSON parser and I am looking for an algorithm that can find all of the matching brackets ([]) and braces ({}) and put them into a table with the positions of the pair.
Examples of returned values:
table[x][firstPos][secondPos] = type
table[x] = {firstPos, secondPos, bracketType}
EDIT: Let parse() be the function that returns the bracket pairs. Let table be the value returned by the parse() function. Let codeString be the string containing the brackets that I want to detect. Let firstPos be the position of the first bracket in the Nth pair of brackets. Let secondPos be the position of the second bracket in the Nth pair of brackets. Let bracketType be the type of the bracket pair ("bracket" or "brace").
Example:
If you called:
table = parse(codeString)
table[N][firstPos][secondPos] would be equal to type.
Well, In plain Lua, you could do something like this, also taking into account nested brackets:
function bm(s)
local res ={}
if not s:match('%[') then
return s
end
for k in s:gmatch('%b[]') do
res[#res+1] = bm(k:sub(2,-2))
end
return res
end
Of course you can generalize this easy enough to braces, parentheses, whatever (do keep in mind the necessary escaping of [] in patterns , except behind the %b pattern).
If you're not restricted to plain Lua, you could use LPeg for more flexibility
If you are not looking for the contents of the brackets, but the locations, the recursive approach is harder to implement, since you should keep track of where you are. Easier is just walking through the string and match them while going:
function bm(s,i)
local res={}
res.par=res -- Root
local lev = 0
for loc=1,#s do
if s:sub(loc,loc) == '[' then
lev = lev+1
local t={par=res,start=loc,lev=lev} -- keep track of the parent
res[#res+1] = t -- Add to the parent
res = t -- make this the current working table
print('[',lev,loc)
elseif s:sub(loc,loc) == ']' then
lev = lev-1
if lev<0 then error('too many ]') end -- more closing than opening.
print(']',lev,loc)
res.stop=loc -- save bracket closing position
res = res.par -- revert to the parent.
end
end
return res
end
Now that you have all matched brackets, you can loop through the table, extracting all locations.
I figured out my own algorithm.
function string:findAll(query)
local firstSub = 1
local lastSub = #query
local result = {}
while lastSub <= #self do
if self:sub(firstSub, lastSub) == query then
result[#result + 1] = firstSub
end
firstSub = firstSub + 1
lastSub = lastSub + 1
end
return result
end
function string:findPair(openPos, openChar, closeChar)
local counter = 1
local closePos = openPos
while closePos <= #self do
closePos = closePos + 1
if self:sub(closePos, closePos) == openChar then
counter = counter + 1
elseif self:sub(closePos, closePos) == closeChar then
counter = counter - 1
end
if counter == 0 then
return closePos
end
end
return -1
end
function string:findBrackets(bracketType)
local openBracket = ""
local closeBracket = ""
local openBrackets = {}
local result = {}
if bracketType == "[]" then
openBracket = "["
closeBracket = "]"
elseif bracketType == "{}" then
openBracket = "{"
closeBracket = "}"
elseif bracketType == "()" then
openBracket = "("
closeBracket = ")"
elseif bracketType == "<>" then
openBracket = "<"
closeBracket = ">"
else
error("IllegalArgumentException: Invalid or unrecognized bracket type "..bracketType.."\nFunction: findBrackets()")
end
local openBrackets = self:findAll(openBracket)
if not openBrackets[1] then
return {}
end
for i, j in pairs(openBrackets) do
result[#result + 1] = {j, self:findPair(j, openBracket, closeBracket)}
end
return result
end
Will output:
5 14
6 13
7 12
8 11
9 10
There are many reports of slow performance of Octave's dlmread. I was hoping that this was fixed in 3.2.4, but when I tried to load a csv file that has a size of ca. 8 * 4 mil (32 mil in total), it also took very, very long time. I searched the web but could not find a workaround for this. Does anybody know a good workaround?
I experienced the same problem and had R handy, so my solution was to use "read.csv" in R, and then use the R package "R.matlab" to write a ".mat" file, and then load that in Octave.
"read.csv" can be pretty slow too, but this worked very well in my case.
The reason is that Octave has a bug that adding data to a very large matrix takes more time then adding the same amount of data to a small matrix.
Below is my try. I choose to save data each 50000 lines, so meanwhile I could already take a look instead of being forced to wait. It is slower for small files, but much faster for larger files.
function alldata = load_data(filename)
fid = fopen(filename,'r');
s=0;
data=[];
alldata=[];
save "temp.mat" alldata;
if fid == -1
disp("Couldn't find file mydata");
else
while (~feof(fid))
line = fgetl(fid);
[t1,t2,t3,t4,d] = sscanf(line,'%i:%i:%i:%i %f', "C"); #reading time as hh:mm:ss:ms and data as float
s++;
t = (t1 * 3600000 + t2 * 60000 + t3 * 1000 + t4);
data = [data; t, d];
if (mod(s,10000) == 0)
#disp(s), disp(" "), disp(t), disp(" "), disp(d), disp("\n");
disp(s);
fflush(stdout);
end
if (mod(s,50000) == 0)
load "temp.mat";
alldata=[alldata; data];
data=[];
save "temp.mat" alldata;
disp("data saved");
fflush(stdout);
end
end
disp(s);
load "temp.mat";
alldata=[alldata; data];
save "temp.mat" alldata;
disp("data saved");
fflush(stdout);
end
fclose(fid);
Here is a workaround that I am using.
I did not find that sscanf will parse input lines as indicated above. Also, I didn't use the temp file.
My .csv file has a large number of rows. They begin with a header of 18 lines and are followed by a data block, each of which has 135 columns. The following code has been tested. My file also begins each row with a dd/mm/yyyy hh:mm field. This will also catch poor lines and indicate where they are by using try/catch.
My .csv file came from a customer who dumped his PARCView load in an Excel file.
function [tags,descr,alldata] = fbcsvread(filename)
fid = fopen(filename,'r');
s = 0;
data=[];
alldata=zeros(1,135);
if fid==-1
disp("Couldn't find file %s\n",filename);
else
linecount = 1;
while (~feof(fid))
line = fgetl(fid);
data2 = zeros(1,135);
if linecount == 1
tags = strsplit(line,",");
elseif linecount == 2
descr = strsplit(line,",");
elseif linecount >= 19
data = strsplit(line,",");
datetime = strsplit(char(data(1))," ");
modyyr = strsplit(char(datetime(1)),"/");
hrmin = strsplit(char(datetime(2)),":");
year1 = sscanf(char(modyyr(3)),"%d","C");
day1 = sscanf(char(modyyr(2)),"%d","C");
month1 = sscanf(char(modyyr(1)),"%d","C");
hour1 = sscanf(char(hrmin(1)),"%d","C");
minute1 = sscanf(char(hrmin(2)),"%d","C");
realtime = datenum(year1,month1,day1,hour1,minute1);
data2(1) = realtime;
for location = 2:134
try
data2(location) = sscanf(char(data(location)),"%f","C");
catch
printf("Error at %s %s\n",char(datetime(1)),char(datetime(2)) );
fflush(stdout);
end_try_catch
endfor
alldata(linecount-18,:) = data2;
if mod(linecount,50) == 0
printf(".");
fflush(stdout);
endif
endif
linecount = linecount + 1;
endwhile
fclose(fid);
endif
endfunction
Whenever an error occurs in a Lua script, I'd like it to write the values of all local and global variables to the screen/optionally to a file - in addition to the usual stack trace.
How could I get this to be the default behavior for all errors?
If you're using the standard Lua interpreter, replace debug.traceback with your own function. If you're embedding Lua in your program, use your traceback function in lua_pcall.
The StackTracePlus module does what you want, displaying local variables at each level of the stack trace. It doesn't dump the entire globals table, but that is probably overkill.
To install it with LuaRocks, use
luarocks install stacktraceplus
Then in your code, do:
local STP = require "StackTracePlus"
debug.traceback = STP.stacktrace
In Lua 5.1 this will automatically convert all stack traces; for Lua 5.2 code you need to wrap your code with an xpcall as suggested in other answers.
A more proper solution would be to use xpcall around your whole code.
local function myerrhandler ( errobj )
print(debug.traceback())
for k,v in pairs(_G) do print("GLOBAL:" , k,v) end
return false
end
xpcall( function ()
--Your code here
end , myerrhandler )
Your error handler may be overwritten. If you're calling Lua from C, to always print the stack you can hook in to the luaG_errormsg function.
In lua, write :
local _HandlingError = 0
function _ErrorHandler ( errobj )
if( _HandlingError == 0 ) then
_HandlingError = 1
local errStr = tostring(errobj) or ""
if( type(errobj)=='table' ) then
errStr = "Table: {" .. table.concat(errobj, ',') .. "}"
end
print("Error: \"" .. errStr .. "\"")
--for k,v in pairs(_G) do print("GLOBAL:" , k,v) end
if( type(errobj)=='thread' ) then
print(debug.traceback(errobj))
else
print(debug.traceback('',2))
end
_HandlingError = 0
end
return false
end
Then in ldebug.c, add to luaG_errormsg after if(L->errfunc != 0)
else
{
lua_getfield(L, LUA_GLOBALSINDEX, "_ErrorHandler");
if (!lua_isfunction(L, -1)) {
lua_pop(L, 1);
}
else {
lua_pushvalue(L, 1);
lua_call(L, 2, 1);
lua_pop(L, 1);
}
}