Monday, April 11, 2011

Changing ListBox selection is not moving changes from BindingSource to DataSet.

The answer to this question may turn out to be, "Don't use typed DataSets without using the Binding Navigator." I am curious, however, about the behavior I'm seeing.

So, I created a form where every control was dragged from the data sources explorer. I deleted the Binding Navigator because it is ugly and inappropriate for this particular form. I added a ListBox and set the DataSource to the BindingSource.
Notice that the ListBox is not bound, it is just filling itself from the BindingSource. By some magic that I wasn't counting on, moving around in the ListBox is navigating the BindingSource and all other controls are updating accordingly.

I can make changes to the bound controls and explicitly call EndEdit on the BindingSource and then update the DataSource through the Table Adapter. Works great.

When I make changes in the bound controls and click a new option in the ListBox, I want to be able to check for changes and prompt to save or reset if there are any.

Here is the strange part that I haven't been able to figure out.

No matter what event I attach to, DataSet.HasChanges doesn't return true until the second ListBox change. I've searched and tried dozens of suggestions, most of them ridiculous, but a few that seemed promising. No luck.

Edit: It isn't the second click that is significant, it is when you click back on the original (edited) item.

From stackoverflow
  • Since asking the question, I've learned a bit more about BindingSources, DataSets and TableAdapters.

    Here is what works:

        private void MyListBox_Click(object sender, EventArgs e)
        {
            this.myBindingSource.EndEdit();
            if (myDataSet.HasChanges())
            {
                if (MessageBox.Show("Save changes?", "Before moving on", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    myTableAdapter.Update(myDataSet.myDataTable);
                }
                else
                {
                    myDataSet.RejectChanges();
                }
            }
        }
    

How can I pre-compress files with mod_deflate in Apache 2.x?

I am serving all content through apache with Content-Encoding: zip but that compresses on the fly. A good amount of my content is static files on the disk. I want to gzip the files beforehand rather than compressing them every time they are requested.

This is something that, I believe, mod_gzip did in Apache 1.x automatically, but just having the file with .gz next to it. That's no longer the case with mod_deflate.

From stackoverflow
  • This functionality was misplaced in mod_gzip anyway. In Apache 2.x, you do that with content negotiation. Specifically, you need to enable MultiViews with the Options directive and you need to specify your encoding types with the AddEncoding directive.

  • You can use mod_cache to proxy local content in memory or on disk. I don't know if this will work as expected with mod_deflate.

  • mod_gzip compressed content on the fly as well. You can pre-compress the files by actually logging into your server, and doing it from shell.

    cd /var/www/.../data/
    for file in *; do
        gzip -c $file > $file.gz;
    done;
    
    Otto : This will remove the original files, which means clients that don't have Aceept-Encoding: gzip won't be serviced.
    Aeon : good point, updated.
    Otto : While you're editing, why not add -9 and get the highest compression possible. My 1500 files compressed in 38 seconds, so it's worth doing to save every byte possible in bandwidth and download time. :) (Also wishing I could edit my typo in my previous comment. Ugh)
    Aristotle Pagaltzis : -9 is the default anyway.
    Otto : Not according to the man page on my Mac, it says -6 is the default.
  • To answer my own question with the really simple line I was missing in my confiuration:

    Options FollowSymLinks MultiViews
    

    I was missing the MultiViews option. It's there in the Ubuntu default web server configuration, so don't be like me and drop it off.

    Also I wrote a quick Rake task to compress all the files.

    namespace :static do
        desc "Gzip compress the static content so Apache doesn't need to do it on-the-fly."
        task :compress do
         puts "Gzipping js, html and css files."
         Dir.glob("#{RAILS_ROOT}/public/**/*.{js,html,css}") do |file|
          system "gzip -c -9 #{file} > #{file}.gz"
         end
        end
    end
    
  • I have an Apache 2 built from source, and I found I had to modify the following in my httpd.conf file:

    Add MultiViews to Options:

    Options Indexes FollowSymLinks MultiViews
    

    Uncomment AddEncoding:

    AddEncoding x-compress .Z
    AddEncoding x-gzip .gz .tgz
    

    Comment AddType:

    #AddType application/x-compress .Z
    #AddType application/x-gzip .gz .tgz
    
  • This is mostly working for me. But if I go to http://ismyblogworking.com/www.whatsthatbug.com to check http compression, there is one problem:

    "# Your blog page content type is application/x-gzip, not HTML or XHTML."

    This is causing a few people to get a download prompt instead of the compressed page. Do I need to use a Content-Type tag or something to fix this?

    EDIT: Nevermind, I think I just wasn't patient enough. It appears to be correct now.

  • I have the same issue in my Ubuntu 9.10 with apache. I have enabled mod_defleat but enable to support html.gz pages to server. I also add the Multiviews option in my virtualhost settings but still it ask me to download the file.

    any one can help me the exact settings

