Thursday, February 17, 2011

wxWidgets sizer problem

I'm still getting used to the sizers in wxWidgets, and as such can't seem to make them do what I want...

Basicly I wantt a large panel that will contain a list of other panels/boxes, which each then contain a set of text fields

----------------------
| label    text box  |
| label2   text box2 |
----------------------
----------------------
| label    text box  |
| label2   text box2 |
----------------------
----------------------
| label    text box  |
| label2   text box2 |
----------------------

I also need to be able to add (at the end), and remove(anywhere) these boxes. If theres too many to fit in the containing panel a vertical scroll bar is also required.

This is what ive tried so far, it works for the first box thats created with the containing panel, but additional added items are just a small box in the top left of the main panel, even though the sizer code is the same for all boxes...

//itemsList is a container containg a list of *Item pointers to each box/panel/whatever the right name is
Items::Items(wxWindow *parent)
:wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_SUNKEN)
{
    //one sstarting item
    OnAdd(wxCommandEvent());
}

void Items::OnAdd(wxCommandEvent &event)
{
    unsigned id = itemsList .size();
    Item *item = new Item(this,id);
    itemsList .push_back(item);

    RebuildSizer();
}
void Items::RebuildSizer()
{
    this->SetSizer(0,true);
    wxBoxSizer *sizerV = new wxBoxSizer(wxVERTICAL);

    for(std::vector<Item*>::iterator it = itemsList .begin(); it != itemsList .end(); ++it)
        sizerV->Add(*it, 1, wxEXPAND | wxLEFT | wxRIGHT, 5);

    SetSizer(sizerV);
}
void Items::OnRemove      (wxCommandEvent &event, unsigned itemId)
{
    delete itemsList [itemId];
    itemsList .erase(items.begin()+itemId);
    for(std::vector<Item*>::iterator it = itemsList .begin()+itemId; it != itemsList .end(); ++it)
        (*it)->ChangeId(itemId++);

    RebuildSizer();
}

Also whats the best way to lay out the contents of each box? I was thinking of using a 2 by 2 grid sizer, box im not sure how to make the text boxes to expand to be as wide as possible while making the labels stay as small as possible (but also mantaing the alignment between the 2 text boxes)?

From stackoverflow
  • "If theres too many to fit in the containing panel a vertical scroll bar is also required."

    You could have a look at wxScrolledWindow.

    "additional added items are just a small box in the top left of the main panel"

    I am not sure, but, maybe a call to wxSizer::Layout() will help.

    "Also whats the best way to lay out the contents of each box?"

    Have a look at this sizerdemo. If it is not mandatory, that the labels stay as small as possible, you could give the labels a fixed width and only let the text boxes grow. If you want to adapt the size when adding or removing new boxes, you could implement the OnSize() event handler.

  • May I suggest to you to post this question to one of the wxWidgets mailing list? They will be able to help you very quickly.

  • Can I also recommend the wxForum, I have found it very useful for wxWidgets questions in the past.

    More specifically for scrolling wxScrolledWindow should help, use wxScrolledWindow->SetSizer with your top level sizer (the one that contains your controls) to set up a scrolled area, also check out the samples called scroll, scrollsub and vscroll included in wxWidgets (in the samples directory of your wxwidgets install).

Patch vs. Hotfix vs. Maintenance Release vs. Service Pack vs....

When you are somewhere between version 1 and version 2, what do you do to maintain your software?

The terms Patch, Hotfix, Maintenance Release, Service Pack, and others are all blurry from my point of view, with different definitions depending on who you talk to.

What do you call your incremental maintenance efforts between releases?

From stackoverflow
  • When I hear those terms this is what comes to mind:

    • Patch - Publicly released update to fix a known bug/issue
    • Hotfix - update to fix a very specific issue, not always publicly released
    • Maintenance Release - Incremental update between service packs or software versions to fix multiple outstanding issues
    • Service Pack - Large Update that fixes many outstanding issues, normally includes all Patches, Hotfixes, Maintenance releases that predate the service pack

    That being said that isn't how we do updates at all. We just increment the version and/or build number (which is based on the date) and just call it an "Update". For most software I find that easier, you can easily see that one computer is running 1.1.50 vs 1.2.25 and know which is newer.

  • I'd like to point to http://semver.org/ for an attempt to define version numbers in sane manner, and the definitions given there actually fit closely to how I use version numbers (or how I wish I used them :))

    As for the term definitions, I find patch and hotfix very similar, except "hotfix" is usually not broadcast if done to a service.

    Maintenance Release and Service Pack fit fairly closely to the two denominations of version numbers. if you have a version number structure like X.Y.Z, Maintenance Release would be the Z, Service Pack would be the Y. I've really only heard these terms in big, corporate products, though. I'm more acquainted with the minor/mayor version terms.

    Of course, every shop has their own use of the terms, and it depends on which type of user you're targeting. For end-users of MMOs, for instance, every update is a "patch" because the user has to "patch their client" to apply it, while for end-users of more common software, you often just have the term "update" and "new version" (new mayor version).

Creating WCF messages with mutiple namespaces.

I'm trying to create a WSTransfer implementation (I realise Roman Kiss has written one already for WCF - but it doesn't actually meet the specifications)

I've ended up abandoning data contracts on the service contacts because WSTransfer is loosely coupled; so each the create message looks like Message Create(Message request).

This works fine, and everything is lovely until it's time to fire back a response.

The problem I have is in the way a WSTransfer response is constructed. Taking create as the example the response looks like

<wxf:ResourceCreated>
  <wsa:Address>....</wsa:Address>
  <wsa:ReferenceProperties>
    <xxx:MyID>....</xxx:MyId>
  </wsa:ReferenceProperties>
</wxf:ResourceCreated>

As you can see there are 3 different XML namespaces within the response message.

