Saturday, August 8, 2009

If you want to put your code in lib/ but you have your features and steps under features/ .. create a file called features/support/env.rb with the following (cucumber will load and run it)


:.unshift File.dirname(__FILE__) + "/../../lib"
some xml

SICP #1

Lecture 1

fixed point - finding the fixed point - take a guess, then apply the function
successively til "it doesnt change much" - how does this work? what does it mean?

eg. use fixed point method to find sqroot - find fixed point of average(x, y/x)


higher-order procedures take as inputs and outputs, procedures

generic operations - eg the many interpretations of '+'

2 ways of dealing with large scale systems
- oo
- operations on aggregates - "streams" eg. a signal processing engineer designing a large electrical system

another way to handle complexity - design a new language that highlights salient things and hides irrelevant detail

"meta-linguistic abstraction"

Three things about a language:
- primitive operations
- means of combination
- means of abstraction - how to make larger order primitives

lisp
definitions are just expressions

lambda - "make a procedure"

key thing about lisp - there is no arbitrary distinction between things that are primitives and things that are defined

case analyses

(DEFINE (ABS X) (COND ((< X 0) (- X)))

lisp - you can define all other constructs for it


(DEFINE (TRY GUESS X)
(IF (GOOD-ENOUGH? GUESS X)
GUESS
(TRY (IMPROVE GUESS X) X))))


recusion - go on ininitely - fix point?

summary

what we are doing is "expressing imperative knowledge"

Wednesday, June 24, 2009

Rails Webapp stuff

Configuration: db
Db migrations
Active record
Validations
Controller, routing
View, layouts
scaffold now generates useful code
Helper functions in views
Sessions, storing sessions
Error reporting and logging - the "flash"

Tuesday, June 2, 2009

Ivy

all you need if Ivy is properly installed is to define an XML namespace in your Ant file (xmlns:ivy="antlib:org.apache.ivy.ant"). Then all the Ivy ant tasks will be available in this namespace






http://ant.apache.org/ivy/history/2.1.0-rc1/tutorial/start.html
Without any settings, Ivy retrieves files from the maven 2 repository. That's what happened here.
The resolve task has found the commons-lang and commons-cli modules in the maven 2 repository, identified that commons-cli depends on commons-logging and so resolved it as a transitive dependency. Then Ivy has downloaded all corresponding artifacts in its cache (by default in your user home, in a .ivy2/cache directory). Finally, the retrieve task copies the resolved jars from the ivy cache to the default library directory of the project: the lib dir (you can change this easily by setting the pattern attribute on the retrieve task).

Configurations are very important concept in ivy. They allow you to group artifacts by meaning.
When you write ivy file for projects that are supposed to be reused, use configurations to allow people to get only they what they need without having to specify it by hand using artifact tag in dependency section.

Monday, June 1, 2009

Agile Rails Development Book

Ajax
use form_remote_tag helper instead of button_to
use respond_to instead of redirect_to in controller and create a rjs file - which is some ruby from which javascript is generated. The js is then interpreted on the ajax response.



Partial templates - you can pass it a collection and it will render it once for every item in the collection.
Partials should be in the same directory as the template that calls it. Name should start with an underscore.

Partial has a default variable with same name as the filename of the partial, which is set to each item of the collection. Strange.



Every controller has a logger attribute

A flash is a bucket
(actually closer to a Hash) in which you can store stuff as you process a request.
The contents of the flash are available to the next request in this session
before being deleted automatically.

This tells us that it’s generally a really bad idea to store application-level
objects in session data. Any change to the application could potentially require
us to lose existing sessions when we next update the application in production.
Instead, the recommended practice is to store only simple data in the session:
strings, numbers, and so on. Keep your application objects in the database,
and then reference them using their primary keys from the session data. If we
were rolling the Depot application into production, we’d be wise to make the
Cart class an Active Record object and store cart data in the database.5 The
session would then store the cart object’s id.


makes session available to u in controller with session map

the button_to method also links a
view back to the application, but it does so by generating an HTML form that
contains just a single button. When the user clicks the button, an HTTP POST
request is generated. And a POST request is just the ticket when we want to
do something like add an item to a cart.


<%= number_to_currency(product.price) %> 


Use the following to force http delete
<%= link_to 'Destroy', product, :confirm => 'Are you sure?', :method => :delete %>


Double quotes with %{ }

Use decimal instead of float for numbers

rake db:migrate [VERSION=0]
rake db:sessions:clear
rake db:migrate:redo

Handle escape characters:
Email: <%= h("Ann & Bill frazers@isp.email") %> 