Bouncing Ball in Java

This is probably a really basic problem but I can't seem to find any other articles on it.

Anyway, I have written a small bouncing ball program in Java to try and expand my basic skills. The program is just a simple bouncing ball that will drop and hopefully bounce for a while. The original program worked fine but now I have tried to add gravity into the program. The gravity actually works fine for a while but then once the bounces get really small the animation becomes erratic for a very short time then the position of the ball just constantly decreases. I've tried to figure out the problem but I just can't see it. Any help would be most welcome.

public final class Ball extends Rectangle {
float xspeed = 1.0f; float yspeed = 1.0f; float gravity = 0.4f;


public Ball(float x, float y, float width, float height) {
 super(x, y, width, height);
}

public void update(){
 yspeed += gravity;

 move(xspeed, yspeed);

 if(getX() < 0){
  xspeed = 1;
 }
 if(getX() + getWidth() > 320){
  xspeed = -1;
 }
 if(getY() < 0){
  yspeed = 1;
 }
 if(getY() + getHeight() > 200 && yspeed > 0){
  yspeed *= -0.98f;
 }
 if(getY() + getHeight() > 200 && yspeed < 0){
  yspeed *= 0.98f;
 }

}

public void move(float x, float y){
 this.setX(getX()+x);
 this.setY(getY()+y);
}

}

EDIT: Thanks that seems to have sorted the erratic movement. I'm still struggling to see how I can stop my ball moving down when it has stopped bouncing. Right now it will move stop bouncing then continue moving down passed the "floor". I think it's to do with my yspeed += gravity line. I just can't see how I'd go about stopping the movement down.

From stackoverflow
  • When you do

    yspeed += gravity;
    

    you are assuming that the ball has space move through a distance dx = v_i * t + 1/2 (-g) t^2. When you are very near the floor this may not be true. It fail if:

    • You are near enough the the floor and moving down
    • You are very near the floor and have low velocity (like when the ball has lost most of it's energy)

    This bug causes your simulation to stop conserving energy, resulting in the erratic behavior you see at low amplitude.

    You can reduce the problem by using smaller time steps, and you can get rid of it outright if you do test computation to notice when you're out of room and to select a safe time step for that iteration (i.e. always use your default unless there is a problem, then calculate the best time step).

    However, the basic approximation you're using here has other problems as well. Look in any numeric analysis text for a discussion of solving differential equations numerically.

  • I suspect it's because when the ball bounces, it will actually be slightly below the "ground", and at low speeds, it won't move back above the ground in one tick - so the next update() will see it still below the ground, and bounce again - but downwards this time, so the cycle continues.

    You need to move the ball back up to ground level when it bounces, something like this:

        if(getY() + getHeight() > 200){
                yspeed *= -0.981;
                setY(200 - getHeight());
        }
    
    paxdiablo : move seems to take deltas, not absolute values, your ball is likely to fly off the edge of the universe :-)
    Blorgbeard : heh, oops. Fixed.
  • Similar question: How do I apply gravity to my bouncing ball application?

  • First things first: setting y-speed to 1 when you bounce on the top of the window is not correct, you should set yspeed to -yspeed (but if you start within the borders, it should never bounce up to the top anyway).

    Secondly, your multiply by -0.981 when bouncing on the bottom is okay but I'm concerned with the constant 0.4 gravity being added to yspeed every iteration. I think that's what is causing you wiggles at the bottom since you do the move before checking which can result in the ball dropping below ground level.

    I would try ensuring the the y value can never go below ground level by replacing the move with:

    if (getY() + getHeight() + yspeed > 200) {
        move(xspeed, 200 - getY() - getHeight());
    } else {
        move(xspeed, yspeed);
    }
    
  • The problem is that when the bounces get really small, the

    yspeed *= -0.981;
    

    line will get called in short succession. The ball will go below the bottom, start coming back up, but still be below the bottom (because 0.981 < 1.0) eventually, and it will behave eradically. Here's how you fix it:

    if(getY() + getHeight() > 200){
      yspeed *= -0.981;
      setY(400 - getY() - getHeight()); // I believe this is right.
    }
    

    By fixing the position, you won't alternate between decreasing and increasing as quickly and won't get stuck in the situation where it is always decreasing because it is always below the bounds.

    qpingu : 200 - (getY() + getHeight() - 200) = 200 - getY() - getHeight() + 200 = 400 - getY() - getHeight()
  • [EDIT: I think I misunderstood, so this probably isn't much use :) ]

    if(getY() + getHeight() > 200){
      yspeed *= -0.981;
    }
    

    You're negating the vertical velocity on every update. I'd probably try handling gravity in update-sized slices. Assuming you're doing 30 updates per second (for 30fps), maybe something like

    // Define some constants
    SecondsPerUpdate = (1.0f / 30);
    AccelDueToGravity = 0.981;
    
    if(getY() + getHeight() > 200){
      yspeed -= (AccelDueToGravity * SecondsPerUpdate);
    }
    

Regular Expression Compiler

I have had the need to use regular expressions only a few times in the work that I have done; however, in those few times I discovered a very powerful form of expression that would enable me to do some extremely useful things.

The problem is that the language used for regular expressions is wrong - full stop.

It is wrong from a psychological point of view - using disembodied symbols provides a useful reference only to those with an eidetic (photographic) memory. Whilst the syntactic rules are clearly laid out, from my experience and what I have learnt from others, evolving a regular expression that functions successfully can prove to be a difficult thing to do in all but the most trivial situations. This is understandable since it is a symbolic analog for set theory, which is a fairly complicated thing.

One of the things that can prove difficult is dissolving the expression that you are working on into it's discrete parts. Due to the nature of the language, it is possible to read one regular expression in multiple ways if you don't have an understanding of it's primary goal so interpreting other people's regexes is complicated. In natural language study I believe this is called pragmatics.

The question I'd like to ask then is this - is there such a thing as a regular expression compiler? Or can one even be built?

It could be possible to consider regexes, from a metaphorical point of view, as assembly language - there are some similarities. Could a compiler be designed that could turn a more natural language - a higher language - into regular expressions? Then in my code, I could define my regexes using the higher level language in a header file and reference them where necessary using a symbolic reference. I and others could refer from my code to the header file and more easily appreciate what I am trying to achieve with my regexes.

I know it can be done from a logical point of view otherwise computers wouldn't be possible but if you have read this far (which is unlikely :) then would you consider investing the time in realising it?

From stackoverflow
  • I never stumbled across something like that. And I don't think that something like that would be useful.

    That higher-level language would be very verbose and my guess is that you'd need pretty long statements to come up with a regular expression of average complexity.

    Maybe you just haven't been using regular expressions often enough. Believe me, my memory is far from being eidetic (or even good), but I rarely have problems crafting regular expressions or understanding those of my coworkers.

  • One way you can by pass this problem is by using programs like QuickREx, it shows how regex works on multiple test data(with highlights). You could save text data in file near your regex and latter when you want to change it, understand it or fix it that would be much easier.

  • Have you considered using a parser generator (aka compiler compiler) such as ANTLR?

    ANTLR also has some kind of IDE (ANTLR Works) where you can visualize/debug parsers.

    On the other hand a parser generator is not something to throw into you app in a few seconds like a regex - and it also would be total overkill for something like checking email address format.

    Also for simple situations this would be total overkill and maybe a better way is just to write comments for your regex explaining what it does.

  • What about write them with Regex Buddy and paste the description it generates as comment on your code?

    Michael Haren : +1: regex is extremely hard to read, but this is a tooling issue, not a language issue
  • 1) Perl permits the /x switch on regular expressions to enable comments and whitespace to be included inside the regex itself. This makes it possible to spread a complex regex over several lines, using indentation to indicate block structure.

    2) If you don't like the line-noise-resembling symbols themselves, it's not too hard to write your own functions that build regular expressions. E.g. in Perl:

    sub at_start { '^'; }
    sub at_end { '$'; }
    sub any { "."; }
    sub zero_or_more { "(?:$_[0])*"; }
    sub one_or_more { "(?:$_[0])+"; }
    sub optional { "(?:$_[0])?"; }
    sub remember { "($_[0])"; }
    sub one_of { "(?:" . join("|", @_) . ")"; }
    sub in_charset { "[^$_[0]]"; }       # I know it's broken for ']'...
    sub not_in_charset { "[^$_[0]]"; }   # I know it's broken for ']'...
    

    Then e.g. a regex to match a quoted string (/^"(?:[^\\"]|\\.)*"/) becomes:

    at_start .
    '"' .
    zero_or_more(
        one_of(
            not_in_charset('\\\\"'),    # Yuck, 2 levels of escaping required
            '\\\\' . any
        )
    ) .
    '"'
    

    Using this "string-building functions" strategy lends itself to expressing useful building blocks as functions (e.g. the above regex could be stored in a function called quoted_string(), you might have other functions for reliably matching any numeric value, an email address, etc.).

  • There are ways to make REs in their usual form more readable (such as the perl /x syntax), and several much wordier languages for expressing them. See:

    I note, however, that a lot of old hands don't seem to like them.

    There is no fundamental reason you couldn't write a compiler for a wordy RE language targeting a compact one, but I don't see any great advantage in it. If you like the wordy form, just use it.

  • Regular Expressions (well, "real" regular expressions, none of that modern stuff;) are finite state machines. Therefore, you create a syntax that describes a regular expressions in terms of states, edges, input and possibly output labels. The fsmtools of AT&T support something like that, but they are far from a tool ready for everyday use.

    The language in XFST, the Xerox finite state toolkit, is also more verbose.

    Apart from that, I'd say that if your regular expression becomes too complex, you should move on to something with more expressive power.

  • XML Schema's "content model" is an example of what you want.

    c(a|d)+r
    

    can be expressed as a content model in XML Schema as:

    <sequence>
     <element name="c" type="xs:string"/>
     <choice minOccurs="1" maxOccurs="unbounded">
      <element name="a" type="xs:string"/>
      <element name="d" type="xs:string"/>     
     </choice>
     <element name="r" type="xs:string"/>
    <sequence>
    

    Relax NG has another way to express the same idea. It doesn't have to be an XML format itself (Relax NG also has an equivalent non-XML syntax).

    The readability of regex is lowered by all the escaping necessary, and a format like the above reduces the need for that. Regex readability is also lowered when the regex becomes complex, because there is no systematic way to compose larger regular expressions from smaller ones (though you can concatenate strings). Modularity usually helps. But for me, the shorter syntax is tremendously easier to read (I often convert XML Schema content models into regex to help me work with them).

  • I agree that the line-noise syntax of regexps is a big problem, and frankly I don't understand why so many people accept or defend it, it's not human-readable.

    Something you don't mention in your post, but which is almost as bad, is that nearly every language, editor, or tool has its own variation on regexp syntax. Some of them support POSIX syntax as it was defined so many years ago, some support Perl syntax as it is today. But many have their own independent ways of expressing things, or which characters are "special" (special characters is another topic) and which are not. What is escaped and what isn't. Etc. Not only is it difficult to read a regexp written for one language or tool, but even if you totally memorize the syntax rules for your favorite variation, they can trip you up in a different language, where {2,3} no longer means what you expect. It's truly a mess.

    Furthermore, I think there are many non-programmers who (if they knew it existed) would appreciate having a pattern-matching language they could use in everyday tools like Google or Microsoft Word. But there would need to be an easier syntax for it.

    So, to answer your question, I have often thought of making some kind of cross-platform, cross-language, cross-everything library that would allow you to "translate" from any regexp syntax (be it Perl, or POSIX, or Emacs, etc) into any other regexp syntax. So that you wouldn't have to worry if Python regexps could do negative look-behind, or if character-class brackets should be escaped in an Emacs regexp. You could just memorize one syntax, then make a function call to get out the equivalent syntax for whatever you happened to be using.

    From there, it could be extended with a new pattern-matching language, that would be a bit more verbose or at least more mnemonic. Something for people who don't want to spend half-an-hour studying a regexp to figure out what it does. (And people who think regexps are fine as they are have obviously never had to maintain anything they didn't write themselves, or they would understand the need for other people to be able to parse what they've written.)

    Will I ever attempt such a beast? I don't know, it's been on my to-do list for a long time, and there are a lot of easier and more entertaining projects on there as well. But if you are contemplating something similar, let me know.

  • regular expression compiler:

    ftp://reports.stanford.edu/pub/cstr/reports/cs/tr/83/972/CS-TR-83-972.pdf

