Archive for the 'Professional' category

Lua function to traverse all files in a folder recursively

Jan 12 2012 Published by under Tips&Tricks

Here is a little function that uses Lua File System (lfs module) in order to traverse all the files in a folder and its sub folders (and their sub folders) recursively.

DIR_SEP="\\" --should be "/" for Unix platforms (Linux and Mac)
function browseFolder(root)
	for entity in lfs.dir(root) do
		if entity~="." and entity~=".." then
			local fullPath=root..DIR_SEP..entity
			--print("root: "..root..", entity: "..entity..", mode: "..(lfs.attributes(fullPath,"mode")or "-")..", full path: "..fullPath)
			local mode=lfs.attributes(fullPath,"mode")
			if mode=="file" then
				--this is where the processing happens. I print the name of the file and its path but it can be any code
				print(root.." > "..entity)
			elseif mode=="directory" then
				browseFolder(fullPath);
			end
		end
	end
end

--this is a sample call
browseFolder(".")

Comments are off for this post

Checking IP address format in Lua

Jan 09 2012 Published by under Tips&Tricks

Here is a little function that I developed to test if a string is a valid IPv4 address (that is 4 numbers between 0 to 255 separated with “.”)

---checks if a string represents an ip address
-- @return true or false
function isIpAddress(ip)
 if not ip then return false end
 local a,b,c,d=ip:match("^(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)$")
 a=tonumber(a)
 b=tonumber(b)
 c=tonumber(c)
 d=tonumber(d)
 if not a or not b or not c or not d then return false end
 if a<0 or 255<a then return false end
 if b<0 or 255<b then return false end
 if c<0 or 255<c then return false end
 if d<0 or 255<d then return false end
 return true
end

And here are some tests:

assert(isIpAddress("1.1.1.1")==true)
assert(isIpAddress("255.1.1.1")==true)
assert(isIpAddress("255.255.0.0")==true)
assert(isIpAddress("0.0.0.0")==true)
assert(isIpAddress("255.255.255.255")==true)
assert(isIpAddress("0.0.0.1")==true)
assert(isIpAddress("0.0.1.1")==true)
assert(isIpAddress("0.1.1.1")==true)
assert(isIpAddress("1.2.3.4")==true)
assert(isIpAddress(nil)==false)
assert(isIpAddress("")==false)
assert(isIpAddress("1")==false)
assert(isIpAddress("1.2")==false)
assert(isIpAddress("1.2.3")==false)
assert(isIpAddress("1.2.3.4.")==false)
assert(isIpAddress(".1.2.3.4")==false)
assert(isIpAddress("0")==false)
assert(isIpAddress("-1")==false)
assert(isIpAddress("256")==false)
assert(isIpAddress("-1.2.3.4")==false)
assert(isIpAddress("1.-2.3.4")==false)
assert(isIpAddress("1.2.-3.4")==false)
assert(isIpAddress("1.2.3.-4")==false)
assert(isIpAddress("256.2.3.4")==false)
assert(isIpAddress("1.256.3.4")==false)
assert(isIpAddress("1.2.256.4")==false)
assert(isIpAddress("1.2.3.256")==false)
assert(isIpAddress("256.256.256.256")==false)
assert(isIpAddress("1000.0.0.0")==false)
assert(isIpAddress("a.b.c.d")==false)
assert(isIpAddress("a.2.c.d")==false)
assert(isIpAddress("a.b.3.d")==false)
assert(isIpAddress("a.b.c.4")==false)

Comments are off for this post

What are all the valid subnet masks

Jan 09 2012 Published by under Tips&Tricks

Here are all the valid subnet masks for IPv4:

  1. 128.0.0.0
  2. 192.0.0.0
  3. 224.0.0.0
  4. 240.0.0.0
  5. 248.0.0.0
  6. 252.0.0.0
  7. 254.0.0.0
  8. 255.0.0.0
  9. 255.128.0.0
  10. 255.192.0.0
  11. 255.224.0.0
  12. 255.240.0.0
  13. 255.248.0.0
  14. 255.252.0.0
  15. 255.254.0.0
  16. 255.255.0.0
  17. 255.255.128.0
  18. 255.255.192.0
  19. 255.255.224.0
  20. 255.255.240.0
  21. 255.255.248.0
  22. 255.255.252.0
  23. 255.255.254.0
  24. 255.255.255.0
  25. 255.255.255.128
  26. 255.255.255.192
  27. 255.255.255.224
  28. 255.255.255.240
  29. 255.255.255.248
  30. 255.255.255.252
  31. 255.255.255.254