Something about suppressing blank lines in the script output

ERbisafilterthat takesan.erbfileandoutputsatransformedversion. The
outputfileisoftenHTMLinRails, but it canbeanything.

Create view files that have same name as action files

After installing a new version of Rails, you might also want to update the files
that Rails initially added to your applications (the JavaScript libraries it uses
for Ajax support, various scripts, and so on). You can do this by running the
following command in your application’s top-level directory:
rubys> rake rails:update


What are test fixtures?

Ways Rails beats EJB:
  • automatically adds class methods for find, update, delete etc to model objects

Saturday, May 30, 2009

Open a file and it closes automatically


File.open("testfile", "r") do |file|
# ... process the file
end

Friday, May 29, 2009

RSpec book

Test Behaviour Not Internal Structure

Unit Tests can be brittle in that they use internals of an object (eg. check register() method works by checking something was added to an internal array). If we change internals, test will fail even though behaviour hasn't changed. How can we avoid tying our unit tests to internals?

Design the API by using it

When writing code, call methods you wish you had - then you can implement them. Better than designing the API on its own.

Wednesday, May 13, 2009

Supervising Controller

http://www.martinfowler.com/eaaDev/SupervisingPresenter.html

Pull complex view logic out into the controller to make it testable. In the examples, the controller listens to widget events, and does stuff with the input. Controller will update model, however can leave it up to the view to update model for basic stuff (which it might do using data binding).

Sunday, May 3, 2009

TCP Tunnel Gui

http://jcbserver.uwaterloo.ca/cs436/software/tgui/tcpTunnelGUI.shtml

java -jar tunnel.jar 9999 jcbServer.uwaterloo.ca 80

Tuesday, April 28, 2009

Weird Firefox/Eclipse mouse problems

Had problems with mouse focus events in Eclipse and Firefox, only a restart would fix this. Tried different mouse. It also happened on different computers. Finally found a weird fix - click the scroll button of the mouse when it happens:

http://support.mozilla.com/tiki-view_forum_thread.php?locale=mn&forumId=1&comments_threshold=0&comments_parentId=86324&comments_offset=40&comments_per_page=20&thread_style=commentStyle_plain

Thursday, April 23, 2009

What sucks about the Geo module

GeoDataSets - ok they are useful because they store the busunitguid and other stuff. But there should be only one type of them - not different types. The different types just made it painful and added no benefit.

Also, they should have been able to be referenced by the entityTypeGuid of the domain object they were associated with, so you can easily pass in the geodataset when creating a geoobject, without having to first lookup the geodataset on something.

Wednesday, April 22, 2009

Don't have a create operation inside failed lookup


GeoTrackedEntity te = null;
try {
te = geoTrackedEntityApi.findTrackedEntity(vehicle.getGuid(), false);
} catch (UnknownFeatureException e2) {
te = addTrackedEntity(vehicle, buGuid);
}


This code is awful because it makes it hard to know when something is created. Plus you would have to have this kind of thing everywhere a find was performed.

This is truly awful. The above method addTrackedEntity then repeats this anti-pattern to add a dataset (which is required if you need to add a tracked entity).


GeoDataSet ds;
try {
ds = geoDatasetApi.findDataSetByBusUnitAndName(buGuid,
vehicle.getVehicleType().getName());

} catch (UnknownDataSetException e1) {
ds =addTrackedEntityDataSet(vehicle.getVehicleType().getName(),
vehicle.getVehicleType().getGuid(), buGuid);
}

APIs - parameter objects?

public void associateTrackedEntityWithIsUnique(GeoTrackedEntity trackedEntity,
GeoDevice geoDevice,
Date startDate,
boolean isUniqueTypedAssociated)
throws UnknownFeatureException;

The purpose of the above method is to associate the trackedEntity object with the geoDevice object. It would have been neater to specify these objects by their unique identifer, rather than requiring the whole object to be passed in. The latter causes code like this:


GeoDevice geoDevice = getGeoDevice(drvDriver.getBusUnitGuid(),deviceId);
GeoTrackedEntity te = getGeoTrackedEntity(drvDriver);
geoTrackedEntityApi.associateTrackedEntityWithIsUnique(te,gd,d,true);


We need to look up the two objects first, which is unnecessary since we already have the unique identifiers.

Another ugly code pattern is the fact that SS has created helper methods around the core api methods because they throw annoying exceptions. These exceptions should be runtime if there is nothing the coder can do about it.


