Friday, March 4, 2011

How to test fluent-NHibernate's PersistenceSpecification.VerifyTheMappings with lists and relational objects?

How would you test this scenario?

I've just started looking into NHibernate and having my first bash at TDD. So far I've really enjoyed it and have been using fluent-Nhibernate for my mapping of the classes.

However I seem to be hitting a dead end when it comes to using the VerifyTheMappings method on PersistenceSpecification.

Essentially I have two classes, Recipient and RecipientList. The RecipientList class has a mapping to the Recipient with a fluent "HasMany" relationship:

public class RecipientListMap : ClassMap<RecipientList>
{

    public RecipientListMap()
    {
        Id(x => x.ID);
        Map(x => x.ApplicationID);
        Map(x => x.Name);
        Map(x => x.IsDeleted);
        HasMany<Recipient>(x => x.Recipients).WithKeyColumn("RecipientListID").AsList().LazyLoad();
    }

}

However when I use the following code in my test:

private IList<Recipient> _recipients = new List<Recipient>()
        {
            new Recipient { FirstName = "Joe", LastName = "Bloggs", Email = "joe@bloggs.com", IsDeleted = false },
            new Recipient { FirstName = "John", LastName = "Doe", Email = "john@doe.com", IsDeleted = false },
            new Recipient { FirstName = "Jane", LastName = "Smith", Email = "john@smith.com", IsDeleted = false }
        };

        [Test]
        public void Can_Add_RecipientList_To_Database()
        {
            new PersistenceSpecification<RecipientList>(Session)
                .CheckProperty(x => x.Name, "My List")
                .CheckProperty(x => x.Columns, "My columns")
                .CheckProperty(x => x.IsDeleted, false)
                .CheckProperty(x => x.ApplicationID, Guid.NewGuid())
                .CheckProperty(x => x.Recipients, _recipients)
                .VerifyTheMappings();
        }

The following error occurs:

failed: System.ApplicationException : Expected 'System.Collections.Generic.List`1[Project.Data.Domains.Recipients.Recipient]' but got 'NHibernate.Collection.Generic.PersistentGenericBag`1[Project.Data.Domains.Recipients.Recipient]' for Property 'Recipients'

I can see that the error is because I am passing in a List and the list returned is a PersistentGenericBag, therefore throwing an error. I don't get how you are suppose test this though if you can't just pass in an IList?

Any help would be appreciated.

From stackoverflow
  • Well stupidely I was using the wrong method on PeristenceSpecification.

    I should have been using CheckList not CheckProperty.

    Duh!

    John_ : Be sure not to do the same with CheckReference :)

Brute force , Need help

Hi guys I'm a junior student and I had a course called The Design and Analysis of Algorithms,The course is cool but the instructor is not any way, I dont understand the brute force and how to count the number of operations and how to count the time complexity(worst,best,avg), I tried to search for it on the net but each time I end with the big-o notation and the divide and conquer which i dont want. If any of you guys can download the instructor slide from this link and see what I'm talking about ....

the slide

I really need your help on this , and I promise i will do my best