The following Lua script was used to calculate those values:

map={
  ["00000000"]="0",
  ["10000000"]="128",
  ["11000000"]="192",
  ["11100000"]="224",
  ["11110000"]="240",
  ["11111000"]="248",
  ["11111100"]="252",
  ["11111110"]="254",
  ["11111111"]="255"
}
for i=1,31 do
  s=string.rep("1",i)..string.rep("0",32-i)
  print(map[s:sub( 1, 8)].."."..map[s:sub( 9,16)].."."..map[s:sub(17,24)].."."..map[s:sub(25,32)])
end

Comments are off for this post

Setting up Tele2 Huawei e367 3G modem on Linux (Ubuntu 11.04)

Dec 31 2011 Published by under Tips&Tricks

I needed to connect my Tele2 usb modem to Ubuntu and here is a good solution.

It’s basically these lines that made it work:

$ cd /etc/usb_modeswitch.d
$ sudo tar xzf /usr/share/usb_modeswitch/configPack.tar.gz 12d1:1446
$ sudo sed -i -e 's/14ac"/14ac,1506"/' 12d1\:1446

Also it seems that the following command is required for it to work:

$ sudo modprobe usbserial vendor=0x12d1 product=0x1506

After that, you need to configure Ubuntu Network Connections (the little network icon on the top right of the screen near the speaker icon). Go to “Mobile Broadband” tab, click “Add”. Select “Sweden” as your country, “Tele2″ as your operator and “Mobile Bredband” as your data plan.
Then use the following configurations:

  • PIN1: ***** (your pin code)
  • connection type: NDIS
  • access point: mobileinternet.tele2.se
  • Phone number: *99#
  • Username and password: Not used (leave empty)
  • Password Authentication Protocol: CHAP (to be safe you can select all of them)
  • IP address: Dynamic
  • DNS address : Dynamic
  • WINS address: Dynamic

PS. The Linux version of the driver is really stable! I share the Internet using an Asus Eee Box and an access point to 4 other wireless devices at home. In Windows, the device used to get disconnected and sometimes it had to be removed from the USB port and inserted again (even when using the latest driver from Huawei). In Linux this hasn’t happened during the last week.

Comments are off for this post

Comment remover script for JavaScript, HTML, XML, CSS and Lua

Nov 28 2011 Published by under Tips&Tricks

The following script removes all comments (single line or multi line) from 5 types of files that I use mostly: JavaScript, HTML, XML, CSS and Lua.

formats={
	["js"]={
		name="JavaScript",
		single="//.-\n",
		multi="/%*.-%*/"
	},
	["xml"]={
		name="XML",
		single=nil,
		multi="<!--.--->"
	},
	["html"]={
		name="HTML",
		single=nil,
		multi="<!--.--->"
	},
	["css"]={
		name="CSS",
		single=nil,
		multi="/%*.-%*/"
	},
	["lua"]={
		name="Lua",
		single="--.-\n",
		multi="/%[%[.-%]%]/"
	},

}
---Gets a valid compilable javascript code and removes its comments
-- @note the javascript code should be ready to compile that is: there are no syntax
-- errors whatsoever. Otherwise the behavior of this function is unpredictable.
-- @param txt the compilable javascript code
-- @param patt the pattern table from format table. See how it's called from removeCommentsFile()
-- @return a text string the semantically behaves the same as the txt that was passed
-- to the function but doesn't have comments
function removeComments(txt,patt)
	--remove all multi-line comments
	if patt.multi then
		txt=txt:gsub(patt.multi,"\n")
	end
	--remove all single-line comments
	if patt.single then
		txt=txt:gsub(patt.single,"\n")
	end

	txt=txt:gsub("\n[%s]*","\n")  --remove all soaces at the start of lines
	txt=txt:gsub("[%s\n]*\n","\n")--remove all empty lines and all spaces at the end of lines
	txt=txt:gsub("^\n","")        --remove first empty new line
	txt=txt:gsub("\n$","")        --remove last empty new line
	return txt
end

---Opens a file and detects its extension before passing the contents to removeComments()
function removeCommentsFile(fileName)
	local f=io.open(fileName,"r")
	local txt=f:read("*a")
	local extension=fileName:match("%.(.-)$")
	if not extension then
		return nil,"Could not find extension for file '"..fileName.."'"
	end
	extension=extension:lower()
	if formats[extension] then
		print("Removing comments from '"..fileName.."' (a "..formats[extension].name.." file)")
		return removeComments(txt,formats[extension])
	else
		return nil,"This file is not recognized: '"..fileName.."'"
	end
end

for k,v in ipairs(arg) do
	print(removeCommentsFile(v))
end

Comments are off for this post

Lua function to remove JavaScript comments

Nov 28 2011 Published by under Tips&Tricks

JavaScript is an interpreted language. Therefore when the code is put in a web page, the client can easily see how it works. Commenting the code is a good coding practice to improve readability but we don’t want to waste user bandwidth with comments. Before releasing JavaScript codes it’s good to remove the comments from them. Here is a little Lua script that does the job.

 

--- Gets a valid compilable javascript code and removes its comments
-- @note the javascript code should be ready to compile that is: there are no syntax
-- errors whatsoever. Otherwise the behavior of this function is unpredictable.
-- @param txt the compilable javascript code
-- @return a text string the semantically behaves the same as the txt that was passed
-- to the function but doesn't have comments
function removeCommentsJS(txt)
	txt=txt:gsub("/%*.-%*/","\n")   --remove all multi-line comments
	txt=txt:gsub("//.-\n","\n")     --remove all single-line comments
	txt=txt:gsub("\n[%s\n]*\n","\n")--remove all empty lines
	txt=txt:gsub("^\n","")          --remove first empty new line
	txt=txt:gsub("\n$","")          --remove last empty new line
	return txt
end

And here is a test script that will not print any error if finished successfully:

--removeCommentsJS() test
txt={
[[
code;
]],
[[code;
]],
[[code;]]
,
[[/**
comments
*/
code;
]],
[[//comments
code;
]],
[[code;//comments
]],
[[//comments
code;
//comments
]],
[[//comments

code;

//comments
//comments
//comments
]],
[[//comments

/*comments*/

/** comments */

/**
* comments
*/

/**
* comments
* comments
* comments
* comments
*/

code;

//comments
//comments
//comments
]]
}
for _,t in ipairs(txt) do
    local uncommentedJS=removeCommentsJS(t)
    if uncommentedJS~="code;" then
        print("Test failed for :\n'"..t.."'! Return value is:\n'"..uncommentedJS.."'")
    end
end

Comments are off for this post

The Philosophy of “While”!

Oct 26 2011 Published by under Quotes (Pro)

Fredrik M. says:

while(1); //doesn't do anything
while(0); //doesn't even do something!

Comments are off for this post

Siri vs. Google voice

Oct 17 2011 Published by under Quotes (Pro)

This is a good article from TechCrunch which compares the two. A funny quote:

Put another way, Google’s voice search and Siri may look comparable on paper. But in reality, one is something best used by a robot, the other is something best used by a human. And robots don’t buy phones — at least not yet.

Comments are off for this post

Lua string sanitization

Oct 07 2011 Published by under Tips&Tricks

I needed to write some string as Lua code. In this case, if double quote (“) appears in the string, it may end the string literal in the generated source code. Also all the escape characters like \n if are written as \\n in the string may cause trouble. I thought it’s better to create a sanitization function just like HTML sanitization function and here it is:

Update: apparently Lua takes care of multiline strings before writing to file! it adds “..\n at the end of each line (including the quote) and ” at the beginning of the next line.

---replaces quotation marks (") with (\") so that the string can be saved as a Lua string in code files
-- NOTE: str should not be nil
function luastrsanitize(str)
	str=str:gsub('\\','\\\\')  --replace \ with \\
	str=str:gsub('"','\\"')    --replace " with \"
	return '"'..str..'"'
end

--luastrsanitize() test
print(repquote(""))
print(repquote("hi\""))
print(repquote("hi\nhow are you?"))
print(repquote('he said: "hi"'))
print(repquote("one tab\\tdistance"))
print(repquote([=[hello "kitty"!]=]))
print(repquote('"'))

Comments are off for this post

REST tutorial

Oct 04 2011 Published by under Links

This website has a great and simple tutorial about REST: http://rest.elkstein.org/

The main advantage of ROA is ease of implementation, agility of the design, and the lightweight approach to things. In a way, SOA and SOAP is for people in business suits; that’s what you’ll find used in the banking and finance industries. Conversely, somebody that needs something up-and-running quickly, with good performance and low overhead, is often better off using REST and ROA. (src)

Here are some more links about REST from this website.

Comments are off for this post

Older posts »