private GeoTrackedEntity getGeoTrackedEntity(DrvDriver driver)
{
logger.debug("");

GeoTrackedEntity te;
try {
te = geoTrackedEntityApi.findTrackedEntity(driver.getGuid(), false);
} catch (UnknownFeatureException e2) {
te = addTrackedEntity(driver);
}

return te;
}

Tuesday, March 31, 2009

Caching of collections isn't working how I would expect. I had a TaskTypeEntity which has an AttrTypeEntity which in turn has AttrDef. I placed cache markers on all entities and on the collections of AttrTypeEntity. When I changed an AttrDef, the cached copy in the AttrTypeEntity collection wasn't updated.

Need to find out how the cache works exactly.

Tuesday, March 24, 2009

I wanted to write a servlet filter that would catch errors and send an event. You can't catch exceptions for the GWT services that extend RemoteServiceServlet as it handles the errors itself.

Monday, March 23, 2009

Viewing Deadlocks in Sql Server

Go to Sql Profiler
New Trace
Events Selection -> Locks -> Choose Deadlock graph and DeadLock chain
Run
Search for word deadlock

Thursday, March 19, 2009

Vertical Panel "spreads things out"

If I add things to a Vertical Panel, like 2 labels, they end up not exactly one after the other - they are spread out to take up the whole space - how can I change that?

Ans - you can work around this problem by setting cell heights of children widgets to "1%"

Wednesday, March 18, 2009

Change default jdk platform in NetBeans

Edit the property netbeans_jdkhome in netbeans\etc\netbeans.conf

Thursday, March 12, 2009

SNP Load Testing Adventures

Ran 20 threads all at the same time with default cache settings - takes 65 secs.

When I changed entity cache to use OPTIMISTIC locking (it uses pessimistic by default) it seemed to make a difference when I hot-changed the cache file, but not from after a restart. After a restart there were lots of exceptions like


2009-03-12 18:43:10,875 WARN [org.jboss.cache.interceptors.TxInterceptor] Rolling back, exception encountered


Caused by: org.jboss.cache.optimistic.DataVersioningException: Tx attempted to create /sa_XmTaskMgrInternal-ejb_jar,Xmotion/au/com/xmotion/xmattribute/ejb/orm/AttrValue/au.com.xmotion.xmattribute.ejb.orm.AttrValue#87616 anew. It has already been created since this tx started by another (possibly remote) tx.


After restart optimistic cache - 20 simultaneous requests - 60sec
After restart optimistic cache - 20 simultaneous requests with 20sec rampup period - 16sec

After restart pessimistic cache - 20 simultaneous requests - 45sec
After restart pessimistic cache - 20 simultaneous requests with 20sec rampup period - 16sec

Monday, March 9, 2009

JAXB printing xs:date as xs:datetime

For xs:date element, the automatic xml it created for a java date object came out as a datetime element. I tried to use custom binding but this didn't work. Hack I found around it was

tripDate.clear();
tripDate.setDay(cloneDate.getDay());
tripDate.setMonth(cloneDate.getMonth());
tripDate.setYear(cloneDate.getYear());
tripType.setTripDate(tripDate);

It then printed it out correctly

Monday, March 2, 2009

Properties in Python

Can set a property like this

class Group(db.Model):
name = db.StringProperty()
description = db.TextProperty()

@property
def members(self):
return Contact.gql("WHERE groups = :1", self.key())

What is that ampersand notation?

Wednesday, February 25, 2009

Parameters in python

http://wiki.futuretoby.com/Parameter_List_Chaining_in_Python

Sunday, February 22, 2009

JBoss Cache

JBoss 4.2.3 includes JBoss Cache 1.4.7

Guide to JBoss Cache
http://galder.zamarreno.com/wp-content/uploads/2008/09/hibernate-jbosscache-guide.pdf

http://www.infoq.com/news/2008/06/jboss-cache-interview

http://www.jboss.org/file-access/default/members/jbosscache/freezone/docs/2.1.1.GA/userguide_en/html/transactions.html#d0e3653

Sunday, February 15, 2009

Good T-SQL tutorial

For those of you who would like to know T-SQL

http://www.databasejournal.com/features/mssql/article.php/3087431/T-SQL-Programming-Part-1---Defining-Variables-and-IFELSE-logic.htm

An example T-SQL script


declare @jobId int

declare JobList cursor for select id from tsktask where fkparenttaskid is not null


OPEN JobList
FETCH NEXT FROM JobList INTO @jobId

WHILE @@FETCH_STATUS = 0
BEGIN

declare @parentTaskId int
SET @parentTaskId = (select fkParentTaskId from TskTask where id = @jobId)

declare @runNo varchar(25)
SET @runNo = (select identifier from tsktask where id = @parentTaskId)

update tsktask
set identifier = @runNo
where id = @jobId


FETCH NEXT FROM JobList INTO @jobId
END

CLOSE JobList
DEALLOCATE JobList

In Junit you can group your tests together into a suite, so they can be run altogether. This is useful for running all your module tests in your IDE in the one go, to get a nice overview.

In Junit4 you create a test suite by creating and running a class like example below:



@RunWith(Suite.class)
@SuiteClasses({
ConfigModuleMgmtApiTest.class,
ConfigMgmtApiTest.class,
ConfigHelperTest.class,
DataTypeHelperTest.class
})
public class ConfigTestSuite {

}

Sunday, February 8, 2009

Unable to install Terminal Services ActiveX Client

Trying to login via the POTA portal with IE7. When trying to get a web RDP session to one of the servers, it prompted me to Install the add on "Terminal Services ActiveX Client". I would click "Run ActiveX Control" and then Run when it popped up, but this would just do nothing.

The fix was:

- In IE go to Tools -> Internet Options -> Security (2nd tab) -> Trusted sites.
- Click Sites button and add your Terminal Server's FQDN, or IP. Uncheck "Require server verification (https:) for all sites in this zone" if your server doesn't use https. Click Close.
- Click on the Custom level... button about 1/3rd up from the bottom of the Security Window and scroll down to "Download unsigned ActiveX controls" and change the radio button from Disable to Prompt.
- Click OK and you should be set.

From
http://msmvps.com/blogs/steveb/archive/2007/07/30/blocked-in-ie7-from-connecting-to-your-desktop-in-remote-web-workplace.aspx

Saturday, February 7, 2009

Crazy javascript

What is that InstallFunction doing?
 
function doAdd() {
server
.Add($('num1').value, $('num2').value, onAddSuccess);
}

function InstallFunction(obj, name) {
   obj[name] = function() { Request(name, arguments); }
}

var server = {};
InstallFunction(server, 'Add');


Where Request is a method that encapsulates and simplifies an AJAX call

Friday, February 6, 2009

Things I like about Django Templates

If you use variables, values are automatically escaped.

Python packages

We tried to create packages for our controllers and there is code like below. But I don't want to have to write an import for every class I use, and I don't want to have to put all my classes in one file. I want it to be like Java - you can import a package (a directory) and you get access to all the classes within it.


from controllers.main_page import *
from controllers.book_owning_create import *
from controllers.book_yearning_create import *