Now, it's easy enough when one is involved; you can (even if you're not exposing it), create a data contract and set the values and fire it back

Message response = Message.CreateMessage(request.Version, 
            "http://schemas.xmlsoap.org/ws/2004/09/transfer/CreateResponse",
            resourceCreatedMessage);

However the problem arises in setting different namespaces for the child elements within the response; it appears WCF's datacontracts don't do this. Even using

[MessageBodyMember(Namespace="....")]

on the individual elements within the response class don't appear to make any changes, everything becomes part of the namespace specified for the contract class.

So how do I apply different namespaces to individual elements in a WCF Message; either via a contract, or via some other jiggery pokery?

From stackoverflow
  • In a case like this when you need precise control over the XML output, you should use the the XmlSerializer instead of DataContract or MessageContract serialization. Here is more info on how to do that:

    http://msdn.microsoft.com/en-us/library/ms733901.aspx

    blowdart : Been there, tried that; that fails even more horribly :)
    jezell : What wasn't working for you?
  • So following up jezell's answer; the problem with using XmlSerialization when creating a message by hand is that the child elements of the root get their element names mangled. This happens because despite the operation contract being marked as [XmlSerializerFormat] when you create a message by hand the DataContractSerializer is used.

    You cannot pass the XmlSerializer into Message.CreateMessage() because it demands an XmlObjectSerializer, which XmlSerializer is not.

    So the answer appears to be write a wrapper class for XmlSerializer, which has XmlObjectSerializer as its base class (here's an example) and pass that in; along with your message holding class.

    Unfortunately it's not clever enough to setup prefixes in the XML; so you end up with messages like

    <ResourceCreated xmlns="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Address xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing/">http://localhost:8731/Design_Time_Addresses/AddTests/WSTransfer/</Address>
      <ReferenceType xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing/"></ReferenceType>
    

    But it's all equivalent.

Full-screen camera

How can I make the iPhone camera full-screen by removing the overlay?

Can I change the camera toolbar style?

From stackoverflow
  • There is no reliable way to do this using the current iPhone SDK. You should file a bug with Apple to try to get them to add more control over the camera.

  • I ran into a blog on this last night, that discussed how to stripp out the overlay view.

    http://blogs.oreilly.com/iphone/2008/10/creating-a-full-screen-camera.html

    It's not clear whether this would pass testing, though Phanfare do customize their view.

  • I've been trying to do this for quite some time.

    Aswell as the link in the post above mine. I've stumbled across this page - http://blog.airsource.co.uk/index.php/2008/11/11/views-of-uiimagepickercontroller/

    While the article itself is not spectacular, the comments provide some great insight and suggestions. Also, some users provided links to some external sites. If you happen to get it working, please email me.

What access does Apache 2.0 need in Windows Server 2003 in order to start as a service?

Until this morning, I have had Apache 2.0 running as a service using a local account which was configured with appropriate permissions. Sometime yesterday, someone must have changed something, and now Apache 2.0 won't start as a service under this account.

I made the account an Administrator temporarily, and Apache 2.0 starts fine.

I tried following the access listed in the official documentation, but it seems to require more access. Does anyone know what access Apache 2.0 needs to start as a service?

I'm running Apache 2.0.63 with SVN 1.4.6 and mod_auth_sspi for windows domain authentication.

I also checked the syntax of the configuration file from command-line using the -t parameter, but I received the message Syntax OK.

Here's the error I get when starting as a service from command-line:

X:\>net start apache2
The Apache2 service is starting.
The Apache2 service could not be started.

A service specific error occurred: 1.

More help is available by typing NET HELPMSG 3547.
From stackoverflow
  • Verify that your service still has the "Log on as a Service" user right. If your machine is a part of a domain, it's possible the account permissions or user rights have been reset by a group policy.

    Can you do a "Run As" using the Apache account, and run Apache from the command line? This will tell you if there are other permission problems.

    Kev : If you're running Apache as Local System, you might need to read http://johnnycoder.com/blog/2008/11/10/run-cmdexe-as-local-system-account/
  • Set the "LogLevel" directive to "debug" in the apache configuration file.

    Execute Apache from the command-line and use the "-X" argument so that Apache does not fork processes.

    Apache should output a bit more information to help debug your problem.

Column cannot be added because its CellType property is null exception

Hi,

I have trouble with the following piece of code. When I go through with the debugger I get an exception when it comes to the following line:

dgvCalls.Columns.Insert(1, msisnnColumn);

I get an exception:

Column cannot be added because its CellType property is null.

Oddly, I created the same procedure for some other DataGridViews and it worked fine.

if (!(dgvCalls.Columns.Contains("DirectionImage")))
                {
                    directionIconColumn = new DataGridViewImageColumn();
                    directionIconColumn.Name = "DirectionImage";
                    directionIconColumn.HeaderText = "";
                    dgvCalls.Columns.Insert(0, directionIconColumn);
                    directionIconColumn.CellTemplate = new DataGridViewImageCell();
                }
                if (!(dgvCalls.Columns.Contains("msisndColumn")))
                {
                    msisnnColumn = new DataGridViewColumn();
                    msisnnColumn.Name = "msisndColumn";
                    msisnnColumn.HeaderText = "Klic";
                    dgvCalls.Columns.Insert(1, msisnnColumn);
                    msisnnColumn.CellTemplate = new DataGridViewTextBoxCell();
                }

Any suggestions?

From stackoverflow
  • dgvCalls.Columns.Insert(1, msisnnColumn);
    msisnnColumn.CellTemplate = new DataGridViewTextBoxCell();
    

    Try flipping those two lines. That might do the trick.

    niko : Thanks! It works. I wonder why it works in the other form where the order is different!
    BFree : The thing is, since you're just assigning msisnnColumn to a new DataGridViewColumn() it doesn't know what CellType you want, so it just leaves it null. Therefore when you went to do the insert, it blew up. However, if you first assign the CellTemplate to a TextBoxCell, it knows what you want.
  • its working... really thanks.....

Is there a modern ( e.g. CLR ) replacement for bison / yacc ?

I have just been re-working an old bit of compiler-like code written using bison. While I was doing this, I was wondering what the modern equivalent is? Is there a nice .NET ( or similar ) compiler writing framework that takes a BNF grammar and splits out a DLL that does the parsing?

From stackoverflow
  • Check out the Gardens Point Parser Generator. It's a YACC/BISON like implementation for C#

    GPPG

  • There's also ANTLR, a very widely used parser generator implemented in Java.

    utku_karatas : ..which btw supports C# as a target.
  • A quick google search found the Gardens Point Parser Generator.

  • I recommend Coco/R. It's very similar to JavaCC. Supports C#, Java, C++, F#, VB.Net, Oberon, and other languages.

  • I use Gardens Point GPPG and GPLEX in my own dynamic language interpreter. GPPG and GPLEX have been adopted by Microsoft as MPPG and MPLEX in the Visual Studio 200x SDK. This means that is very easy to create a Visual Studio language extension for syntax colouring of your language.

Can Delphi applications have double shortcut keys like Visual Studio? (ie. Ctrl-k Ctrl-k)

As stated in the title, I need double shortcut keys for my application (ie. as Ctrl-k Ctrl-k is the Toggle Bookmark key in VS.NET ). I wonder if any of you has found a solution for this in Delphi? I suspect by modifying the very core of VCL one might do but is there any easier way?

From stackoverflow
  • SynEdit had/has this functionality in the SynEditKey*.* files (I'm looking at version 1.03 myself), complete with an editor for shortcuts. Maybe you can not simply integrate them into your application, but the code will hopefully provide some guidance.

Can you add data to a datagrid with no data source?

I have a DataGrid with 5 template columns,

However when I try and add some dynamically created controls into the grid, it fails, as there are no rows.

-Can i add a blank row in and use that? and how? -Or any other way?

From stackoverflow
  • I'm pretty sure you have to bind to a data source. But it's easy enough to create your own DataTable and insert a row into it with some dummy info.

    //pseudo code:
    
    DataTable dt = new DataTable();
    DataColumn dc = new DataColumn("column1");
    
    DataRow dr = dt.NewRow();
    dr["column1"] = "value1";
    dt.Rows.AddNew(dr);
    
    myDataGrid.DataSource = dt;
    myDataGrid.DataBind();
    
  • If you are using an unbound DataGridView, you can create new rows and then add them to DataGridView. Your question referred to DataGrid, but you tagged it for DataGridView.

    // Sample code to add a new row to an unbound DataGridView
    DataGridViewRow YourNewRow = new DataGridViewRow();
    
    YourNewRow.CreateCells(YourDataGridView);
    YourNewRow.Cells[0].Value = "Some value"
    YourNewRow.Cells[1].Value = "Another value";
    
    YourDataGridView.Rows.Add(YourNewRow);
    
  • how i insert data to next row in datagrid . i while loop it inserts to same row which causes exception.

What are some useful third-party SSIS components (data flow or control flow)?

The number of products out there right now still seems to be slim.

From stackoverflow

Problem matching Java String against array

I need to see if a string value matches with an object value, but why won't this work?

public int countPacks(String flavour) {
    int counter = 0;
    for(int index = 0; index < packets.size(); index++) {            
        if (packets.equals(flavour)) {
           counter ++;
        }
        else {
           System.out.println("You have not entered a correct flavour");
        }
    } 
    return counter; 
}
From stackoverflow
  • You probably mean something like

    if (packets.get(index).equals(flavour)) { ...

  • What is "packets"? It's not going to be a string - so how would it equal a string?

    I suspect you meant your test to be:

    if (packets.get(index).equals(flavour))
    

    However you're still going to print out "You have not entered a correct flavour" for every packet of the "wrong" flavour even if there's one with the right flavour!

    I suspect you want to move the error reporting to the end of the method, after the loop, and only execute it if counter == 0

  • You should do it this way to be certian you really are comparing strings in the most foolproof way possible.

    I also fixed your loop

    public int countPacks(String flavour, List packets)
        {
            int counter = 0;
            for (Iterator iter = packets.iterator(); iter.hasNext();) {
          Map packet = (Map) iter.next();
    
                if (packet.get("flavour").toString().equalsIgnoreCase(flavour)) {
                 counter ++;
                }
              else {
                System.out.println("You have not entered a correct flavour");
                }
            } 
            return counter; 
        }
    
  • Assuming packets is a Collection (and you're using JDK 1.5 or greater), you could also just make the method

    public int countPacks(String flavor) { int numOccurrences = java.util.Collections.frequency(packets, flavor); if(numOccurrences == 0) { System.out.println("You have not entered a correct flavor"); } return numOccurrences; }

  • A problem with methods declared in Object is that there is a lack of static type checking in their use. The same applies to synchronized, where it is common to lock the wrong object.

    In this case Object.equals(Object) works with any two objects. You have used the collection, packets, instead of getting an element from it. The important question is not how did this particular bug come about, but how can we prevent it from occurring in the first place.

    First of all, use generics and get assign each element for the iteration to a statically typed local:

    public int countPacks(String flavour) {
        // [ The field represents a count. ]
        int count = 0;
        for(int index=0; index<packets.size(); ++index) {
            String packet = packets.get(index);
            if (packet.equals(flavour)) {
               ++count;
            }
        } 
        // [The error mesage was printed for each non-match.
        //  Even this is probably wrong,
        //    as it should be valid to have no packs of a valid flavour.
        //  Having the message in this method is actually a bit confused.]
        if (count == 0) {
            System.out.println("You have not entered a correct flavour");
        }
        return count; 
    }
    

    We can further tidy this up using the enhanced for loop.

    public int countPacks(String flavour) {
        int count = 0;
        for(String packet : packets) {
            if (packet.equals(flavour)) {
               ++count;
            }
        } 
        if (count == 0) {
            System.out.println("You have not entered a correct flavour");
        }
        return count; 
    }
    

    That looks clearer, but a good programmer knows his/her libraries.

    public int countPacks(String flavour) {
        int count = Collections.frequency(packets, flavour);
        if (count == 0) {
            System.out.println("You have not entered a correct flavour");
        }
        return count; 
    }
    

    You might also consider a Map<String,Integer> instead of the collection.

What would be the ideal script language for parsing text files?

My code reads in a file, usually HTML but it could be any plain text. Now I was thinking to have each piece as a separate module loaded externally at run time so I don't have to maintain it. I would like to use a scripting language to parse the text/strings and call my appropriate c or c++ functions. What scripting language would be good to use? I'd need traveling forward and backward in the string/textfile, extracting HTML like links, as well as numbers, dates, and a few other pieces of data. What should I use?

Being able something like:

goto(".com"); //move pos forward
rgoto("method"); //move back
string1 = "Username is %STRING%" //extract a string with a space deliminator 
time = Time%HH_MM_SS%?m //extract the time down to the second

Where ? would be 1 letter so it wouldn't matter if its am or pm. doing %MH_MM% would be good to (military hours, 0-23 and minutes, no second available.

But any script language would due. I just like something doesn't take much effort to parse text with.

From stackoverflow
  • Personally I would use Python for this. Especially to be able to call your existing C/++ code.

    Vinko Vrsalovic : Lua is another good option
    EBGreen : I have briefly looked at Lua, but I am more conversant with parsing in Python that is why I would suggest it. Not because I have any criticism of Lua for the task. Thanks for the edit btw. My typing-fu is weak today.
  • lua is designed for embedding. It's perfect for what you are trying to do.

    Vinko Vrsalovic : Python is also a good option
    Paul : Both work. Lua's considerably smaller (which may or may not be an issue) and as David said, designed from the get-go for easy embedding
    EBGreen : Ya. I was a little confused by the question. When I read it I got the feeling that the OP wanted a language that lived outside his app. On second read, embedded may be what the OP really wanted in which case Lua probably would be easier than Python.
  • Lua is not only expressly designed for embedding, but there's also LPEG (by the same author), which lets you write a parser almost in EBNF. it's like having YACC (or Bison) in a small library.

  • Vote for python - the text processing is top notch, and it's great for embedding. It can call your c/c++ code and you can dynamically import modules - great for keeping that maintainability cost down. Dive into python has a really great tutorial on how to set that up using the GetAttr() method and a consistent naming scheme.

    http://diveintopython.org/object_oriented_framework/index.html

  • How come nobody's mentioned perl yet? I personally can't stand perl, but it is purpose built for doing this kind of stuff.

    If you can't stomach perl either, I'd ecommend Ruby - it takes a lot of the powerful things from perl, like built-in regular expression syntax, but without a lot of the mess. It is also very easy to create Ruby <-> C libraries to handle those transitions.

    Python doesn't have a lot of this, so while it's a great general purpose language, and may or may not be as easy to link to your C/C++ code, I don't think it'd be quite as nice for pure string processing

  • Perl is definitely the traditional answer - it'll certainly get the job done, and would totally have been my answer two months ago.

    On the other hand, I've recently discovered python, which I've completely switched over to for this kind of thing. The inclusion of HTML/XML/DOM parsers in the standard library is what did it for me.

    Just the other other day I knocked a HTML data extractor / screen scraper together in python in 20 minutes and ~4o lines of code. Loved every second of it.

  • PERL, anyone... thats what it was invented for.

  • AWK was designed for that... http://en.wikipedia.org/wiki/Awk

  • Perl is the language that was made specifically for this. Noting that, I would recommend you pick up Python or Ruby, both of which are sort of a modern equivalent to Perl. Perl's syntax can be a little maddening.

    Python is for people who appreciate a very clean language with one way to accomplish each thing.

    Ruby is for people who like being able to do neat "tricks" and accomplish the same thing different ways.

    Oh, and Perl was made as a replacement for scripts using awk, sed, and grep. Don't start with them.. they're really odd if you didn't know them from long ago.

  • Chiming in with Perl.

  • This is pretty much what perl was made for.

Besides EAR and EJB, what do I get from a J2EE app server that I don't get in a servlet container like Tomcat?

We use Tomcat to host our WAR based applications. We are servlet container compliant J2EE applications with the exception of org.apache.catalina.authenticator.SingleSignOn.

We are being asked to move to a commercial J2EE application server.

  1. The first downside to changing that I see is the cost. No matter what the charges for the application server, Tomcat is free.
  2. Second is the complexity. We don't use either EJB nor EAR features (of course not, we can't), and have not missed them.

What then are the benefits I'm not seeing?

What are the drawbacks that I haven't mentioned?


Mentioned were...

  1. JTA - Java Transaction API - We control transaction via database stored procedures.
  2. JPA - Java Persistence API - We use JDBC and again stored procedures to persist.
  3. JMS - Java Message Service - We use XML over HTTP for messaging.

This is good, please more!

From stackoverflow
  • Hi,

    Cost isn't necessarily a downside as there a few free J2EE servers, e.g. JBoss and Glassfish.

    Your question assumes that (J2EE = Servlet + EJB + EAR) and therefore, there's no point in using anything more than a Servlet container if you're not using EJB or EAR. This is simply not the case, J2EE includes a lot more than this. Examples include:

    • JTA - Java transaction API
    • JPA - Java persistence API
    • JMS - Java messaging specification
    • JSF - technology for constructing user interfaces out of components

    Cheers, Donal

    dacracot : We use JSF without a J2EE container.
    dacracot : I haven't mentioned the specific J2EE app server so that it wouldn't be the subject of flaming, but it does come with a price tag.
    Don : I'm not saying that you need to use a J2EE app server to use any of these technologies, just making the point that there's more to J2EE than EJB, Servlets and EAR.
  • Unless you want EJB proper, you don't need a full stack J2EE server (commercial or not).

    You can have most J2EE features (such as JTA, JPA, JMS, JSF) with no full stack J2EE server. The only benefit of a full stack j2ee is that the container will manage all these on your behalf declaratively. With the advent of EJB3, if you need container managed services, using one is a good thing.

    You can also have no cost full stack server such as Glasfish, Geronimo or JBoss.

    You can also run embedded j2ee container managed services with embedded Glasfish for example, right inside Tomcat.

    You may want an EJB container if you want to use session beans, message beans, timer beans nicely managed for you, even with clustering and fail over.

    I would suggest to the management to consider upgrades based on feature need. Some of these EJB containers might just well use embedded Tomcat as their webserver so what gives!

    Some managers just like to pay for things. Ask them to consider a city shelter donation or just go for BEA.

    Don : JBoss uses Tomcat as the embedded servlet container
  • If you are being asked to move to a commercial J2EE server, the reasons may have nothing to do with the J2EE stack but with non-technical considerations.

    One thing that you do get with a commercial J2EE offering that you don't get with Tomcat is technical support.

    This may not be a consideration for you, depending on the service levels your web applications are supposed to meet. Can your applications be down while you try and figure out a problem with Tomcat, or will that be a major problem?

  • In truth, with the vast array of packages and libraries available, there's little an EJB container provides that can't be added to a modern servlet container (ala Tomcat). So, if you ever wanted any of those features, you can get them "ala carte" so to speak with the cost being the process of integrating that feature in to your app.

    If you're not "missing" any of these features now, then from a practical standpoint, you probably don't need them.

    That all said, the modern EJB containers are really nice, and come with all of those services pre-integrated, making them, somewhat, easier to use should you ever want them. Sometimes having the feature nearby and handy is enough to make someone explore it for its potential in their application, versus seeing the integration process of a feature as a hurdle to adoption.

    With the quality of the free EJB containers, it's really hard to imagine how buying one can be at all useful, especially given that you have no real demand for one at the moment.

    However, I do encourage you to actually get one and play around with it and explore the platform. Glassfish is very easy to get started with and very good, and should easily take your WARs as is (or with very minor tweaks).

    As a rule when it comes between running Tomcat vs an EJB container the question is really why NOT use one? Speaking specifically for Glassfish, I find it easier to use than Tomcat, and It's primary difference is that it can have a moderately larger memory footprint (particularly for a small application) than Tomcat, but on a large application you won't even notice that. For me, the memory hit isn't a big deal, for others it may be an issue.

    And it gives me a single source of all this nice functionality without having to crawl the net for a 3rd party option.

    Thorbjørn Ravn Andersen : A distinct advantage of deploying an EAR is that all the wiring can be specified inside, instead of having to set up Tomcat explicitly for providing several additional services. The more that can be automated the better.
    Jonik : Great answer, and by far the clearest one here. What you say mostly matches my understanding of the matter: if using Tomcat, no real need to switch as you can add almost any JEE feature anyway, but if starting afresh, it's probably easier to go with a good, free app server like JBoss or Glassfish.

How can you detect on runtime if your sql-server 2005 instance is a 32 or 64 bit instance?

How can you detect if your sql-server 2005 instance is a 32 or 64 bit instance from C# code? If you know some documentation on this issue, please let me know.. Thanks!

From stackoverflow
  • I'm curious... why?

    E. : Optimizations fine tuning..
  • Use SERVERPROPERTY ( propertyname )

    With property name Edition.

    64-bit versions of the Database Engine append (64-bit) to the version.

    SELECT SERVERPROPERTY ( 'Edition' )
    

    For me on my x64 machine returns the following string value: Enterprise Edition (64-bit)

    You could also check the env variable PROCESSOR_ARCHITECTURE to see what the machine itself is running as.

    E. : Is this listed also on the registry or can be concluded from a file version? I need a way to do this not assuming I have a valid connection.
    Brian R. Bondy : updated answer with PROCESSOR_ARCHITECTURE note. I'm not 100% sure if you can install an x86 SQL on an x64 though. But I don't think you can.

VBA event for document edited.

Is there an event for when a document is edited? If not does anyone know where I could find a list of the VBA events available?

From stackoverflow
  • I would start here:

    http://msdn.microsoft.com/en-us/isv/aa905357.aspx

    http://msdn.microsoft.com/en-us/isv/bb190538.aspx

  • Here are the events for the document object:

    http://msdn.microsoft.com/en-us/library/aa140279(office.10).aspx

    Events

    DocumentBeforeClose : Immediately before any open document closes. 
    DocumentBeforePrint : Before any open document is printed. 
    DocumentBeforeSave : Before any open document is saved. 
    DocumentChange : A new document is created, when an existing document is opened, or when another document is made the active document. 
    DocumentOpen : A document is opened. 
    EPostageInsert : A user inserts electronic postage into a document. 
    EPostagePropertyDialog : A user clicks the E-postage Properties (Labels and Envelopes dialog box) button or Print Electronic Postage toolbar button. This event allows a third-party software application to intercept and show their properties dialog box. 
    MailMergeAfterMerge : After all records in a mail merge have merged successfully. 
    MailMergeAfterRecordMerge : After each record in the data source successfully merges in a mail merge. 
    MailMergeBeforeMerge : A merge is executed before any records merge. 
    MailMergeBeforeRecordMerge : As a merge is executed for the individual records in a merge. 
    MailMergeDataSourceLoad : The data source is loaded for a mail merge. 
    MailMergeDataSourceValidate : A user performs address verification by clicking Validate in the Mail Merge Recipients dialog box. 
    MailMergeWizardSendToCustom : The custom button is clicked on step six of the Mail Merge Wizard. 
    MailMergeWizardStateChange : A user changes from a specified step to a specified step in the Mail Merge Wizard. 
    NewDocument : A new document is created. 
    Quit : The user quits Word. 
    WindowActivate : Any document window is activated. 
    WindowBeforeDoubleClick : The editing area of a document window is double-clicked, before the default double-click action. 
    WindowBeforeRightClick : The editing area of a document window is right-clicked, before the default right-click action. 
    WindowDeactivate : Any document window is deactivated. 
    WindowSelectionChange : The selection changes in the active document window. 
    WindowSize : The application window is resized or moved.
    

    There are also Auto Macros:

    AutoNew, AutoOpen, AutoExec, AutoExit

  • To intercept any Word command, you can:

    1.

    Press Alt+ F8 to bring up the Macros dialog and where it says “Macros in”, select “Word Commands”.

    2.

    Find and select one of the commands you want to intercept – for instance, to intercept the Print commands you need to find FilePrint and FilePrintDefault. To intercept the Save commands you need to find FileSave, FileSaveAs and FileSaveAll

    3.

    Where it says “Macros in”, select the template you want to store the macro in, and click “Create”.

    4.

    The code needed to execute the command will be written for you; just add your own code.

  • The command is WindowSelectionChange

Auto-Generate Binded Columns/Fields for a DetailsView

In Visual Studio I have set up a DetailsView and an ObjectDataSource which connects with my BLL.

<asp:DetailsView runat="server" ID="UserProfileview" DataSourceID="UserData" AutoGenerateRows="False">

<asp:ObjectDataSource ID="UserData" runat="server" TypeName="UoM.Business.Core.UserAccount" SelectMethod="Read">
<SelectParameters>
    <asp:QueryStringParameter QueryStringField="id" Direction="input" Type="Int32" Name="Id" DefaultValue="" />
</SelectParameters>

I am not sure how so Visual Studio can automatically show me all the columns/fields so I can start modifying it instead of typing in each column manually.

Any ideas?

From stackoverflow
  • If you set AutoGenerateRows="False" then the tags for your bound columns have to be added manually.

Is there a better way than parsing /proc/self/maps to figure out memory protection?

On Linux (or Solaris) is there a better way than hand parsing /proc/self/maps repeatedly to figure out whether or not you can read, write or execute whatever is stored at one or more addresses in memory?

For instance, in Windows you have VirtualQuery.

In Linux, I can mprotect to change those values, but I can't read them back.

Furthermore, is there any way to know when those permissions change (e.g. when someone uses mmap on a file behind my back) other than doing something terribly invasive and using ptrace on all threads in the process and intercepting any attempt to make a syscall that could affect the memory map?

Update:

Unfortunately, I'm using this inside of a JIT that has very little information about the code it is executing to get an approximation of what is constant. Yes, I realize I could have a constant map of mutable data, like the vsyscall page used by Linux. I can safely fall back on an assumption that anything that isn't included in the initial parse is mutable and dangerous, but I'm not entirely happy with that option.

Right now what I do is I read /proc/self/maps and build a structure I can binary search through for a given address's protection. Any time I need to know something about a page that isn't in my structure I reread /proc/self/maps assuming it has been added in the meantime or I'd be about to segfault anyways.

It just seems that parsing text to get at this information and not knowing when it changes is awfully crufty. (/dev/inotify doesn't work on pretty much anything in /proc)

From stackoverflow
  • I do not know an equivalent of VirtualQuery on Linux. But some other ways to do it which may or may not work are:

    • you setup a signal handler trapping SIGBUS/SIGSEGV and go ahead with your read or write. If the memory is protected, your signal trapping code will be called. If not your signal trapping code is not called. Either way you win.

    • you could track each time you call mprotect and build a corresponding data structure which helps you in knowing if a region is read or write protected. This is good if you have access to all the code which uses mprotect.

    • you can monitor all the mprotect calls in your process by linking your code with a library redefining the function mprotect. You can then build the necessary data structure for knowing if a region is read or write protected and then call the system mprotect for really setting the protection.

    • you may try to use /dev/inotify and monitor the file /proc/self/maps for any change. I guess this one does not work, but should be worth the try.

    Edward Kmett : By the time I get a SIGSEGV its too late. I need to know if some data is constant to know that I can "safely" constant fold through it. With appropriate hacks for constant mmap'ed non-constant data and the vsyscall page.

How to properly set a datatable to an gridview in code with an ObjectDataSource?

Hello,

I have an ObjectDataSource with an ID of ObjectDataSource1 on a webpage. I also have a gridview in which I am binding the ObjectDataSource.ID to the GridView.DataSourceID. The problem I get is when text is changed in a textbox, the code calls BrokerageTransactions.GetAllWithDt which returns a DataTable. I want to set this datatable as the DataSource for the GridView, but it is telling me that I can't set the DataSouce and DataSourceId together. How can I fix this? Code is below. Also. Why can't you set a DataSourceID and a DataSource when using an ObjectDataSource?

Thanks, X

protected void BrokerageChange(Object sender, EventArgs e)
{
    BrokerageTransactions brokerageaccountdetails = 
                          new BrokerageTransactions();

    DataSet ds = BrokerageAccount.GetBrkID2(new 
                 Guid(Membership.GetUser().ProviderUserKey.ToString()), 
                 ddlBrokerageDetails.SelectedItem.Text.ToString());

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        brokerageaccountdetails.BrokerageId = 
                                new Guid(dr["BrkrgId"].ToString());
    }

    ddlBrokerageDetails.SelectedItem.Value = 
                        brokerageaccountdetails.BrokerageId.ToString();

    if (txtTransactionsTo.Text != "" 
        && txtTransactionsFrom.Text != "")
        ObjectDataSource1.FilterExpression = 
        "convert(CreateDt,System.DateTime)>Convert('" + 
         Convert.ToDateTime(txtTransactionsFrom.Text) + "',System.DateTime) 
         and Convert(CreateDt,System.DateTime)<convert('"
         + Convert.ToDateTime(txtTransactionsTo.Text.ToString()) + 
         "',System.DateTime)";
    else if (txtTransactionsFrom.Text != "")
            ObjectDataSource1.FilterExpression =
            "convert(CreateDt,System.DateTime)>convert('" +
             Convert.ToDateTime(txtTransactionsFrom.Text) + 
            "',System.DateTime)";
    else if (txtTransactionsTo.Text != "")
            ObjectDataSource1.FilterExpression = 
            "convert(CreateDt,System.DateTime)
            <convert('" 
            + Convert.ToDateTime(txtTransactionsTo.Text.ToString()) +  
            "',System.DateTime)";
    else
        ObjectDataSource1.FilterExpression = " ";

    grvBrokerage.DataSourceID = ObjectDataSource1.ID;
    grvBrokerage.DataBind();

    DateTime dtTransFrom = Convert.ToDateTime("1/1/1900");
    DateTime dtTransTo = System.DateTime.Today;

    //TransactionsTo Box is Empty
    if ((txtTransactionsFrom.Text.Length > 2) 
    && (txtTransactionsTo.Text.Length < 2)) 
    {
        dtTransFrom = Convert.ToDateTime(txtTransactionsFrom.Text);
        dtTransTo = System.DateTime.Today;
    }

    //TransactionsFrom Box is Empty
    if ((txtTransactionsFrom.Text.Length < 2) 
    && (txtTransactionsTo.Text.Length > 2))
    {
       dtTransFrom = Convert.ToDateTime("1/1/1900");
       dtTransTo = Convert.ToDateTime(txtTransactionsTo.Text);
    }

    //TransactionsFrom Box and TransactionsTo Box is Not Empty
    if ((txtTransactionsFrom.Text.Length > 2) 
    && (txtTransactionsTo.Text.Length > 2))
    {
        dtTransFrom = Convert.ToDateTime(txtTransactionsFrom.Text);
        dtTransTo = Convert.ToDateTime(txtTransactionsTo.Text);
    }
    // Fails Here
    grvBrokerage.DataSource = 
    BrokerageTransactions.GetAllWithDt(brokerageaccountdetails.BrokerageId, 
                                       dtTransFrom, 
                                       dtTransTo);
    grvBrokerage.DataBind();  }
From stackoverflow
  • You got 2 options:

    • Do not use the ObjectDataSource at all. You just use the DataSource property and Set It grammatically every time.
    • You use the DataSourceID property of the GridView and Add 2 plain asp:Parameters with default value set. On the ObjectDataSource_Selecting Event you set these parameters through e.InputParameters[]

    Hope this helps.

    Xaisoft : Could you be more specific? What would these two parameters be? Thanks
    norbertB : Those parameters for you would be the From and To dates for the BrokerageTransactions In your example code this would be dtTransFrom and dtTransTo.

modern for loop for primitive array

Hi,

Is there any performance difference between the for loops for primitive array?

Assume

double[] doubleArray = new double[300000];


for (double var: doubleArray) 
   someComplexCalculation(var);

or

for ( int i = 0, y = doubleArray.length; i < y; i++)
   someComplexCalculation(doubleArray[i]);

Test result

I actually went and profile it.

Total timeused for modern loop= 13269ms
Total timeused for old loop   = 15370ms

So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5.

From stackoverflow
  • Why not measure it yourself?

    This sounds a bit harsh, but this kind of questions are very easy to verify yourself.

    Just create the array and execute each loop 1000 or more times, and measure the amount of time. Repeat several times to eliminate glitches.

  • There is no difference. Java will transform the enhanced for into the normal for loop. The enhanced for is just a "syntax sugar". The bytecode generated is the same for both loops.

    erickson : This answer is incorrect. Compile both examples and examine the resulting byte codes. You'll see that the code is different, as I explain in my answer.
  • My opinion is that you don't know and shouldn't guess. Trying to outsmart compilers these days is fruitless.

    There have been times people learned "Patterns" that seemed to optimize some operation, but in the next version of Java those patterns were actually slower.

    Always write it as clear as you possibly can and don't worry about optimization until you actually have some user spec in your hand and are failing to meet some requirement, and even then be very careful to run before and after tests to ensure that your "fix" actually improved it enough to make that requirement pass.

    The compiler can do some amazing things that would really blow your socks off, and even if you make some test that iterates over some large range, it may perform completely differently if you have a smaller range or change what happens inside the loop.

    Just in time compiling means it can occasionally outperform C, and there is no reason it can't outperform static assembly language in some cases (assembly can't determine beforehand that a call isn't required, Java can at times do just that.

    To sum it up: the most value you can put into your code is to write it to be readable.

  • Your hand-written, "old" form executes fewer instructions, and may be faster, although you'd have to profile it under a given JIT compiler to know for sure. The "new" form is definitely not faster.

    If you look at the disassembled code (compiled by Sun's JDK 1.5), you'll see that the "new" form is equivalent to the following code:

    1: double[] tmp = doubleArray;
    2: for (int i = 0, y = tmp.length; i < y; i++) {
    3:   double var = tmp[i];
    4:   someComplexCalculation(var);
    5: }
    

    So, you can see that more local variables are used. The assignment of doubleArray to tmp at line 1 is "extra", but it doesn't occur in the loop, and probably can't be measured. The assignment to var at line 3 is also extra. If there is a difference in performance, this would be responsible.

    Line 1 might seem unnecessary, but it's boilerplate to cache the result if the array is computed by a method before entering the loop.

    That said, I would use the new form, unless you need to do something with the index variable. Any performance difference is likely to be optimized away by the JIT compiler at runtime, and the new form is more clear. If you continue to do it "by hand", you may miss out on future optimizations. Generally, a good compiler can optimize "stupid" code well, but stumbles on "smart" code.

  • Similar question here !

  • I got very curious about your question, even after my previous answer. So I decided to check it myself too. I wrote this small piece of code (please ignore math correctness about checking if a number is prime ;-)):

    public class TestEnhancedFor {
    
        public static void main(String args[]){
         new TestEnhancedFor();
        }
    
        public TestEnhancedFor(){
         int numberOfItems = 100000;
         double[] items = getArrayOfItems(numberOfItems);
         int repetitions = 0;
         long start, end;
    
         do {
          start = System.currentTimeMillis();
          doNormalFor(items);
          end = System.currentTimeMillis();
          System.out.printf("Normal For. Repetition %d: %d\n", 
            repetitions, end-start);
    
          start = System.currentTimeMillis();
          doEnhancedFor(items);
          end = System.currentTimeMillis();
          System.out.printf("Enhanced For. Repetition %d: %d\n\n", 
            repetitions, end-start);
    
         } while (++repetitions < 5);
        }
    
        private double[] getArrayOfItems(int numberOfItems){
         double[] items = new double[numberOfItems];
         for (int i=0; i < numberOfItems; i++)
          items[i] = i;
         return items;
        }
    
        private void doSomeComplexCalculation(double item){
         // check if item is prime number
         for (int i = 3; i < item / 2; i+=2){
          if ((item / i) == (int) (item / i)) break;
         }
        }
    
        private void doNormalFor(double[] items){
         for (int i = 0; i < items.length; i++)
          doSomeComplexCalculation(items[i]);
        }
    
        private void doEnhancedFor(double[] items){
         for (double item : items)
          doSomeComplexCalculation(item);
        }
    
    }
    

    Running the app gave the following results for me:

    Normal For. Repetition 0: 5594 Enhanced For. Repetition 0: 5594

    Normal For. Repetition 1: 5531 Enhanced For. Repetition 1: 5547

    Normal For. Repetition 2: 5532 Enhanced For. Repetition 2: 5578

    Normal For. Repetition 3: 5531 Enhanced For. Repetition 3: 5531

    Normal For. Repetition 4: 5547 Enhanced For. Repetition 4: 5532

    As we can see, the variation among the results is very small, and sometimes the normal loop runs faster, sometimes the enhanced loop is faster. Since there are other apps open in my computer, I find it normal. Also, only the first execution is slower than the others -- I believe this has to do with JIT optimizations.

    Average times (excluding the first repetition) are 5535,25ms for the normal loop and 5547ms for the enhanced loop. But we can see that the best running times for both loops is the same (5531ms), so I think we can come to the conclusion that both loops have the same performance -- and the variations of time elapsed are due to other applications (even the OS) of the machine.

    erickson : Interesting results! As I expected, JIT appears to have optimized away the subtle difference in the compiled byte code.

SAX parser breaking on ñ

I have implemented a SAX parser in Java by extending the default handler. The XML has a ñ in its content. When it hits this character it breaks. I print out the char array in the character method and it simply ends with the character before the ñ. The parser seems to stop after this as no other methods are called even though there is still much more content. ie the endElement method is never called again. Has anyone run into this problem before or have any suggestion on how to deal with it?

From stackoverflow
  • What's the encoding on the file? Make sure the file's encoding decloration matches it. Your parser may be defaulting to ascii or ISO-8859-1. You can set the encoding like so

    <?xml version="1.0" encoding="UTF-8"?>
    

    UTF-8 will cover that character, just make sure that's what the file actually is in.

  • If you are saving your XMLs in ASCII, you can only use the lower half (first 128 characters) of the 8-bit character table. To include accented, or other non-english characters in your XML, you will either have to save your XML in UTF-8 or escape your charaters like &#241; for ñ.

Find the address of a DLL in memory

Hi,

I have just been getting into low level programming (reading/writing to memory that sort of thing) and have run into an issue i cannot find an answer to.

The piece of information i want to read from has an address that is relative to a DLL loaded in memory e,g, it is at mydll.dll + 0x01234567. the problem im having is that the dll moves around in memory but the offset stays the same. Is there anyway to find out the location of this dll in memory.

I am currently trying to do this preferably in c# but i would be grateful for help in most highish level languages.

From stackoverflow
  • From a Win32 perspective you need to use the GetModuleHandle and GetModuleInformation functions. These let you look the module handle up by name, and then retrieve information, including the base address about that handle.

    It should be straight forward to wrap these APIs using the standard P/Invoke wrappers.

  • i tried the method Rob Walker suggested and could not get it to work (i think it did not work because the dll was loaded as part of another executable so it could not be found so easily).

    I did however discover a solution that worked for me so here it is:

    i created an object of type Process

    String appToHookTo = "applicationthatloadedthedll";
    Process[] foundProcesses = Process.GetProcessesByName(appToHookTo)
    ProcessModuleCollection modules = foundProcesses[0].Modules;
    ProcessModule dllBaseAdressIWant = null;
    foreach (ProcessModule i in modules) {
    if (i.ModuleName == "nameofdlliwantbaseadressof") {
                        dllBaseAdressIWant = i;
                    }
            }
    

    now you have the module you can just do dllbaseAdressIWant.BaseAddress to get the value.

    Hope this helps