Session isn't passing over domain

In my rails app, when I log in at the www.site.com address, I am logged in just fine. Although without logging out, I go to the site, http://site.com I am logged out, but still logged in at the www.site.com address if I go back.

I can't find anything to set in my environment variables, any idea as to how to keep this session across all domains on my domain?

From stackoverflow
  • Set the session cookie properly; that is, for .site.com and site.com rather than just for www.site.com.

    Garrett : I don't know what you mean by setting the session cookie properly. I don't ever remember setting it. I just use session[:user_id] and move along.
  • since they alias www. to .; couldn't you just prepend www. onto the .?

  • You should redirect www.site.com to site.com (or the other way around). If you don't do that, google may think it's two different sites.

    Matt : +1 whilst this doesn't answer the question, it is certainly something you should implement.
  • When you set a session cookie for "site.com", that will be different than "www.site.com." You need to specify the "cookie_domain" as ".site.com" which will set the cookie or all subdomains as well. In PHP, you could use ini_set or session_set_cookie_params to set session.cookie_domain. In Rails, you can either add a small script to the enviroment.rb - something like:

    ActionController::Base.session_options[:session_domain] = '.site.com'

    (in this case you might also do some switching based on the domain name in production/test/development env's) or try some other configuration options.

    Here's more than you'd ever want to know on the subject.

    Garrett : Following what you said worked. :-)
  • In rails 2.3 this has been changed to:

    config.action_controller.session[:domain] = '.example.com'
    

    or if the session variable hasn't been created yet

    config.action_controller.session = {:domain => '.example.com'}
    

    See http://stackoverflow.com/questions/663893/losing-session-in-rails-2-3-2-app-using-subdomain/978716