application = webapp.WSGIApplication([
('/', MainPage),
('/bookowning/create', BookOwningCreate),
('/bookyearning/create', BookYearningCreate)


What I want to do is


from controllers import *

application = webapp.WSGIApplication([
('/', MainPage),
('/bookowning/create', BookOwningCreate),
('/bookyearning/create', BookYearningCreate)



It seems there is no really easy way to do it (that doesn't involve more typing). Also it seems to general consensus is to group classes in a module (ie. file).

The way I could do it would be to import all those classes in the __init__.py file of the controllers package. Like such:

(in __init__.py)

from book_owning_create import BookOwningCreate
from book_yearning_create import BookYearningCreate

Wednesday, February 4, 2009

Using SUPPORTS transaction attribute doesn't work when a transaction has become inactive

In our message receivers, we are sending an event after an exception has occured.

In our receiver method:

h.handle(message);
} catch (Throwable e) {
logger.error("Error in handling message", ExceptionUtils.getRootCause(e));
MessageProcessingErrorEvent mpe = new MessageProcessingErrorEvent(userManagement.getUserBusUnitGuid(),
e);
mpe.send();
throw new XmRuntimeException(e.toString(),e);
}


The sending of the event fails because we look up the user's busUnitGuid and this requires a transaction. The receiver method is being run in a transaction itself.

I thought one solution to this problem would be to put SUPPORTS transaction attribute on the getUserBusUnitGuid() method. The SUPPORTS attribute says that it will go under a transaction if one is present, otherwise it will run without a transaction.

It didn't fix the problem though, it was still saying that the transaction was inactive. Probably JBoss realised there was a transaction attached, so tried to use it, but then discovered it was inactive.

Monday, February 2, 2009

Hibernate Classpath problems in Eclipse

Getting NoSuchMethodException when trying to run XmLocationInternal test in Eclipse - something about ClassValiditor - I think there was a clashing jar in my JBoss 4.2.3 Client library - after positioning this library after the JBoss 4.2.3 library in my classpath, it worked again.

Wednesday, January 21, 2009

Creating Unit Tests in Eclipse

In eclipse, with Designer, you can create a unit test with New -> Other -> Designer -> GWT -> JUnit Test Case

Choose the class you want to test.

This will create a source directory called src-test, the test case which extends GWTTestCase? , and it willl automatically add the module name for you.

Add the jar gwt-dev-windows.jar in the GWT distro to your classpath.

To run from within eclipse, you can just choose "Run as GWT Junit Test"

To run from ant, make sure the source and test source directories are on the classpath.

Example ant file:

  































how to setup your run configuration to run your GWT app under eclipse.

Assuming you have tried to run your GWT app and failed...

Open Run Dialog and locate your app run config. Copy the following into the VM arguments field in the Arguments tab

-Xmx512m
-Djava.naming.factory.initial=org.jboss.security.jndi.JndiLoginInitialContextFactory
-Djava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
-Djava.naming.security.principal=admin
-Djava.naming.security.credentials=admin
-Djava.naming.provider.url=localhost:1099

Copy the attached jndi.properties file into a folder called conf and add that folder to the project classpath (I do this by adding it as a src folder).

Add Jboss Client and Jboss libraries to your project cllasspath (you need jboss client jars as well as server jars).

Get rid of Log 4 J library if you have it on classpath (when we migrated to Jboss 4.2.3, I started getting weird errors about TRACE field not being available - probably jboss uses a newer log4j version that what is in our libs).

Saturday, January 17, 2009

Dual Booting, MBR and Grub

I had Linux and Solaris installed and had an empty partition I wanted to install Windows on. When installing Windows, I was able to choose the correct partition and format it, however then it something about Windows needing the active partition to be set. This is a dos term and meaning is bootable partition. Windows apparently overwrites the Master Boot Record (which is

master boot record (MBR), or partition sector, is the 512-byte boot sector that is the first sector ("LBA Sector 0") of a partitioned data storage device such as a hard disk.

There can however be a boot sector for each partition.

BIOS executes code in the MBR which could be the code that bootstraps windows (called a chain loader ) or it can be code that can load and run Grub, which can bootstrap any OS. Info on how Grub works:

http://www.redhat.com/docs/manuals/linux/RHL-7.2-Manual/ref-guide/ch-grub.html

Tuesday, January 6, 2009

GWT Exceptions

You need to declare RuntimeExceptions as throwable from GWT servlet if you want to be able to catch it in the javascript. Otherwise you will just get a StatusCodeRPC exception or whatever.

Saturday, January 3, 2009

change default python version

Doesn't sound very official, but apparently you change the /usr/bin/python symlink to point to /usr/bin/python2.5 and then change instances of python2.5 in /usr/share/python/debian_defaults

Static vs Dynamic Libraries

I always wanted to understand the mechanism by which your C program calls library code at runtime.

From http://stackoverflow.com/questions/311882/what-do-statically-linked-and-dynamically-linked-mean

When you compile some C code (for instance), it is translated to machine language. Just a sequence of bytes which when run causes the processor to add, subtract, compare, "goto", read memory, write memory, that sort of thing. This stuff is stored in object (.o) files.

Now, a long time ago, computer scientists invented this "subroutine" thing. Execute-this-chunk-of-code-and-return-here. It wasn't too long before they realised that the most useful subroutines could be stored in a special place and used by any program that needed them.

Now in the early days programmers would have to punch in the memory address that these subroutines were located at. Something like CALL 0x5A62. This was tedious and problematic should those memory addresses ever need to be changed.

So, the process was automated. You write a program that calls printf(), and the compiler doesn't know the memory address of printf. So the compiler just writes CALL 0x0000, and adds a note to the object file saying "must replace this 0x0000 with the memory location of printf".

Static linkage means that the linker program (the GNU one is called ld) adds printf's machine code directly to your executable file, and changes the 0x0000 to the address of printf. This happens when your executable is created.

Dynamic linkage means that the above step doesn't happen. The executable file still has a note that says "must replace 0x000 with the memory location of printf". The operating system's loader needs to find the printf code, load it into memory, and correct the CALL address, each time the program is run.

It's common for programs to call some functions which will be statically linked (standard library functions like printf are usually statically linked) and other functions which are dynamically linked. The static ones "become part" of the executable and the dynamic ones "join in" when the executable is run.


Also good:
http://www.learncpp.com/cpp-tutorial/a1-static-and-dynamic-libraries/