Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Thursday, April 02, 2009

Syntax Highlighting for Sahi Code

I have added syntax highlighting to my blogs now. Used Alex Gorbatchev's SyntaxHighlighter 2.0 which is awesome. I added a Sahi brush to SyntaxHighlighter so that keywords in Sahi would also be highlighted.

This is what shBrushSahi.js looks like:

SyntaxHighlighter.brushes.SahiScript = function()
{
var keywords = 'abstract boolean break byte case catch char class const continue debugger ' +
'default delete do double else enum export extends false final finally float ' +
'for function goto if implements import in instanceof int interface long native ' +
'new null package private protected public return short static super switch ' +
'synchronized this throw throws transient true try typeof var void volatile while with';

var schedulerFns = '_alert _assertEqual _assertNotEqual _assertNotNull _assertNull _assertTrue _assert _assertNotTrue _assertFalse _assertExists _assertNotExists _callServer _click _clickLinkByAccessor _dragDrop _resetSavedRandom _setSelected _setValue _simulateEvent _call _eval _setGlobal _wait _popup _highlight _log _navigateTo _callServer _doubleClick _rightClick _addMock _removeMock _expectConfirm _setFile _expectPrompt _debug _debugToErr _debugToFile _mouseOver _keyPress _focus _keyDown _keyUp _mockImage _execute _assertContainsText _enableKeepAlive _disableKeepAlive _dragDropXY _deleteCookie _createCookie _clearPrintCalled _saveDownloadedAs _clearLastDownloadedFileName _rteWrite';

var browserFns = '_accessor _button _check _checkbox _image _imageSubmitButton _link _password _radio _select _submit _textarea _textbox _event _getGlobal _random _savedRandom _cell _table _containsText _containsHTML _byId _row _getText _getCellText _div _span _spandiv _option _lastConfirm _reset _file _lastPrompt _lastAlert _get _style _byText _cookie _position _print _printCalled _label _lastDownloadedFileName _rteHTML _rteText _re _prompt _getCellText _getSelectedText _scriptName _isVisible _listItem _parentNode _parentCell _parentRow _parentTable _in';

var otherFns = '_getDB _readFile _logException _logExceptionAsFailure _stopOnError _continueOnError _include';

schedulerFns += (' ' + otherFns);


this.regexList = [
{ regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
{ regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
{ regex: /\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
{ regex: new RegExp(this.getKeywords(schedulerFns), 'gm'), css: 'color4' }, // operators and such
{ regex: new RegExp(this.getKeywords(browserFns), 'gm'), css: 'color5' }, // operators and such
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keywords
];

this.forHtmlScript(SyntaxHighlighter.regexLib.scriptScriptTags);
};

SyntaxHighlighter.brushes.SahiScript.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.SahiScript.aliases = ['sahi', 'sahiscript'];


And this is what I added to my blogger template:


<script src='http://sahi.co.in/static/syntaxhighlighter/scripts/shCore.js' type='text/javascript'/>
<script src='http://sahi.co.in/static/syntaxhighlighter/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='http://sahi.co.in/static/syntaxhighlighter/scripts/shBrushSahi.js' type='text/javascript'/>
<link href='http://sahi.co.in/static/syntaxhighlighter/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://sahi.co.in/static/syntaxhighlighter/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<style>
.syntaxhighlighter .color4, .syntaxhighlighter .color4 a{color: #000A7F !important;}
.syntaxhighlighter .color5,.syntaxhighlighter .color5 a{color: brown !important;}
</style>
<script type='text/javascript'>
SyntaxHighlighter.config.clipboardSwf = 'http://sahi.co.in/static/syntaxhighlighter/scripts/clipboard.swf';
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();
</script>


Note that, in blogger, <br> tags will be visible in the code in place of new lines if you do not add
SyntaxHighlighter.config.bloggerMode = true;


So now Sahi scripts on the blog will look like this:


function search(){
_setValue(_textbox("q"), "sahi");
_click(_submit("Google Search"));
_assertExists(_link("Sahi"));
}
function goToForums(){
_click(_link("Sahi"));
_click(_link("Forums"));
}
function logout(){
if (_condition(_link("Logout"))){
_click(_link("Logout"));
}
}
function login($username, $password){
_click(_link("Login"));
_setValue(_textbox("req_username"), $username);
_setValue(_password("req_password"), $password);
_click(_submit("Login"));
_assertExists(_listItem("Logged in as "+$username));
}

search();
goToForums();
logout();
login("sahitest" "khuljasimsim");

Tuesday, August 12, 2008

Viewing cookies in IE

There are times during development when you wish to see the cookies of a particular site, but do not know how to view them. You can use this simple solution to view cookies.

Drag this link to the Bookmarks toolbar on firefox. (Enable the toolbar by: View -> Toolbars -> Bookmarks Toolbar)
Show Cookies

On IE, right click on link, "Add to Favorites", Create In -> "Links". (Enable toolbar via Tools -> Toolbars -> Links)

Once you have this link on the toolbar, you can navigate to any site and click it to see the cookies.

Of course there are plenty of cookie viewing techniques and tools around, but this is a very easy and handy way of checking cookies quickly.

The html of the link above looks like this:
<a href="javascript:alert(document.cookie)">Show Cookies</a>

Bookmarlets like these can be really useful at times. For example in my newly launched http://www.househunt.in website, I have a bookmarklet which helps me gather relevant links from a builder's site. All I need to do is navigate to the builder's website, click a bookmarklet on my browser and it injects javascript into the page to collect all relevant links and display a popup page. I then just add some more information and submit. This ease has helped more than 400 projects in Pune to be added within a short span of time.

Tuesday, April 15, 2008

Unicode encode decode error in python email

Been bothered with these on and off errors in our application while sending email via python:
File "/usr/lib/python2.4/email/Generator.py", line 182, in handletext self._fp.write(payload)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2014' in position 4986: ordinal not in range(128)

The reason is that Python's email module needs some information about charset used when a MIMEText object is created.

Here is a link which explians how to solve this:
http://mg.pov.lt/blog/unicode-emails-in-python


Links to understand unicode in Python:

http://effbot.org/zone/unicode-objects.htm
http://www.amk.ca/python/howto/unicode

Tuesday, December 11, 2007

java -cp does not work?

Was trying to get Sahi's batch and shell scripts to work properly since I get a lot of queries regarding database drivers not being found instpite of adding to the classpath.

The problem is this. I need to add a mysql driver to Sahi's classpath so that the scripts can access the driver to do some data driven testing.

So I had to add the mysql driver to this:

java -jar ../lib/sahi.jar

Trivially, I added a -cp option so the command looks like this:

java -cp ../extlib/mysql-connector-java-5.0.4-bin.jar -jar ../lib/sahi.jar

But this does NOT work. Why? Because an executable jar should have its classpath in its manifest file and not outside.

The way to solve this is to use:

java -cp ../extlib/mysql-connector-java-5.0.4-bin.jar;../lib/sahi.jar net.sf.sahi.Proxy

So I made these changes on my windows machine, and it worked. Then logged on to my newly installed ubuntu to check if the shell script works with the same changes.

Made the necessary semi-colon to colon conversion in the classpath, so it looks like this.

java -cp ../extlib/mysql-connector-java-5.0.4-bin.jar:../lib/sahi.jar net.sf.sahi.Proxy

The sahi.sh file has a few other lines too.

When I ran sahi.sh, it gave me a NoClassDefFound error for net/sf/sahi/Proxy! After hunting around quite a bit on the net to see if there was such a problem on linux, I realized that nobody on the forums seems to understand the problem even when somebody reported it.

Eventually I realized that since I had edited the file in windows, it was adding ^M characters at the newlines which was not being recognized by the shell. So I used another editor and got rid of them by deleting and reentering the newlines. (I could also have used dos2unix, but did not have it installed on my machine)

I also realized why the people in the forums did not understand the problem. Most of the replies were from people using linux all the time and the question posters would have mostly been using windows but since the problem was on a linux machine would have posted the question on linux forums!

Anyway, now things work properly :)

Tuesday, September 18, 2007

0=="" is true

Debugging something on Sahi, came across this interesting equality in javascript:

0 == "" is true!

So are:

1 == "1" etc.

An easy way to test these out (and any other single line javascript) is to type

javascript:0==""

on the browser url navigation bar.
Yes, it works on IE and firefox.

Monday, November 27, 2006

Ruby mocking - Using flexstub

Ruby proves to be as sweet as most people have claimed it to be.

Pick testing and and you hit flexmock and flexstub.

So how do you use them? Here goes:

You have

class CA{
def method_1
do_some_processing
if condition method_2
else method_3
end

def method_2
do_some_slow_processing_worth_mocking_out
end

def method_3
do_some_more_slow_processing_worth_mocking_out
end

}

If you want to test method_1's conditonal logic, with method_2 and method_3 stubbed out, here is how you do it with flexstub:


require 'flexmock'

class MyTest< Test::Unit::TestCase
include FlexMock::TestCase
def test_method_1
ca = CA.new
# do something to make the condition be true
# stub some methods of the instance
stub = flexstub(ca)
stub.should_receive(:method_2).once
stub.should_receive(:method_3).never
ca.method_1
# Note: method_1 is invoked on ca.
# stub.method_1 will fail!
end
end


So when would you use flexmock?
If you wish to mock all the methods being called on an object, you may use a flexmock.
A flexmock is an object which will just receive the methods you set expectations for, using should_receive.
If you wish to mock only one of the methods of an object but the other methods need to be invoked with the real functionality,
use flexstub to mock only that particular method.

As you see, method_1 is invoked properly, but method_2 and method_3 are stubbed out.

One remarkable thing about this is mocking out an object's new method.

flexstub(Customer).should_receive(:new)
.and_return(mock_customer)

Anywhere Customer.new is called inside any class during your test, it will return a mock_customer.
This is quite powerful, because we no longer need to use dependancy injection for just test purposes.

Wednesday, March 29, 2006

Testing SMTP settings

Came upon this link for testing SMTP server using telnet.
http://www.petri.co.il/test_smtp_service.htm.
Was very useful in verifying whether the settings are right before deploying our j2ee app on a remote server.
Also realized that the WebLogic domain needs a restart if settings in the JNDI Mail Session are changed.

Tuesday, October 18, 2005

If double clicking on a folder on the right hand pane of explorer opens a new window all the time, here is the fix. I know this works for XP.
Open explorer
Go to Tools > Folder Options... > File Types (tab)
Select "File Folder" and click on "Advanced" button.
Add a new junk entry by clicking "New".
Enter values "To DOS" and "cmd.exe" in the two text boxes and press "OK".
Then select "To DOS" and click "Set Default" (This is very important)
Click "OK", "OK".
Close explorer.
Open regedit (Start > run > regedit > OK)
Search for "To DOS".
Delete this node from the "shell" folder (HKEY_CLASSES_ROOT\Folder\shell).
Close regedit and restart explorer and the problem should be fixed.