From stackoverflow
  • Brute force is a class of "algorithms" (or plainly "way of doing things") where you don't try to be clever, just dumb search. Example: if you want to look up a phone number in the phone book, the clever solution would be to observe that all entries are sorted by last name, and directly look up the correct letter, etc. The brute force solution would be to read the phone book from the start, checking every single name and stopping when the right name is found.

    Karl : Wow, way too many questions. Get yourself some books or finish taking the class. Or look up sorting algorithms, there's plenty of good examples online.
  • Brute forcing is the task of testing all possible configurations of a specific problem and testing if one of them matches the properties of a solution.

    Consider a 4 digit pin code. If you lose it, you can test all possible codes from 0000 to 9999 to find the correct code. This is a kind of brute forcing.

    The same thing can be used to solve some computer science problems such as 0/1 knapsack problem in which, a thief wants to find out what to steal. Every object has value v[i] and weight w[i]. He or she wants to find out the combination that provides maximum value and has less weight than "W". A possible solution to this problem is to consider all combinations of objects and find the value and the weight of each combination and then select the optimal one.

    nickf : he should just grab the gear and go, man! the cops are coming!
  • You might get a bit out of watching the first few lectures of this series on algorithms.

  • Can i have an example on the selection sort and bubble sort how to count the time complixity and how to count the operations and what is the traveling sales man problem

    The Selection sort algorithm is available in pseudocde from Wikipedia, as is the Bubble Sort. The time complexity is computed by the number of times it takes the algorithm to run through until it gets the right answer.

    The Traveling Salesman problem is a classic problem in computer science that interrelates the algorithm's execution time with figuring out the answer to the question.

    To wit:

    The problem is: given a number of cities and the costs of travelling from any city to any other city, what is the least-cost round-trip route that visits each city exactly once and then returns to the starting city?

    If I try to use an algorithm to bruteforce the best route, it'll take a really long time on any route bigger than the simplest route. That's where Big(O) comes in, it shows me how each algorithm I'd choose would affect how long it'd take me to get the answer.

    I posted this answer based off of the comments you left for other answers. For what it's worth, Big-O notation is exactly what you want, it's the indicator of how long your algorithm will take to execute.

What is the best 2D graphics library for Windows Mobile?

The title speaks for itself... I've tried to find another question like it but must have missed it if it exists. I'm looking for anything, from a core library replacing GAPI to a .net wrapper... It's for building a nice UI so no 3D needed...

From stackoverflow
  • The System.Drawing classes in .NET are a lot more powerful than people realize. The only thing missing (which is actually really important in 2D graphics) is the ability to read and write individual pixels. This is technically possible using the GetPixel and SetPixel methods on the Bitmap object, but these methods are unimaginably slow.

    Fortunately, there is a super-fast alternative that you can implement by calling LockBits on a bitmap and then accessing the bitmap's byte data directly. I've used this to good effect. In fact, I've spent the last week creating a fisheye lens effect entirely in .NET (no libraries or PInvoke calls at all).

    This JPEG is kind of crappy, but it shows what's possible using just .NET:

    alt text

  • IMO I would suggest getting hold of the frame buffer somehow and drawing to it directly if possible or using D3DM or use the drawing services provided by the Native Platform (GDI) through APIs like DrawGradient() etc from coredll.dll and since you are on WM you might be able to leverage aygshell.dll to draw widgets.

    Here are some links...

    1)Using gradient fill from dot net
    2)Using gradient fill directly
    3)Other native GDI functions

  • Take a look at WMGL http://www.mobilityflow.com/products/wmgl/

Emitting headers from a tiny Python web-framework

I am writing a web-framework for Python, of which the goal is to be as "small" as possible (currently under 100 lines of code).. You can see the current code on github

Basically it's written to be as simple to use as possible. An example "Hello World" like site:

from pyerweb import GET, runner

@GET("/")
def index():
    return "<strong>This</strong> would be the output HTML for the URL / "

@GET("/view/([0-9]+?)$")
def view_something(id):
    return "Viewing id %s" % (id) # URL /view/123 would output "Viewing id 123"

