Thursday, March 31, 2011

Firefox Div Problem

I'm trying to make a little gallery of some school works I've done in my animation class. I want to put 3 images on each line and they are all in divs because I did onion skin wrapping for a dropshadow on them. Unfortunately this makes them all just stick together in two lines across the page. But I want them specifically formatted so I tried to wrap a div of 480px wide around each set of 3. In IE this works great and it looks perfect. However in firefox it does this

I can't figure out why it is putting that one left aligned on the second line and therefore screwing up the order of the rest. Here's my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ryan Merl's Portfolio</title>
<style type='text/css'>
    * {
     padding: 0px;
     margin: 0px;
     font-family:Verdana, Arial, Helvetica, sans-serif;
     font-size: 11px;
    }
    body {
     background-color:#333333;
     background-image: url('images/head.png');
     background-repeat: repeat-x;
    }
    a {
     color:#333333;
     text-decoration: none;
    }
    a:hover {
     color:#000000;
     text-decoration:underline;
    }
    div.main {
     width: 800px;
     background-color:#FFFFFF;
     margin-top: 10px;
     color: #000000;
     height: 1000px;
     margin-bottom: 10px;
    }
    img.thumb {

    }
    .wrap1, .wrap2, .wrap3 {
     display:inline-table;
     /* \*/display:block;/**/
    }
    .wrap1 {
     float:left;
     background:url('images/shadow.gif') right bottom no-repeat;
    }
    .wrap2 {
     background:url('images/corner_bl.gif') left bottom no-repeat;
    }
    .wrap3 {
     padding:0 4px 4px 0;
     background:url('images/corner_tr.gif' ) right top no-repeat;
    }
</style>
<link rel="stylesheet" type="text/css" href="doc/css/style.css" />
<script type="text/javascript" src="src/adapter/shadowbox-base.js"></script>
<script type="text/javascript" src="src/shadowbox.js"></script>
<script type="text/javascript" src="glossy.js"></script>
<script type="text/javascript">

Shadowbox.loadSkin('classic', 'src/skin');
Shadowbox.loadLanguage('en', 'src/lang');
Shadowbox.loadPlayer(['flv', 'html','img', 'swf'], 'src/player');

window.onload = function(){
    Shadowbox.init();
};

</script>
</head>
<body>
    <center><div class='main'>
        <img src='images/theantistudio.png' /><br /><br />

     <img src='images/gallery.png' /><br />
        <div style='text-align:center;width:480px;'>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">
                        <a href='video/rmerl_particle_fire.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_fire.png' /></a>
                    </div>
                </div>
            </div>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">
                        <a href='video/rmerl_firework.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_firework.png' /></a>
                    </div>
                </div>
            </div>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">
                        <a href='video/rmerl_fountain.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_fountain.png' /></a>
                    </div>
                </div>
            </div>
        </div>
        <br />
        <div style='text-align:center;width:480px;'>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">
                        <a href='video/rmerl_logo.flv' rel='shadowbox'><img class='thumb' src= 'thumbs/thumb_logo.png' /></a>
                    </div>
                </div>
            </div>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">  
                        <a href='video/rmerl_rocket_ship.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_rocket.png' /></a>
                    </div>
                </div>
            </div>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">
                        <a href='video/rmerl_solar_system.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_solar_system.png' /></a>
                    </div>
                </div>
            </div>
        </div>
        <br />
        <div style='text-align:center;width:480px;'>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">
                        <a href='video/rmerl_space_ship.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_space_ship.png' /></a>
                    </div>
                </div>
            </div>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">
                        <a href='video/rmerl_still_life.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_still_life.png' /></a>
                    </div>
                </div>
            </div>
            <div class="wrap1">
                <div class="wrap2">
                    <div class="wrap3">
                        <a href='video/rmerl_walkthrough.flv' rel='shadowbox'><img class='thumb' src='thumbs/thumb_walkthrough.png' /></a>
                    </div>
                </div>
            </div>
        </div>
    </div></center>
</body>
</html>
From stackoverflow
  • I cannot see your picture, but based on your description it sounds like you're not clearing the floats. You have a br after each block of three images in a div, so adding the following CSS will clear the floats and show three in a row.

    br { clear: both; }
    
    annakata : he could do that on the parent div of .wrap1 - the br is entirely extraneous
    Rich Adams : Very true. There's also no need for the inline styles on the parent div to .wrap1.
  • Also, if there is not enough width on a specified "line", it will drop down to the next line. Try making the window as wide as possible (click n drag) and see if this is the issue.

  • It looks like your second image may be slightly taller than your third. So your floated second line is only floating back until it hits the second image. Either set your image or wrap1 heights, or add style="clear:both" to the break tags between lines.

Tools for programming tutorials?

I engage in lot of training sessions and I would like to create video tutorials of all my sessions so that I can distribute it. What are the best Windows-based tools to add my PowerPoint slides, notes, voice and video (tutorials of code I write) and compile them into one video?

From stackoverflow
  • Camtasia, if you're on Windows.

    Dacto : Got me exactly 1 second before i posted! :)
    David Anderson : +1 for suggesting a really awesome suite!
    Shoban : Thanks! Any free tools?
  • Techsmith Camtasia. Supreme Screen/voice recorder with extensive deployment option (ie. as flash, avi, etc..)

  • We are using Camtasia (http://www.techsmith.com/camtasia.asp) but I've heard that Adobe's Captivate (http://www.adobe.com/products/captivate/) is way better. Both solutions are commercial.

    If you are looking for a free alternative, Camstudio(http://camstudio.org/) is pretty good, although it lacks a lot of features.

    Dacto : it's a shame that captivate doesnt come with CS4 master collection.
    Shoban : Thanks +1 :) Its sad that I cannnot mark two answers as accepted answer
  • CamTasia (TechSmith.com) integrates with PowerPoint, has an excellent editor and is very powerful. If you're spending more than a few hours on screencasts, get CamTasia. It can integrate a webcam too and export SCORM for e-learning.

    CamStudio is gpl, fine for simple screencasts, lacks an editor and has problem with audio/video synchronisation after 10s of minutes of recording (CamTasia has no synch problems)

    HyperCam is a no-frills shareware recorder, similar to CamStudio, no synch bugs, but no editor either. The author is responsive to bugs, I used it a few yrs back, it does fine for basic recordings.

    VirtualDubMod is a gpl video editor, it is clunky but will give you some editing+merging power if you're using CamStudio

    I'd suggest getting a reasonable mic (£40UK on a usb mic should do fine), avoid 3.5mm analogue jack mics as motherboard electrical noise will come through in your recording.

    ShowMeDo.com (disclosure: I'm a co-founder) hosts 800 open-source tutorial screencasts made by >100 open source authors. If you want diverse examples of presenting presentation+programming material, you'll find many examples and a friendly community here.

    I'm a professional screencaster with 4 yrs experience. I've been gathering various articles and interviews (disclosure: some interviews are with me) that should give you further background, they cover open-source tutorials, product demos, how-tos etc:

    blog.procasts.co.uk/2009/01/screencaster-interviews-and-articles/

    David : I would +10 this if I could. Great overview of the existing tools, and thanks for introducing us to ShowMeDo.

asp.net MVC - ValidationSummary not displaying

Hi All

I have a strange problem whereby the ValidationSummary is not being displayed. However, the ValidationMessage's are being displayed. I've checked the output page source and it's not as though they are in a colour that is obscuring them. I'm using the RC. Any ideas?

Edit: Break point set at ValidationSummary shows:

ViewData.ModelState.Values[1].ErrorMessage = ""
ViewData.ModelState.Values[1].Exception.InnerException.Message = "4a is not a valid value for Int32"

Does ValidationSummary use ErrorMessage and ValidationMessage use InnerException.Message?

My view code is:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<App.Models.PurchaseOrdersView>" %>


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <title>Edit</title>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Edit</h2>

    <%= Html.ValidationSummary() %>

    <% Html.BeginForm("Edit", "PurchaseOrder", FormMethod.Post); %>
    <table>
        <tr>
            <td>
                Purchase Order Id:
            </td>
            <td>
                <%= Html.TextBox("PurchaseOrderId", Model.PurchaseOrderId)%>
                <%= Html.ValidationMessage("PurchaseOrderId")%>
            </td>
        </tr>
        <tr>
            <td>
                Date:
            </td>
            <td>
                <%= Html.TextBox("Date", Model.Date.ToString("dd-MMM-yyyy"))%>
                <%= Html.ValidationMessage("Date")%>
            </td>
        </tr>
    </table>
    <input type="submit" value="Save" />

    <% Html.EndForm(); %>

</asp:Content>
From stackoverflow
  • You don't say what the errors are that are not displaying, but there are some errors which will be displayed in ValidationMessage but not in ValidationSummary. I think that this is a bug in the Release Candidate, but I am open to other interpretations. In particular, consider this line from the ValidationSummary source code:

    string errorText = GetUserErrorMessageOrDefault(modelError, null /* modelState */);
    

    Note that nothing is passed for modelState. Now contrast that with ValidationMessage:

    ... GetUserErrorMessageOrDefault(modelError, modelState) ...
    

    Finally, let's look at GetUserErrorMessageOrDefault:

        private static string GetUserErrorMessageOrDefault(ModelError error, ModelState modelState) {
            if (!String.IsNullOrEmpty(error.ErrorMessage)) {
                return error.ErrorMessage;
            }
            if (modelState == null) {
                return null;
            }
    
            string attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;
            return String.Format(CultureInfo.CurrentCulture, MvcResources.Common_ValueNotValidForProperty, attemptedValue);
        }
    

    What this tells us is that if you specify a custom error message when you add an error to the model state, it will be displayed. If, however, an exception is added (there is one overload for AddModelError which takes an exception, another which takes a string; implementing IDataErrorInfo works like the string case), instead of a string error message, it will only be displayed if modelState is non-null, and then we'll give you a generic message instead of the error message on the exception.

    Update

    Does ValidationSummary use ErrorMessage and ValidationMessage use InnerException.Message?

    Yes, that's more or less the effect. Like I said, I think this is a bug.

    Alan T : Hi Craig: For PurchaseOrderId (integer) and Date (date) I entered strings. I tried with/without custom error messages. I use UpdateModel to get add errors. I'm a n00b and I just about undertand what you're saying. I've updated my question with a bit more info.
    Naz : Hi I also think this is a bug as my validation summary isn't displaying all the errors but my in-line validation messages are. I think this bug was introduced in MVC2 RC2.
  • Try

    <%= Html.ValidationSummary(false) %>
    

rails if object.nil? then magic '' in views?

This is one of those things, that maybe so simple I'll never find it because everyone else already knows it.

I've got objects I have to check for nil in my views so I don't dereference a nil:

<%= if tax_payment.user; tax_payment.user.name; end %>

Or I could do this variant:

<%= tax_payment.user ? tax_payment.user.name : '' %>

So this is ok ... for most languages. But I feel like there must be some bit of shiny ruby or railness I'm still missing if this is the best I can do.

From stackoverflow
  • What about:

    <%= tax_payment.user.name if tax_payment.user %>
    
    Jeremy : I knew it would be a head slapper, thanks.
  • You can also try the new Object.try syntax, pardon the pun.

    This is in the shiny new Rails 2.3:

    tax_payment.try(:user).try(:name)
    
    Jeremy : Cool that is also like what I was looking for, I look forward to that release.
  • For a little more comprehensive solution, you could check out the Introduce Null Object Refactoring. The basic mechanics of this refactoring is that instead of checking for nil in the client code you instead make sure that the provider never produces a nil in the first place, by introducing a context-specific null object and returning that.

    So, return an empty string, an empty array, an empty hash or a special empty customer or empty user or something instead of just nil and then you will never need to check for nil in the first place.

    So, in your case you would have something like

    class NullUser < User
        def name
            return ''
        end
    end
    

    However, in Ruby there is actually another, quite elegant, way of implementing the Introduce Null Object Refactoring: you don't actually need to introduce a Null Object, because nil is already an object! So, you could monkey-patch nil to behave as a NullUser – however, all the usual warnings and pitfalls regarding monkey-patching apply even more strongly in this case, since making nil silently swallow NoMethodErrors or something like that can totally mess up your debugging experience and make it really hard to track down cases where there is a nil that shouldn't be there (as opposed to a nil that serves as a Null Object).

  • I just do

    <%= tax_payment.user.name rescue '' %>
    
  • I do:

    <%= tax_payment.user.name || '' %>
    

    This seems the cleanest and simplest to me.

    Jeremy : You'll get a nil object error when user is nil.
    The Wicked Flea : Good point. I haven't used it that deep. But it also depends on the page logic, the page may never get to that point because a payment requires a user. Etc. So, there are some failsafes to consider BEFORE voting me down.
    Nick : The things about the "failsafes" you mention is that they too sometimes fail.
    The Wicked Flea : Sure. So check the failsafe and the input. Ensure that output is fine that way, or redirect to an error page.
  • The Ruby community has put an incredible amount of attention to automating this idiom. These are the solutions I know of:

    The most well-known is probably the try method in Rails. However, it has received some criticism.

    In any case, I think Ben's solution is perfectly sufficient.

  • Another option, which makes sense occasionally...

    <%= tax_payment.user && tax_payment.user.name %>

    If tax_payment.user returns nil, nil.to_s (an empty string) is printed, which is harmless. If there is a user, it will print the user's name.

What model/pattern should I use for handling multiple data sources?

As part of an ecommerce system I need to design and implement a blackbox of sorts. This needs to accept customers and orders from various internal and external data sources (i.e., web site, extranet, yahoo store, amazon xml feeds, etc.) and insert/update a backend system. The api's to insert/update customer and order data are in place for the web site and working well. Now we need to add the ability to process orders from other data sources.

I've been leaning towards the provider model (one provider for each data source) and using it to standardize data into sql server tables before calling the api's to actually add customers and place orders. Are there other models or patterns that I should consider? Have you dealt with this issue before and how did you solve it? Are there any resources (articles, books, projects, etc) I should look at?

From stackoverflow
  • You may find an ETL (Extract-Transform-Load) tool will make your life easier than trying to solve your problem in code.:

    These are designed specifically for the type of data loading work that you described.

    EDIT

    While I still maintain that an ETL tool will best serve your needs, if you insist on doing it in code, you should think about implementing ETL as a pattern. The reason for this is that ETL is a well established best practice for loading data from various sources. You should take some time to study how ETL is implemented.

    At a basic level, you should have three layers, an extraction layer, a transformation layer, and a loading layer.

    The extraction layer should be responsible for retrieving the data from the source. It should not worry about the shape of the data at this points. To keep the layer clean, you should only implement code that "gets" the data here. Worry about shaping it in the transformation layer.

    The transformation layer should be responsible for taking data extracted from various sources and transforming it to the destination's shape. ETL tools do this very efficiently by treating the data as pipelines. These can be split and parallelized. You probably won't have the time or resources to do this. An alternative may be to load the data into staging tables (a less normalized representation of the data).

    The load layer takes the transformed data (in the above case from the staging tables) and loads them in to the final destination location.

    This sufficiently separates your layers so that you can protect yourself from future change. Keep in mind, however, that you're really just doing what an ETL tool will do for you out of the box.

    Geri Langlois : I've looked at SSIS as I'm in the MSSQL Server environment but found problems with that approach: http://ayende.com/Blog/archive/2007/07/15/SSIS-15-Faults.aspx http://ayende.com/Blog/archive/2008/01/15/SSIS-vs.-CSV.aspx I'm really looking for a code solution although I will consider alternatives.
    Michael Meadows : SSIS and ODI are technology specific. I agree that SSIS suffers from Microsoft's pre-version-3 problem; although it's imperfect, it is useful. Informatica is not technology specific, and it is very good, although expensive. Updated answer to include a starting point for a code solution.
  • As mentioned, ETL is probably the way to go, unless you can standardize the way the orders come in at the front, like EDI or web services.

    Use the ETL tools to transform from the sources (email, FTP files, etc) into a common pipeline in your SQL Server and then have a separate process which processes the pending batches in the pipeline.

Java split() method strips empty strings at the end?

Check out the below program.

public class test {

  /**
   * @param args
   */
  public static void main(String[] args)  {
    try {
      String data = null;
      // TODO Auto-generated method stub
      BufferedReader br = new BufferedReader(new FileReader(new File("D:/sample.txt")));
      while((data=br.readLine())!= null){
        String[] de = data.split(";");
        System.out.println("Length ="+de.length);
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Sample.txt:

1;2;3;4
A;B;;
a;b;c;

Output:

Length =4
Length =2
Length =3

Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (showing an arrayindexoutofbound exception)?

From stackoverflow
  • have a look at the docs, here the important quote:

    [...] the array can have any length, and trailing empty strings will be discarded.
    

    If you don't like that, have a look at Fabian's comment. When calling String.split(String), it calls String.split(String, 0) and that discards trailing empty strings (as the docs say it), when calling String.split(String, n) with n < 0 it won't discard anything.

  • You can specify to apply the pattern as often as possible with:

    String[] de = data.split(";", -1);
    

    See the Javadoc for the split method taking two arguments for details.

    raja : Yeah.. I got it.. Its working fine now. Thanks alot..
    Alan Moore : So mark the answer as accepted.

How do I figure out which changeset a label in TFS was applied to?

We're using Team Foundation Server and we are using Labels to create points in our version history where specific versions (either internal or external) were produced.

Right now we were wondering if a particular changeset was done before or after a specific label (and thus included in that version or not), but we must be looking in the wrong place. This information is usually provided in the bug-tracking system but this time this field was left open so we thought we could use TFS to figure it out.

The version history for a file doesn't include labels applied. To find labels, the place I know to look is to use the "Get Specific Version" dialog, set type to Label and use the Label selection dialog to see which labels we've made, but this dialog doesn't tell me the changeset before/after the label was applied.

Is the only way to figure out if a particular change was part of that release or not to create a new workspace, map up the directory with the files to a temporary directory on disk, use the Get Specific Version dialog to extract that release and do a file-diff?

Please tell me how stupid I am and point me in the right direction.

From stackoverflow
  • Have you tried opening Source Control Explorer, File -> Source Control -> Labels -> Find Label? [EDIT: that may have been in a beta version, and I don't have TFS here atm...]

    Also, are you using SideKicks? The Labels SideKick allows you to find a label and see the related changesets.

    Lasse V. Karlsen : If I use the Find Label dialog, which is basically the same one I reach from Get Specific Version, I can see a list of all the files and directories and their associated changeset, but I'd have to scroll through them all and find the maximum one. I'll look at SideKick, thanks!
    Lasse V. Karlsen : SideKicks was exactly what we needed, thanks!
  • A label in TFS does not represent a specific point in time - and a label can actually be edited after the event. See the following posts for more information:

    For this reason, I tend to use Changesets in TFS when recording the point in time for a particular release (in fact we label our binaries and installers with the actual changeset number that they were built from just to make it easier to track). (A changeset does represent a unique point in time for the state of the repository).

    Hope this helps,

    Martin.

    Lasse V. Karlsen : Well, I certainly understand that labels in TFS are not like in SourceSafe, but if I look at a single file's version history, surely the label could be included in that list, even when taking that article by Brian Harry into account? Anyway, SideKicks gave us our answer.

Low Cost Online SQL or mySQL training?

Hi,

I'm a Lotus Domino programmer who is in between consulting jobs - not by choice the consulting job market really sucks right now.

With some extra time on my hands I would like to receive some SQL training as a resume booster and to expand my skill set.

SQL is something I have used in the past, but I need a way to document my knowledge on my resume.

Can anyone recommend a source of low cost SQL or mySQL training?

Derek

From stackoverflow
  • If you are really looking for a cheap way, community colleges around my area are offering whole semester MSSQL (exam 70-431 outline) classes. Typical class would have 4 units (in California, community colleges charge $20/unit). Most of these classes are online, so flexibility and convenience are there schedule-wise.

    You could go to 4-day bootcamps but those would usually cost $2-3K per class.

  • I think the lowest cost training you can get is just reading books from your library or Amazon (links below) and practicing at home. Practice makes perfect!

    There is:

    Learning MySQL

    MySQL 5.0 Certification Study Guide

    MySQL in a Nutshell (In a Nutshell (O'Reilly))

Detect changing value of object passed as parameter

I'm now working with code that looks like this

public String getName(User user) {
     user.setSth(...);
     return user.getName();
}

I think it's bad practice to change objects passed as parameters. Is there a tool that detects that kind of code? I looked at findbugs, pmd and checkstyle, but could not find any check for this.

P.S. sorry for bad example.

From stackoverflow
  • You won't find anything because, from a tool's point of view, "getName" and "setSth" are just method calls. Humans say "this is a getter" and "this is a setter" but tools don't. In fact, getName() is not a getter because getters don't accept arguments.

    So the tool can't see anything unusual because methods change objects all the time.

    If you want to enforce this rule, have a look at extending findbugs and PMD. Both allow you to define additional constraints. What you're looking for is probably:

    • If method name starts with "get"
    • AND method body calls method of any object passes as parameter

    then print a warning. That shouldn't take too long. Run this and you will see how many "false positives" you get (warnings about methods which are actually OK). This will help you determine whether it's worth to pursue this further. Plus you'll have a new item to add to your CV :)

  • There are tools that can "reason" about code on a higher level than compilers typically do. Declarative Metaprogramming for example is a discipline that allows writing programs to check if another program conforms to a certain design, or, conversely, to mine for code smells and anti-patterns.

    Some links:

    http://prog.vub.ac.be/DMP/

    http://www.cs.bris.ac.uk/Publications/pub_master.jsp?id=1000273

    and for the rest

    http://www.google.com/search?num=100&hl=en&q=Declarative+Metaprogramming

  • You can create an interface called UserView containing only "getters", make User implement it and use the new UserView interface as the type of parameter.

    interface UserView{
     public String getName();
    ...
    
    class User implements UserView...
    
    public String getName(UserView user) {
         user.setSth(...); // Will not compile
         return user.getName();
    }
    
    eljenso : @Kalecser And how will this help the OP to detect methods that mutate their arguments?
  • You're looking for something like "const" in C++ that will enforce making the parameter value as immutable as the reference that's passed in. Immutable objects guarantee that, if you can live with them.

    You're arguing that this is "bad" because side effects like this can surprise a user. That's valid, but it's only harmful if it's an unwanted surprise.

  • Actually this is something that in C++ was very easy to do via the const qualifier. You would define a parameter as const and for that parameter you could only call methods defined as const - usually, getters.

    In Java this is absent and frankly, I don't really mind. As mentioned there are source code analyzers which can check this behavior, as well as meta-programming methods to do this as well.

    Personally, I believe that if the method is named properly, there is no problem of passing an object to it so that is it modified.

  • You could make User immutable (declare it final, declare all properties final and remote the setters. I know that isn't practible everywhere but in many places that is good and you will have no problems in passing that to other functions).

    If you have to "change" something, you can implement functions like newId in that sample:

    public final class User {
        private final String name;
        private final int id;
    
        User(String name, int id) {
            this.name = name;
            this.id = id;
        }
    
        public User newId(int newId) {
            return new User(this.name, newId);
        }
    
        //getters here;
    }
    

    The built in String, Integer, ... classes do that, too.

    Tom Hawtin - tackline : java.io.File tries, but fails.
    eljenso : @Johannes And how will this help the OP to detect methods that mutate their arguments?
    Johannes Weiß : mutation is impossible then, so no problem.
  • I think you are already on the right track: your best tool to detect this sort of code is almost certainly Findbugs. However, you will probably need to write your own detector for this pattern. Here is an example of how you would write a detector, though it isn't exactly the detector that you're looking for.

    Caveat: I don't really agree that a side-effecting getter is always bad style. However, if you really want to find that sort of thing, I would recommend Findbugs.

UC(User component) concept in Win32/.NET Win forms.

Couple of year ago I when to work for company as web developer. It has my first Sirius web development job, (ASPx/C#) so it has very exciting and I learned a lot about that world, from the developer point of view.

In that group we had a concept for the pages where loaded in the page UC’s (User controls), I don’t know if it’s the same in every web development team with every language, I’ll assume it is so.

The contract ended and I came back to develop win32 “winForm” application.

But since them I have tried to apply the same principle for my win32 development I learn there, meaning having bunch of UC’s (Visual User controls) that I load in the form. They are regular visual components, not loaded in the toolbox, code is available in the project, but the component is not developed in the form, they are loaded there.

I would like to know opinions about this approach, what other are doing similar or better to this And improvements that can help us to speed up development and increase code reuse, because that is what this is all about.

From stackoverflow
  • If you're using the layout components in Winforms, this might be an acceptable approach although I think the thing that distinguishes the web and Windows Forms (note: NOT WPF!) is that in the former you do a lot of "compositing" which is why the UserControl concept is so useful whereas in the latter you operate on very sophisticated controls (e.g. 3rd party - in my last gig we used an incredible grid control via a small company called Infralution)

    The main problem I would see is with layouts since the rendering model is a little different than the web. I know nothing about your application but if it "works" that is what is most important. I assume in this case you use things like the FlowLayoutPanel and the TableLayoutPanel properly.

    If you want to go a more canonical route, take a look beyond simply creating components at how you can use the inheritance model to composite your application in a more robust way - having a base Form class that has containers for where your "UserControl" type components go and then using some kind of interface based dependency injection to swap them out while the application is running.

    Finally, take a look at some of the open source Windows Forms applications out there to see if you're being too hard on yourself since common UI and reusable components are a goal in every application. Even though I've always thought Microsoft's Patterns & Practices stuff teetered towards being bloated, there are some good ideas and you should study some of the approaches of the Composite UI Application Block they put out.

    Okay, not finally, there's one more thing I'd like to add: take a long hard look at WPF which will bring back a lot of the concepts from your web development days and give you that kind of power in a desktop application.

Tool (or combination of tools) for reproducible environments in Python

I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team.

I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.

From stackoverflow
  • Other than easy_install?

    For our Linux servers, we use easy_install and yum.

    For our Windows development laptops, we use easy_install and a few MSI's for some projects.

    Most of the Python libraries we use are source-only, so we can use the same distribution on all boxes. If we could have a network shared device, we'd put them all there. Sadly, our infrastructure is kind of scattered, so we have to either move .TAR files around or redo the installs to rebuild the environments.

    In a few cases (e.g., PIL), we have to recompile and check the version numbers.

  • I also work with both java and python. For python development the maven equivalent is setuptools (http://peak.telecommunity.com/DevCenter/setuptools). For web application development I use this in combination with paster (http://pythonpaste.org/) for the deployment process

  • You will want easy_setup to get the eggs (roughly what Maven calls an artifact).

    For setting up your environment, have a look at working-env.py

    Python is not compiled but you can put all files for a project in an egg. This is done with setuptools

    For CI, check this answer.

  • I do exactly this with a combination of setuptools and Hudson. I know Hudson is a java app, but it can run Python stuff just fine.

    1. virtualenv to create a contained virtual environment (prevent different versions of Python or Python packages from stomping on each other). There is increasing buzz from people moving to this tool. The author is the same as the older working-env.py mentioned by Aaron.

    2. pip to install packages inside a virtualenv. The traditional is easy_install as answered by S. Lott, but pip works better with virtualenv. easy_install still has features not found in pip though.

    3. scons as a build tool, although you won't need this if you stay purely Python.

    4. Fabric paste, or paver for deployment.

    5. buildbot for continuous integration.

    6. Bazaar, mercurial, or git for version control.

    7. Nose as an extension for unit testing.

    8. PyFit for FIT testing.

  • We would be remiss not to also mention Paver, which was created by Kevin Dangoor of TurboGears fame. The project is still in alpha, but it appears very promising. A snippet from the project page:

    Paver is a Python-based build/distribution/deployment scripting tool along the lines of Make or Rake. What makes Paver unique is its integration with commonly used Python libraries. Common tasks that were easy before remain easy. More importantly, dealing with your applications specific needs and requirements is now much easier.

  • You might want to check our Devenv. It allows you to standardize the build environments for development, QA and UAT. It's free as in "free beer".

    HTH

Updating a table within a select statement

Is there any way to update a table within the select_expr part of a mysql select query. Here is an example of what I am trying to achieve:

SELECT id, name, (UPDATE tbl2 SET currname = tbl.name WHERE tbl2.id = tbl.id) FROM tbl;

This gives me an error in mysql, but I dont see why this shouldn't be possible as long as I am not changing tbl.

Edit: I will clarify why I cant use an ordinary construct for this.

Here is the more complex example of the problem which I am working on:

SELECT id, (SELECT @var = col1 FROM tbl2), @var := @var+1, 
(UPDATE tbl2 SET col1 = @var) FROM tbl WHERE ...

So I am basically in a situation where I am incrementing a variable during the select statement and want to reflect this change as I am selecting the rows as I am using the value of this variable during the execution. The example given here can probably be implemented with other means, but the real example, which I wont post here due to there being too much unnecessary code, needs this functionality.

From stackoverflow
  • What results do you want? The results of the select, or of the update.

    If you want to update based on the results of a query you can do it like this:

    update table1 set value1 = x.value1 from (select value1, id from table2 where value1 = something)  as x where id = x.id
    
    Per Stilling : I will make a clarification of my question
  • If your goal is to update tbl2 every time you query tbl1, then the best way to do that is to create a stored procedure to do it and wrap it in a transaction, possibly changing isolation levels if atomicity is needed.

    You can't nest updates in selects.

TFS Team Explorer Stand Alone With VS 2008 Installed

Does anyone know how you can install/run the TFS Team Explorer in stand alone mode when Visual Studio 2008 is installed on the same machine?

Additional Information: I should have been a little more clear in my question. I'm trying to access the Work Items.

From stackoverflow
  • The TFS Team Explorer will always integrate with a version of Visual Studio (apart from Express) if it is installed and there is no way of running it stand-alone.

    If you install the TFS 2008 Power Tools, then you can have it so that you get Windows Explorer integration for TFS which many people enjoy. You might also want to look at Team System Web Access to provide a mechanism for accessing TFS from just a web browser (but obviously doesn't include full version control capabilities)

    Finally, the company I work for has a completely standalone TFS client called Teamprise Explorer that is implemented in Java, however this is a commercial product.

    Hope that helps,

    Martin.

    Chad Green : The Windows Explorer integration from the Power Tools is great and is very helpful. I took a look at the Teamprise Explorer; really nice. But, being a Visual Studio user I just didn't see much need for it.
  • The answer is that there really isn't a standalone version. When you install VS Team Explorer on a machine without Visual Studio, the installer will install a Visual Studio shell. Then, when you run Team Explorer in standalone mode, you are actually running a Visual Studio shell.

    Martin had a good point about Team System Web Access, which probably would do the job nicely. Plus it has the added benefit that it allows non Visual Studio users access to work items. But, it was decided that it was too much trouble to get permission to install it here (working for the US Army can have its issues).

    My solution for now is to run another instance of Visual Studio and access the Team Explorer tools from there.

Converting XML between schemas - XSLT or Objects?

Given:

  • Two similar and complex Schemas, lets call them XmlA and XmlB.
  • We want to convert from XmlA to XmlB
  • Not all the information required to produce XmlB is contained withing XmlA (A database lookup will be required)

Can I use XSLT for this given that I'll need to reference additional data in the database? If so what are the arguments in favour of using XSLT rather than plain old object mapping and conversion? I'm thinking that the following criteria might influence this decision:

  • Performance/speed
  • Memory usage
  • Code reuse/comlpexity

The project will be C# based.

Thanks.

From stackoverflow
  • If the data isn't in the xml, then xslt will be a pain. You can provide additional documents with xsl:document(), or you can use xslt extension methods (but that is not well supported between vendors). So unless you are dead set on xslt, it doesn't sound like a good option on this occasion (although I'm a big fan of xslt when used correctly).

    So: I would probably use regular imperative code - streaming (IEnumerable<T>) if possible. Of course, unless you have a lot of data, such nuances are moot.

  • With C# you can always provide extension objects to XSLT transforms, so that's a non-issue.

    It's hard to qualitatively say without having the schemas and XML to hand, but I imagine a compiled transform will be faster than object mapping since you'll have to do a fair amount of wheel reinventing.

    Further, one of the huge benefits of XSLT is it's maintainability and portability. You'll be able to adapt the XSLT doc really quickly with schema changes, and on-the-fly without having to do any rebuilds and takedowns if you're monitoring the file.

    Could go either way based on what you've given us though.

    Dimitre Novatchev : +1 from me -- seems nothing more to add, at least for XSLT 1.0. One could describe in an answer the possibilities with XSLT 2.0 Schema-Aware processor, but at present doing this in combination with .NET may seem a little bit exotic. Nevertheless, this would be ideal.
  • My question is how likely are the set-of-transformations to change?

    If they won't change much, I favor doing it all in one body of source code -- here that would be C#. I would use XSD.exe (.NET XSD tool) generated serialization classes in conjunction with data layers for this kind of thing.

    On the other hand, if the set-of-transformations are likely to change -- or perhaps need to be 'corrected' post installation -- then I would favor a combination of XSLT and C# extensions to XSLT. The Extension mechanism is straightforward, and if you use the XslCompiledTransform type the performance is quite good.

What is the most impressive LINQ statement that you have come across?

I recently came across this raytracer in LINQ. Just wondering if anyone can top that?

var pixelsQuery =
from y in Enumerable.Range(0, screenHeight)
let recenterY = -(y - (screenHeight / 2.0)) / (2.0 * screenHeight)
select from x in Enumerable.Range(0, screenWidth)
       let recenterX = (x - (screenWidth / 2.0)) / (2.0 * screenWidth)
       let point = Vector.Norm(Vector.Plus(scene.Camera.Forward, 
                                           Vector.Plus(Vector.Times(recenterX, scene.Camera.Right),
                                                       Vector.Times(recenterY, scene.Camera.Up))))
       let ray = new Ray { Start = scene.Camera.Pos, Dir = point }
       let computeTraceRay = (Func<Func<TraceRayArgs, Color>, Func<TraceRayArgs, Color>>)
        (f => traceRayArgs =>
         (from isect in
              from thing in traceRayArgs.Scene.Things
              select thing.Intersect(traceRayArgs.Ray)
          where isect != null
          orderby isect.Dist
          let d = isect.Ray.Dir
          let pos = Vector.Plus(Vector.Times(isect.Dist, isect.Ray.Dir), isect.Ray.Start)
          let normal = isect.Thing.Normal(pos)
          let reflectDir = Vector.Minus(d, Vector.Times(2 * Vector.Dot(normal, d), normal))
          let naturalColors = 
              from light in traceRayArgs.Scene.Lights
              let ldis = Vector.Minus(light.Pos, pos)
              let livec = Vector.Norm(ldis)
              let testRay = new Ray { Start = pos, Dir = livec }
              let testIsects = from inter in
                                   from thing in traceRayArgs.Scene.Things
                                   select thing.Intersect(testRay)
                               where inter != null
                               orderby inter.Dist
                               select inter
              let testIsect = testIsects.FirstOrDefault()
              let neatIsect = testIsect == null ? 0 : testIsect.Dist
              let isInShadow = !((neatIsect > Vector.Mag(ldis)) || (neatIsect == 0))
              where !isInShadow
              let illum = Vector.Dot(livec, normal)
              let lcolor = illum > 0 ? Color.Times(illum, light.Color) : Color.Make(0, 0, 0)
              let specular = Vector.Dot(livec, Vector.Norm(reflectDir))
              let scolor = specular > 0 
                           ? Color.Times(Math.Pow(specular, isect.Thing.Surface.Roughness), light.Color) 
                           : Color.Make(0, 0, 0)
              select Color.Plus(Color.Times(isect.Thing.Surface.Diffuse(pos), lcolor),
                                Color.Times(isect.Thing.Surface.Specular(pos), scolor))
          let reflectPos = Vector.Plus(pos, Vector.Times(.001, reflectDir))
          let reflectColor = 
              traceRayArgs.Depth >= MaxDepth
              ? Color.Make(.5, .5, .5)
              : Color.Times(isect.Thing.Surface.Reflect(reflectPos), 
                            f(new TraceRayArgs(new Ray { Start = reflectPos, Dir = reflectDir }, 
                                               traceRayArgs.Scene, 
                                               traceRayArgs.Depth + 1)))
          select naturalColors.Aggregate(reflectColor, (color, natColor) => Color.Plus(color, natColor)))
                              .DefaultIfEmpty(Color.Background).First())
       let traceRay = Y(computeTraceRay)
       select new { X = x, Y = y, Color = traceRay(new TraceRayArgs(ray, scene, 0)) };

foreach (var row in pixelsQuery)
    foreach (var pixel in row)
        setPixel(pixel.X, pixel.Y, pixel.Color.ToDrawingColor());
From stackoverflow
  • I doubt that there's anything to top the raytracer. I'm quite fond of my Mandelbrot expression though:

    from row in Enumerable.Range(0, ImageHeight)
    from col in Enumerable.Range(0, ImageWidth)
    // Work out the initial complex value from the row and column
    let c = new Complex((col * SampleWidth) / ImageWidth + OffsetX,
                        (row * SampleHeight) / ImageHeight + OffsetY)
    // Work out the number of iterations
    select Generate(c, x => x * x + c).TakeWhile(x => x.SquareLength < 4)
                                      .Take(MaxIterations)
                                      .Count() into count
    // Map that to an appropriate byte value
    select (byte)(count == MaxIterations ? 0 : (count % 255) + 1);
    
  • Call me crazy, but I'm a big fan of readability - so I tend to just have a sequence of individually-innocent-looking expressions that I then combine. Of course, it depends how you define LINQ: if you mean query-syntax in C#, then I don't tend to go overboard... but if you mean meta-programming (i.e. C# code that creates a LINQ expression), I've got a few good examples:

  • Mads Torgersen demonstrates how to write a self-contained recursive lambda expression in LINQ to calculate (e.g.) a factorial:

    i => new Func<Func<int,int>,Func<int,int>>(fac => x => x == 0 ? 1 : x * fac(x
    - 1))(new SelfApplicable<Func<Func<Func<int,int>,Func<int,int>>,Func<int,int>
    >>(y => f => x => f(y(y)(f))(x))(y => f => x => f(y(y)(f))(x))(fac => x => x
    == 0 ? 1 : x * fac(x - 1)))(i)
    

    Mads notes:

    I can’t even figure out how to line break it so that it approaches readable, so I haven’t.

    Marc Gravell : Fascinating (the blog entry, that is - the lambda itself is eye-agonising...)

imap - how to validate that complete message was transferred?

Does IMAP protocol provide any way to validate / verify that complete message was transferred from the server to local client? i.e. is there any equivalent of ETag / MD5 or some other checksum?

From stackoverflow
  • The IMAP protocol will tell you how many octets are going to be transfered when you issue the FETCH command. This should enable you to verify the completeness of the message. However, there is no command (AFAIK) that would provide any kind of checksum/hash functionality.

Hide c# windows application source code

I wrote a windows application using C# .Net 2.0 and i want to do something which hide the source code, so when any one use refactor tool can't see the source code. I used dotfuscator but it just changed the function names but not all the source code.

UPDATE: I want to hide the source code, not because of hiding the key, but to hide how the code is working.

Thanks,

From stackoverflow
  • IL is by definition very expressive in terms of what remains in the body; you'll just have to either:

    • find a better (read: more expensive) obfuscator
    • keep the key source under your control (for example, via a web-service, so key logic is never at the client).
  • There are limits to the lengths obfuscation software can go to to hide the contents of methods, fundamentally changing the internals without affecting the correctness (and certainly performance) is extremely hard.

    It is notable that code with many small methods tends to become far harder to understand once obfuscated, especially when techniques for sharing names between methods that would appear to collide to the eye but not to the runtime are employed.

    Some obfuscators allow the generation of constructs which are not representable in any of the target languages, the set of all operations allowable in CIL for example is way more than that expressible through c# or even C++/CLI. However this often requires an explicit setting to enable (since it can cause problems). This can cause decompilers to fail, but some will just do their best and work around it (perhaps inlining the il it cannot handle).

    If you distribute the pdb's with the app then even more can inferred due to the additional symbols.

  • As soon as people get a hand on your binaries they can reverse-engineer it. It’s easier with languages that are compiled to bytecode (C# and Java) and it’s harder with languages that are compiled to CPU-specific binaries but it’s always possible. Face it.

  • Try SmartAssembly http://www.smartassembly.com/index.aspx

  • Well, the source code is yours and unless you explicitly provide it, youll perobably only be providing compiled binaries.

    Now, these compiled binaries are IL code. To prevent someone "decompiling" and reverse engineering your IL code back to source code, you'll need to obfuscate the IL code. This is done with a code obfuscator. There are many in the marketplace.

    You've already done this with dotfuscator, however, you say that it only changed the function names, not all the source code. It sounds like you're using the dotfuscator edition that comes with Visual Studio. This is effectively the "community edition" and only contains a subset of the functionality of the "professional edition". Please see this link for a comparison matrix of the features of the community edition and the professional edition.

    If you want more obfuscation of your code (specifically to protect against people using tools such as Reflector), you'll need the professional edition of Dotfuscator, or another code obfuscator product that contains similar functionality.

    Amr ElGarhy : from where i can download Dotfuscator Professional Edition?
    CraigTP : Well, the Professional Edition costs money, but you can get an evaluation version from http://www.preemptive.com/dotfuscator.html
  • i found this one as well http://www.eziriz.com/ , seams nice, but still testing

  • Just symbol renaming is not enough of a hindrance to reverse-engineering your app. You also need control flow obfuscation, string encryption, resource protection, meta data reduction, anti-reflector defenses, etc, etc. Try Crypto Obfuscator which supports all this and more.