Pros/Cons of Binary Reference VS WCF

I am in the process of implementing an enhancement to an existing web application(A). The new solution will provide features(charts/images/data) to the application A. The new enhancement will be a new project and will generate new assemblies. I am trying to identify what would be most elegant way to read this information. 1) Do a binary reference and read the data directly. The new assemblies live with your application and are married together 2) Write a WCF call and get the data. This will help to decouple the application.

The new application will involve me to buy some expensive licences. So if i go with the 2nd option i can limit the license fee to a single server or atmost 2-3. My current applicaiton runs under a webfarm of 8 servers.

Please share out the pros/cons of both approach.

Thanks.

From stackoverflow
  • If you decouple the two pieces sufficiently, you will also permit the use of clients running something other than .NET. Using the first option, you could only support .NET clients. This may turn out to be important, even if today you are absolutely certain that only .NET will ever be used - tomorrow, your company may be purchased by another which is a Java or PHP shop.

    Even if you never need to support a non .NET client, coupling to the assemblies will require you to maintain version compatibility between the client and server. If this is not necessary, then use option #2.

  • The benefit of using WCF (decoupled approach) is that you get a deployment option to take it outside of the machine if it impacts the machine too much in terms of processing or storage.

    The downside is that you'll likely pay some performance hit compared to linking directly.

    I'm sure you can do some dynamic linking so you don't have to deploy to all 8 servers.

Building a large form, need advice

I have to build a large form for users to fill out in order to apply for graduate study at the college I work for. There will be a large amount of information to collect (multiple addresses, personal information, business information, past school information, experience, etc...) and I want to know the best way to handle all this. I'm going to be using PHP and Javascript.

Are there any helpers or pieces of frameworks that I can use to help with the building/validation of the form, something I can just pop into my existing project?

Also would like any advice as far as keeping track of a large form and the resulting data.

From stackoverflow
  • You need to use multiple pages, and you need to include a mechanism whereby users can leave, and come back and fill out the rest of the form later (or if they're accidentally disconnected). Otherwise you're going to have all sorts of user issues, not due to your service, but because they're using computers and internet connections that are flaky, etc.

    Survey software is probably a reasonable approximation of what you're doing, and there are survey packages for most PHP CMS's. Are you building this from scratch, or do you have an existing CMS underneath?

  • A List Apart have an article on building sensible forms that is a good read

    Why does the form need to be large on the first instance? Can't you trim it down to the bare essentials for the account and provide a way for them to come back later to flesh out the rest of the details?

    For form validation, pop a gander on the jQuery validation plugin, Validation

  • A few tips, without knowing all the specifics of your form:

    Don't show the user everything at once - this can be accomplished by multiple pages, or by selectively showing/hiding elements on the form as the user progresses through it. Provide contextual navigation that says "You're on step 3 of 10" so the user can get a sense of where they are in the form and how much effort is required to finish it.

    Providing a mechanism to save and return later is a fantastic idea. If possible, provide a link to an email account of their choosing - you want to make this component as easy to use as possible, and requiring them to fill out an additional username/password to retrieve their data is just another barrier to completion.

    Only ask for what you absolutely need. Yes, you're going to have to fight some political battles here - everyone wants as much as they can get. One way to combat this (especially effective when you have pressure from multiple groups) is to build out some prototypes: 1 with EVERYTHING and one with several sections reduced or removed. Have stakeholders from each group fill out both of them and measure their time to completion or roll-throughput yield. When you've got completion data, and they realize how much every other group is asking for (in addition to their group) they are easier to work with. In short, remove as much as possible - let the user go back later to provide more details if they wish.

    Write down all your inputs on index cards and see how they logically fit together. More often than not you will find more efficient groupings or orderings. More than likely you will come up with much more usable ideas. This is extremely important when converting paper forms to online forms. Usability.gov has a fantastic case study on this topic.

  • Well I agree with Adam but I have some advise for you.

    If I were you, I would create some virtual hidden tabs instaed of multiple forms with a next button. You can create some which can control by javascript. First show the first one which will collect personal information like Name,Birthday,email, and etc... . Once user filled them out and clicked on next button,hid this and show the other which will ask for other information like address and so on.

    Once the whole dive compeleted, at the last div put a submit button which will submite the whole information to the server at once.

    By why do so?

    1. User will not get shocked becuase will not see a long form at each time and will fill out with patient.

    2. You hit server at once;usually universtites and college's servers are too busy, you better design a form which hit the server least. This could count as performance tip.

    3. Since you will submit the whole data at once, you would not worry about the issue that user will continue to fill out the other pages or not,so you will use less session which still will count as a performance tip.

    4. This way makes your form more interesting and you can called you did something like Ajax.

  • You can add Javascript form validation to make it more user-friendly, but one thing you should never skimp on is the server-side validation... which has historically been awful in PHP.

    One thing that'll make your life a million times easier here is the filter library, especially filter_input_array() since you can build the input validation programmatically instead of having to copy and paste a lot of checks. It takes some getting used to, but it's much, much better than the old way of doing things.