runner(url = "/", # url would be from a web server, in actual use
       output_helper = "html_tidy" # run returned HTML though "HTML tidy"

Basically you have a function that returns HTML, and the GET decorator maps this to a URL.

When runner() is called, each decorated function is checked, if the URL regex matches the request URL, the function is run, and the output is sent to the browser.

Now, the problem - outputting headers. Currently for development I've just put a line before the runner() call which does print Content-type:text/html\n - this is obviously a bit limiting..

My first ideas was to have the functions return a dict, something like..

@GET("/")
def index():
    return {
        "html": "<html><body>...</body></html>",
        "headers": {"Location":"http://google.com"}
    }

I really don't like this - having to return a dict with a specifically named key isn't nearly as nice as just returning a string..

I could check if the returned data is a dict, if so use returned_data['html'] as the output, if it's a string, there is no custom headers to be sent... but this means to go from no headers (which would be the case a huge majority of the time) to headers, you'd have to change the return function from return my_html to return {'html':my_html} which isn't very elegant either..

After writing this, I discovered "Sinatra" - a similar-in-use Ruby library, and looked at how it dealt with headers:

get "/" do
    content_type 'text/css', :charset => 'utf-8'
end

This seems like it could be nice enough in Python:

@GET("/")
def index():
    header("location", "http://google.com")

To implement this, I was considering changing how the functions are executed - instead of simply using the return value, I would change sys.stdout to a StringIO, so you could do..

def index():
    print "<html>"
    print "<head><title>Something</title></head>"
    print "<body>...</body>"
    print "</html>

..without having to worry about concatenating a bunch of strings together. The upshot of this is I could have a separate stream for headers, so the above header() function would write to this.. Something like:

def header(name, value):
    pyerweb.header_stream.write("%s: %s" % (name, value))

Basically, the question is, how would you output headers from this web-framework (mostly in terms of use, but to a lesser extent implementation)?

From stackoverflow
  • You should reconsider the notion of returning HTML - headers are part of HTTP. If you build your framework around an HTTP stream, the headers are simply lines that precede the HTML payload.

    A headers example from the above link:

    HTTP/1.1 200 OK
    Date: Mon, 23 May 2005 22:38:34 GMT
    Server: Apache/1.3.3.7 (Unix)  (Red-Hat/Linux)
    Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    Etag: "3f80f-1b6-3e1cb03b"
    Accept-Ranges: bytes
    Content-Length: 438
    Connection: close
    Content-Type: text/html; charset=UTF-8
    

    For a Python example, see the implementaion of BaseHTTPRequestHandler.send_header(keyword, value).

    dbr : This framework isn't "designed around an HTTP stream", it's designed to be a nice to use as possible. Making the user manually print headers followed by two carriage-returns would be not-nice to use, and difficult to make send default-headers.. I see your point, but I want to abstract HTTP-stuff
  • you could use that idea of returning a dict or a string, but add a new decorator, so the 'evolution' for a user would be:

    simple html:

    @GET("/")
    def index():
    return "<html><body>...</body></html>"
    

    with constant headers (one @HEADER for each one, or a dict with all of them):

    @GET("/")
    @HEADER("Location","http://google.com")
    def index():
    return "<html><body>...</body></html>"
    

    with complex, maybe calculated headers:

    @GET("/")
    def index():
    return {
        "html": "<html><body>...</body></html>",
        "headers": {"Location":"http://google.com"}
    }
    

    the @HEADER() decorator would simply change the returned value, so the 'framework' code would stay simple.

  • Look at PEP 333 for an excellent design pattern for a very lightweight web server. If your server has this exact API, you can reuse it in a lot of context with a lot of other products.

    PEP 333 (WSGI) suggests that you don't directly return the page, but you provide the HTML page to a "start_response" callable object, which wraps your HTML in the proper HTTP response, with the proper headers.

Opinions on type-punning in C++?

I'm curious about conventions for type-punning pointers/arrays in C++. Here's the use case I have at the moment:

Compute a simple 32-bit checksum over a binary blob of data by treating it as an array of 32-bit integers (we know its total length is a multiple of 4), and then summing up all values and ignoring overflow.

I would expect such an function to look like this:

uint32_t compute_checksum(const char *data, size_t size)
{
    const uint32_t *udata = /* ??? */;
    uint32_t checksum = 0;
    for (size_t i = 0; i != size / 4; ++i)
        checksum += udata[i];
    return udata;
 }

Now the question I have is, what do you consider the "best" way to convert data to udata?

C-style cast?

udata = (const uint32_t *)data

C++ cast that assumes all pointers are convertible?

udata = reinterpret_cast<const uint32_t *>(data)

C++ cast that between arbitrary pointer types using intermediate void*?

udata = static_cast<const uint32_t *>(static_cast<const void *>(data))

Cast through a union?

union {
    const uint32_t *udata;
    const char *cdata;
};
cdata = data;
// now use udata

I fully realize that this will not be a 100% portable solution, but I am only expecting to use it on a small set of platforms where I know it works (namely unaligned memory accesses and compiler assumptions on pointer aliasing). What would you recommend?

From stackoverflow
  • As far as the C++ standard is concerned, litb's answer is completely correct and the most portable. Casting const char *data to a const uint3_t *, whether it be via a C-style cast, static_cast, or reinterpret_cast, breaks the strict aliasing rules (see Understanding Strict Aliasing). If you compile with full optimization, there's a good chance the code will not to the right thing.

    Casting through a union (such as litb's my_reint) is probably the best solution, although it does technically violate the rule that if you write to a union through one member and read it through another, it results in undefined behavior. However, practically all compilers support this, and it results in the the expected result. If you absolutely desire to conform to the standard 100%, go with the bit-shifting method. Otherwise, I'd recommend going with casting through a union, which is likely to give you better performance.

    Tom : litb's solutions is correct by the standard - but as I said, I'm looking at specific platforms already.
    Johannes Schaub - litb : i'm not sure why they downvote this:) but i'm also not sure that my use of the union is undefined behavior.i'm aware that writing to a member and reading from another member is undefined behavior.but in my case, i'm pointing to a member of it,which is assumed to have a valid value,and read it then.
    Steve Jessop : I don't think this particular example does break strict aliasing. char* is a special case under strict aliasing rules - a char* may never be assumed not an alias of a pointer to some other type. But in my answer I still play safe: it's just not worth doing char* differently from other similar cases.
    Johannes Schaub - litb : onebyone, type punning is not the issue, it's already solved by the union. but the issue is the reading from the union member even though we didnt write to it before. the standard does not seem to forbid it. but that's the question we are unsure about :/
    Johannes Schaub - litb : @Adam, i have decided to delete my answer, because i found i don't agree with most of its interpretations anymore. But i still agree with your stuff in this answer.
    Steve Jessop : @litb: What I meant is (if I can remember back that far): contrary to what Adam says, casting `const char*` to `const uint32_t*` *does not* break strict aliasing rules. Aliasing a `uint32_t*` with a `char*` is allowed, and safe, and optimisation doesn't change that.
  • This looks like a case-book example of when to use reinterpret_cast, anything else will give you the same effect without the explicitness you get from using a language construct for its official use.

  • Ignoring efficiency, for simplicity of code I'd do:

    #include <numeric>
    #include <vector>
    #include <cstring>
    
    uint32_t compute_checksum(const char *data, size_t size) {
        std::vector<uint32_t> intdata(size/sizeof(uint32_t));
        std::memcpy(&intdata[0], data, size);
        return std::accumulate(intdata.begin(), intdata.end(), 0);
    }
    

    I also like litb's last answer, the one that shifts each char in turn, except that since char might be signed, I think it needs an extra mask:

    checksum += ((data[i] && 0xFF) << shift[i % 4]);
    

    When type punning is a potential issue, I prefer not to type pun rather than to try to do so safely. If you don't create any aliased pointers of distinct types in the first place, then you don't have to worry what the compiler might do with aliases, and neither does the maintenance programmer who sees your multiple static_casts through a union.

    If you don't want to allocate so much extra memory, then:

    uint32_t compute_checksum(const char *data, size_t size) {
        uint32_t total = 0;
        for (size_t i = 0; i < size; i += sizeof(uint32_t)) {
            uint32_t thisone;
            std::memcpy(&thisone, &data[i], sizeof(uint32_t));
            total += thisone;
        }
        return total;
    }
    

    Enough optimisation will get rid of the memcpy and the extra uint32_t variable entirely on gcc, and just read an integer value unaligned, in whatever the most efficient way to do that is on your platform, straight out of the source array. I'd hope the same is true of other "serious" compilers. But this code is now bigger than litb's, so there's not much to be said for it other than mine is easier to turn into a function template that will work just as well with uint64_t, and mine works as native endian-ness rather than picking little-endian.

    This is of course not completely portable. It assumes that the storage representation of sizeof(uint32_t) chars corresponds to the storage representation of a uin32_t in the way we want. This is implied by the question, since it states that one can be "treated as" the other. Endian-ness, whether a char is 8 bits, and whether uint32_t uses all bits in its storage representation can obviously intrude, but the question implies that they won't.

    Tom : I just tried your last example. GCC refuses to vectorize it, complaining about "unhandled data-ref".
    Steve Jessop : Fair enough, it's not the fastest possible on hardware supporting vector ops. Maybe GCC will get better in future. My extreme programming guru says I don't need to lose sleep over that. My first suggestion isn't as fast as possible on *any* hardware :-)
    Steve Jessop : But I agree that since I mentioned the memcpy being low-cost, the fact that it prevents vectorization could be a show-stopper for some applications.

How do I refresh a table view after returning from a "detail view?"

Hi,

I'm new to iPhone and Apple development and working on my first application. It simple with only a TableView and a "detail view" when an item in a table is selected.

What I want to do is change the background color of the cell in the TableView based on some action taken in my "detail view".

When the application initially loads I customize the colors in -cellForRowAtIndexPath: method, but when user navigates back from my detail view that function is not called, so my table view doesn't have the colors updated. The only way to get that refreshed now is to exit the application and start it up again. (I persist their selection with NSUserDefaults.)

Obviously, I want the table view to be refreshed when they come back form the detail view, but I don't know how to get a reference to a cell and in which method to do that. I'm assuming it should go in -viewDidAppear, since that is called everything the view is shown.

Thanks for your help! alex

From stackoverflow
  • You should really do that in viewWillAppear:.

    Also, you can get the visible cells of the table view by using its visibleCells method. Due to the way table views work, other cells do not exist at all -- scrolling will trigger the delegate method and create new cells (or dequeue existing ones if you use dequeue...).

  • Try [tableView reloadData] - that should make the tableview run though the rows and rebuild itself.

How to draw procedural graphics in Vista Sidebar?

How do I draw procedural graphics in a Vista Sidebar gadget?

I have a gadget that collects data over time and I want to draw animating graphs. My current approach is to draw the graph with VML that I update from JScript on a timer tick. Is this the best way? Can I return bitmap bits from a DLL function as the srouce to an <IMG>? Embed bitmap bits into the HTML itself (and again update it via JScript)? I'd love to hear some ideas.

Thanks!

From stackoverflow
  • The way I currently do it is with Javascript and Adobe Flash Player communicating via the ExternalInterface in ActionScript. It seamlessly integrates local Javascript instances with an instance of a Flash Player and you can communicate just about anything between the two. You can use the fantastic drawing API in ActionScript and really get some power into you hands for charting or just embed some tools off the net.

    But then, if the sandbox permits it, generating data by targeting DLLs would be great! I don't have anything functional at hand to test it, so I leave it to other contributors.

  • You can use Silverlight 2 with Sidebar gadgets now - the Silverlight toolkit available on Codeplex (http://www.codeplex.com/Silverlight) includes charting controls (which support animation), so that should be relatively straightforward.

  • im faced with the same issue right now if anyone has any other suggestions. Silverlight in a gadget will not work on a 64 bit OS by the way. Limitation of Silveright at the moment.

  • How about wz_jsgraphics ?

    DHTML graphics via javascript

    http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm