Friday, May 6, 2011

Can my file (image) names be too long?

When outputting images from Photoshop that are over 31 characters I get a compatibility message? Is there a downside to making image names (or any filenames) too long?

I want to make sure my web app displays my images correctly in all major browsers, including mobile, and that my image names get picked up by Google for indexing.

For example, if I have a Ford Thunderbird that I am selling, ideally I'd like my image name to be nice and descriptive for both usability and rankings, ie ford_thunderbird_sports_car_large.jpg .. the large would be the file size, vs thumbnails...

however that's a longer filename that may cause some browsers to not see it..

anyone have ideas? what are best practices for 2009?

From stackoverflow
  • I think the best place to store those descriptive data would be the image's metadata (this should be possible to edit in Photoshop), that would be a way of making the filename shorter and still keeping the descriptions (you can still use some flags or abbreviations in the filename, though).

    EDIT: Here's a workaround for Photoshop to not give a warning. It seems that this is some Mac-specific thing.

    jim : never thought of that, but I know Google is looking for those keywords in the image filename.. i didnt realize though that that 31 char limit referred to Mac OS9..ancient anyway! thanks
  • I'm pretty sure the maximum file length in any modern OS is at least 255 characters. Here's a wikipedia link: Comparison of file systems

    As for the web, I doubt you'll hit these limits. You should be fine.

    jim : thanks, I'm not worrying about this anymore :)

OSGi SAT, how should we deal with activation failure?

The eclipse OSGi Service Activator Toolkit provides a framework that simplifies handling the dependencies between budles.

One can derive from org.eclipse.soda.sat.core.framework.BaseBundleActivator and over-ride (for example) the activate() method to do some spefic initialisation work.

The signature is protected void activate(){}

Which leads to the question: "what are we spposed to do if activate() fails?", suppose for some reason we cannot initialise correctly. I can't throw an exception, the method signatiure won't allow that.

From stackoverflow
  • It's still possible to throw RuntimeException and Error (And Exceptions that inherit these). (Remember that Error indicates serious problems that a reasonable application should not try to catch.)

    It would also seems like a good idea to output something to your logging facility.

    The alternative you choose is dependent on the situation; what the root cause of the failed activation is. If the cause is something abnormal, that should not happen during normal circumstances, an Error or RuntimeException (and ofcourse loggin) feels right.

    djna : I agree that emiting some diagnostics is a good idea. I'm not sure about the unchecked exceptions. In general, yes I could throw an unchecked exception. However is this valid in the context of this framework? I would expect the framwork to define the error handling "protocol" by specifying an exception to throw.
  • Throwing an RuntimeException or an Error in the activate() method does not help you if you are using Equinox (tested with org.eclipse.osgi_3.5.1.R35x_v20090827). Independent of what you are throwing the bundle will finally end up in state ACTIVE.

    I assume that this behavior is specific to Equinox (bug?) because from my understanding this violates the OSGi specs.

    djna : It does seem to be difficult to know exactly what to do in these cases. I believe that the SAT authors should explcitly define what we should do.

How do I create an SQL query that groups by value ranges

I would like to create a sql query that reports the percentage of results in a particular range. for instance

20% of the values between 10 to 20

40% of the values between 20 to 32.5

Server - MSSQL

From stackoverflow
  • GROUP BY CASE 
             WHEN VALUE >= 10 AND VALUE <= 20 THEN '20%'
             WHEN VALUE > 20 AND VALUE <= 32.5 THEN '40%' ELSE '0' END
    

    You need to cover all possible values, hence the ELSE 0. You'll probably want to do something a little different there, but it should give you a start.


    Based on Joel Gauvreau's comment:

    SUM(CASE WHEN VALUE >=10 AND VALUE <= 20 THEN 1.0 ELSE 0.0 END) / COUNT(*),
    SUM(CASE WHEN VALUE > 20 AND VALUE <= 32.5 THEN 1.0 ELSE 0.0 END) / COUNT(*)
    

    Or at the end of the query use the COMPUTE statement.

    Joel Gauvreau : I Think he meant the distribution of the values by range. 200 records where value is in the range between 10 and 20 would results what percentage of the total number of records...
    Joel Coehoorn : Ah, thanks. Updated my answer.
    Andomar : +1 best idea, but needs a cast from integer to float, and an extra ) for the sum on the second line
  • This will get you the count per range, you can easily determine the percentage from there:

    declare @ranges table (beginInclusive float, endExclusive float)
    insert @ranges (beginInclusive, endExclusive)
        select 10, 20
        union all select 20, 32.5
    
    select
        r.beginInclusive,
        r.endExclusive,
        count(*)
    from t join @ranges on t.RangedValue >= r.beginInclusive and t.RangedValue < r.endExclusive
    group by 
        r.beginInclusive,
        r.endExclusive
    
  • I would usually use a subquery and get rangecounts and join in the total to get the percentage. Something like:

    SELECT 
      RangeCount/CNT as Percentage,
      Range
    FROM 
    (
    SELECT
      Count(*) AS CNT
    FROM
      SomeTable
    ) AS Total
    LEFT JOIN 
    (
    SELECT
      CASE Val <= 10 then
           '0 up to 10'
      ELSE 
           CASE when Val <= 20
             '11 to 20'
           ELSE 
            '> 20'
           END
        END
      END AS Range,
      COUNT(*) AS RangeCount
    FROM 
       SomeTable
    GROUP BY
       Range
    ) AS RangeTotals
    
  • SELECT B.Description, Total = COUNT(*) / CONVERT(money, (SELECT COUNT(*) FROM Target T2))
    FROM Target T
    JOIN (
        SELECT  Description = '0 to 10', LBound = 0, UBound = 10 
        UNION ALL 
        SELECT Description = '10 to 20', LBound = 10, UBound = 20
    ) B ON T.Value >= LBound AND T.Value < B.UBound
    GROUP BY B.Description
    
  • Declare @1 as int
    Declare @2 as int
    Declare @TotalRows as int
    
    set @1 = (Select COUNT(id) FROM dbo.Table_1 WHERE id >= 10 and id <= 20)
    set @2 = (Select COUNT(id) FROM dbo.Table_1 WHERE id > 20 AND id <= 32.5);
    set @TotalRows = (Select Count(id) from dbo.Table_1);
    
    SELECT CAST(((@1 * 100)/@TotalRows) as nvarchar(32)) + '%', CAST(((@2 * 100)/@TotalRows) as nvarchar(32)) + '%';
    

    Little complicated, but that does work... i suppose...

    dbo.Table_1 only has 1 column, 'id' and it is of type int.

  • If it's something that you will be doing regularly, then you can create a table with the ranges and what constitutes those ranges. If not, you can set them up in a table variable or temporary table and join to that. It's basically JohnOpincar's solution, but with a table instead of a subquery.

    Also, in your example you list "10 to 20" and "20 to 32.5". Where is a row counted if it's exactly 20? You should probably make sure that your requirements are clear on that point before you deliver the final solution.

  • Joel's answer seems the best way to me. Posting to explain the query, and because the answer has an integer division sum/count which will return 1 or 0 instead of a percentage.

    For the 20 -> 32.5 range:

    select CAST(SUM(
        CASE WHEN 20 < field AND field <= 32.5 THEN 1 ELSE 0 END
        ) as float) / COUNT(*) * 100.0
    from table
    

    The case returns 1 when the value is in range. Because there's no group by clause, the sum adds the result of the case for every row in the table. Convert to float, divide by the number of rows =count(*), and you get the percentage.

    You can also write it like:

    select SUM(
        CASE WHEN 20 < field AND field <= 32.5 THEN 1.0 ELSE 0.0 END
        ) / COUNT(*) * 100
    from table
    

    Here the CASE will result in a float 1.0 instead of the integer 1.

popen() in C

I can run the following command

xwd -root | xwdtopnm | pnmtojpeg > screen.jpg

in a terminal under linux and it will produce a screenshot of my current screen.

I try to do the following with the code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   FILE *fpipe;
   char *command="xwd -root | xwdtopnm | pnmtojpeg";
   char line[256];

 if ( !(fpipe = (FILE*)popen(command,"r")) )
{  // If fpipe is NULL
   perror("Problems with pipe");
   exit(1);
 }

while ( fgets( line, sizeof line, fpipe))
{
  //printf("%s", line);
  puts(line);
}
pclose(fpipe);
}

then I compile and run the program ./popen > screen.jpg but the resulting file screen.jpg is unrecongizable. How can I do this so that I can pipe through my program?

From stackoverflow
  • Without testing your code I hav doubts that "xwd -root | xwdtopnm | pnmtojpeg" works as an argument for a C - Pipe.

    I wouldn't use a C program anyway for such a problem. Use a simple Bash script instead.

  • You shouldn't use fgets and puts for dealing with binary data. fgets will stop whenever it sees a newline. Worse, puts will output extra newlines and it will also stop whenever it runs into a \0. Use fread and fwrite instead.

    Laurence Gonsalves : Sorry, I meant fread and fwrite, not read and write. (just edited my answer)
  • The functions fgets and puts aren't intended to be used with binary data like image files. They should only be used with strings of text. In C, strings end with a null byte ('\0'). Since that's really just a zero, it might appear anywhere in a binary file. Let's say that line[] is filled with 256 characters of data. When you call puts, the function reads the array until it encounters a null byte then assumes it has reached the end of the string and stops. Since in a binary file a null byte might appear anywhere (and not just at the end of the array), the puts function could easily fail to print out sections of your data.

    If I were you, I'd research the fread and fwrite functions and use them instead. On a Linux machine, you should just be able to type man 3 fread to read documentation for both functions.

  • For those having this same problem, I ended up finally getting it working by using the Unix read/write system calls:

    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    
    //writes to an output file test.jpg directly
    int main()
    {
     FILE *fpipe;
     char *command="xset b off  && xwd -root | xwdtopnm 2> /dev/null | pnmtojpeg";
     char buff[256];
     size_t result_write;
     size_t result_read;
    
     if ( !(fpipe = (FILE*)popen(command,"r")) )
     {  // If fpipe is NULL
      perror("Problems with pipe");
      exit(1);
     }
    
     int dest_fd = open("test.jpg",  O_RDWR|O_TRUNC|O_CREAT, S_IRUSR|S_IWUSR );
     int fd = fileno(fpipe);
     while((result_read = read(fd, buff, sizeof(char)*256))>0){ 
      if(result_read < 0){
       perror("Problem while reading.\n");
       exit(1);
      }
      result_write = write(dest_fd, buff, sizeof(char)*256);
      if(result_write < 0){
       perror("Probelms writing to outputfile.\n");
       exit(1);
      } 
     }
     close(dest_fd);  
       pclose(fpipe);
    }
    
    ephemient : As long as you make sure not to perform buffered IO (fread, fscanf, fwrite, fprintf, ...) and unbuffered IO (read, write, ...) on the same file, this should be fine. Don't understand why you didn't just use fread and fwrite, though.

C++ constructor problem

#include <iostream>
using namespace std;

// This first class contains a vector and a scalar representing the size of the vector.
typedef class Structure1
{
 int N;
 double* vec;
public: 
 // Constructor and copy constructor:
 Structure1(int Nin);
 Structure1(const Structure1& structurein);
 // Accessor functions:
 int get_N() { return N; }
 double* get_vec() { return vec; }
 // Destructor:
 ~Structure1() { delete []vec; }
} Structure1;

Structure1::Structure1(int Nin)
{
 N = Nin;
 vec = new double [N];
 for (int i = 0; i < N; i++)
  {
   vec[i] = i;
  };
}

Structure1::Structure1(const Structure1& structurein)
{
 vec = new double[structurein.N];
 for(int i = 0; i < structurein.N; i++)
 {
  vec[i] = structurein.vec[i];
 };
}

// This class just contains the first structure.
typedef class Structure2
 {
  Structure1 structure;
 public:  
  // Constructor:
  Structure2(const Structure1& structurein) { structure = structurein; }

The error occurs here:

Line Location main.cpp:47: error: no matching function for call to 'Structure1::Structure1()'

  // Accessor Function:
  Structure1 get_structure() { return structure; }
  // Destructor:
  ~Structure2() {}
 } Structure2;

int main (int argc, char * const argv[])
{
 const int N = 100;
 Structure1 structure1(N);
 Structure2 structure2(structure1);

 return 0;
}

If anyone knows what's wrong, your help would be greatly appreciated. Thanks!

From stackoverflow
  • You need to use a member initializer in your Structure2 ctor.

    Structure2(const Structure1& structurein) : structure(structurein) {}
    

    It's trying to use a default constructor for your Structure1 member, and there isn't one.

  • Since you have declared a constructor for Structure2, the compiler refuses to create a default constructor for it which is needed in order to access members of the class like you do in this constructor:

      Structure2(const Structure1& structurein) { structure = structurein; }
    

    You should probably do:

    Structure2(const Structure1& structurein) : structure(structurein) {}
    
  • By the way, I think you need to fix the copy constructor:

    Structure1::Structure1(const Structure1& structurein)
    {
     ///!!!! Initialize N
     N = structurein.N;
    
     vec = new double[structurein.N];
     for(int i = 0; i < structurein.N; i++)
     {
      vec[i] = structurein.vec[i];
     };
    }
    
    ypsu : At the beginning you should make sure you are constructing the object from an another object, like if (this == &structurein) return; Otherwise your copy won't work, and also a memory leak we'll be there as well.
    ypsu : Ah, sorry,ignore my previous commentt, I mixed this this with the = operator! :)
    ypsu : Sorry for spamming, but you can still construct the object from the same object: new (&b) A(b); Calling placement new with the same address where as the object from which A is constructed is rare, maybe you can ignore this.

iPhone: What is Springboard? Do I need to care?

When creating iPhone apps in simulator, I sometimes see messages like "Springboard failed to launch application", etc.

What is Springboard? Are there things I should know about it as a developer?

From stackoverflow
  • Springboard is just the iPhone home screen application.

    This related question may help.

  • Springboard is the launcher application -- i.e. the one you see on the home screen with all the tiled app icons.

    I don't think there's anything more you really need to know about it.

  • Springboard is the iPhone emulator that your app runs within. If Springboard only periodically fails to launch your app, something's probably wrong with Springboard, but if your app won't launch at all, there's probably something wrong with your app (and if it was deployed on a real phone, wouldn't launch there, either).

What sort function is used in NSArray?

This is really a three-part question, but I've answered the first question myself:

I'm working on the iPhone, with many objects (up to 200) on the screen. Each object needs to look if it's overlapping other objects, and act accordingly. My original naive implementation was for each object to run through the list of each other object to check their bounding boxes (using CGRectInsersectsRect).

So my question (and answer) is what's a better method? My new implementation is to sort the array every frame using an insertion sort (since the data will be mostly sorted already) on the y-position of each object, then check only the nearest object on either side of the one searching, to see if it's in range vertically, then check horizontally.

First question: Is insertion sort the method I want to use for an array of objects that tend to move around randomly but only to a small extent so they mostly stay in order based on the last frame? Also: what sort algorithm does the NSArray use when I call

- sortedArrayUsingSelector:

I would sort of assume that it uses a quick sort, since it's the most useful in the general case. Does anybody know if I'm wrong? Does anybody know if I can change the sort method or if I will have to write my own sorting function?

Second question: is there a function for retrieving items from a sorted array using a binary search, rather than the naive approach that I assume is used by

- indexOfObject:

or would I have to write my own?

From stackoverflow
  • NSArray uses many different data structures internally depending on how many objects are in the array. See a Peter Ammon blog entry for more information. But basically this means you can't expect a certain kind of sort to happen. Sometimes it is worth it to write your own array implementation using C arrays so you can control the sorts yourself.

    There are definitely much faster ways to implement collision detection. Look into Bounding Volume Hierarchies like KD Trees or similar.

    As far as I know indexOfObject: is the only way, but it's potentially not as dumb as you think. Everything is hashable for NSDictionary so they can use some of those smarts in NSArray.

Cocoa: What NSTextView the insertion point is currently blinking in?

Hi!

Given an NSApp object (aka [NSApplication sharedApplication]), how can I get the currently active NSTextView, where the insertion point is blinking right now (if there is one)? :-)

I can go [[NSApp keyWindow] contentView] and try traversing the whole view hierarchy, but that seems too hard. Ideal code would be: [NSApp focusedTextView].

I tryed firstResponder for an app and a window, and also fieldEditor:forObject:, but this does not return anything interesting (at least, to me).

By the way, if anybody knows how to get the system wide current text view, that would be even cooler (Accessibility APIs won’t work: it won’t return a Cocoa NSTextView).

Thanks

From stackoverflow
  • The -firstResponder function returns the field editor. So if you want the real view you might need to check the first responder's delegate to get to it. Also see field editor for details.

    There is probably no way to get it system wide as a NSTextViews since that object is in general in a different process space.

    Ilya Birman : Thanks, but what if an app does not use field editor at all? For example, in Pages it returns null. Basically I need to find a current object that responds to selector setInsertionPointColor:. Anything else to try?
    Ilya Birman : Oh, I found that windows’s firstResponder itself usually responds to setInsertionPointColor:, but sometimes it doesn’t (like, in Mail.app it uses some kind of WebView to display message editor).
  • By the way, if anybody knows how to get the system wide current text view, that would be even cooler (Accessibility APIs won’t work: it won’t return a Cocoa NSTextView).

    Not possible. NSTextViews are per-process; you can't get a proxy to an NSTextView from another process without that other process serving it up through an NSConnection. You're just going to have to use Accessibility.

    On the bright side, using Accessibility means your app should (in theory) also work with Carbon apps that use MLTE/HITextView.

ASP.NET URL Routing with WebForms - Using the SiteMap

I'm trying to use Url Routing within my existing ASP.NET WebForms site. Thanks to: this link, I got it working. Now I'm trying to use a SiteMap along with my routing.

I have a page MyReport.aspx. It is in the SiteMap and accessing the page directly, works fine. I've added a route for /report/{param1}/{param2}. I was hoping the sitemap would resolve the route path (MyReport.aspx) instead of /report/{param1}/{param2}, but no dice.

I have seen examples of using the SiteMap with MVC, but this makes assumptions about having controllers and such, none of which exist with a standard webform.

The approach I'm trying now is to retrieve the actual page within a custom SiteMapProvider, but I'm not seeing a way to do this. Is there a way to get the actual ASPX page instead of the Url from the HttpContext?

Thanks, -Damien

From stackoverflow
  • Damien - I recently posted a sample that might be useful. Googling "asp.net routing sitemap" should get you there (only just joined SO so can't post link yet).

    Fyi you can use the SiteMap.SiteMapResolve event instead of creating a custom SiteMapProvider (for simple scenarios at least).

    Hope it helps!

Desktop Development : Remember Target After Losing Focus

Is it possible to take focus from another program to respond to an event, but then once the response has been handled, switch back to the previous program and restore the cursor where it was?

This sounds like a weird question, but think of it along the lines of

  1. User is typing in a text box in Program A.
  2. A window for Program B pops up and user presses a few buttons to confirm something.
  3. Program B returns control to Program A and restores the selection of the textbox.

If there is a complete C# solution, then great, but this sounds like it might require a little more effort than usual.

Any thoughts?

From stackoverflow
  • Personally, doing this could very likely result in the user selecting undesired values in the popup window. For example, someone is typing away in Word. Your application pops up a window, where hitting "Enter" selects a value ... such as the default button. Without wanting to, the user "selected" an incorrect value on your form.

    Windows itself tends to do this, and it's very annoying. Quickly double-clicking a desktop shortcut to open an application and then switching back to (for example) an e-mail before the app launches, will tend to remove focus from the focused e-mail window and put focus in the just-opened application, causing your e-mail text or keyboard strokes to go to the just-opened window.

  • In my experience windows programs work just this way. It often appears that they don't because the user is returning focus with a mouse-click, which itself resets the focus. If it's a winforms app you can probably do something with the lost focus/got focus events at the form level.

Javadoc like documentation for C#'s xml comments

I'm looking for something to turn my C# xml comments into documentation. I don't like chm's, nor msdn's look and feel. I love using the javadocs. They're easy to navigate, and everything is accessible. Is there a tool I can use to convert the comments in my code to a javadoc like look and feel.

Is there something that does this? I've tried sandcastle and it's various GUI's but they don't do what I want.

From stackoverflow

Where is documentation on the Microsoft Visual Studio C++ Name Mangling Scheme?

I am interested in finding either official or reverse engineered documentation detailing the name mangling scheme used by the Visual Studio C++ Compiler to translate C++ names into symbols in generated code.

I am aware that this may change between versions, and am most interested in the details for Visual Studio 2003, 2005 and 2008.

Of special interest is the handling of C++ operators, such as new, placement new, and new[]

From stackoverflow
  • Following link may be of interest to you.

    http://msdn.microsoft.com/en-us/library/ms681400(VS.85).aspx

  • Found a useful link, which also links to further useful information.

  • A serious community effort to uncover the decoration scheme: 1, 2, 3, 4, 5.

  • Thanks for the references, but I have to quibble - meaning it in good humour - about both "serious" and "community". When I wrote those pages, I should have liked very much to make a serious effort, but the pages remain marked just as sketches of how research might continue. Sadly, there is next to no community support for serious efforts at studying other people's software, for this or any other topic.

    In everyday practice, programmers rarely need to know the algorithm for decoration. To find how a particular C++ name gets decorated, they can use the compiler. To reverse a particular decoration, they can feed it to the CRT Library function __unDName. That's admittedly undocumented, but it has been there a long, long time. To use it these days is easy because Visual Studio comes with an UNDNAME.EXE tool.

Calendar control for cocoa touch

I'm want to create a CRM app for me just for fun and to learn more about Cocoa, because CRM application evolve based on a Calendar, I wonder where can I get that cool Calendar control that iCal has in the iPhone.

I can't see it in my Library and I'm using SDK 3.0 beta 5.

And by the way, where can I get a free/paid controls collection like there are so many for the .NET world?

alt text

From stackoverflow
  • Apple does not make the iPhone-style calendar UI part of the public API. You'll need to build your own calendar or contract it out.

    Wally Lawless : Wow, that sorta sucks doesn't it? You'd think they would want their developers to not have to worry about re-inventing this stuff.
    Alex Reynolds : Developers should file a feature request with Apple at http://bugreporter.apple.com. The more developers that ask for a UICalendar, the more likely we'll see one available.
  • This thread on the Apple Support forums confirms what Alex Reynolds says:

    No, does not exist (except in Apple's private library). I had to build one from scratch (actually I "outsourced" building the custom class to a Colorado iPhone development outfit via eLance) in order to develop my calendar-based app

    The only thing I could find was this, which is a iPhone calendar control. It doesn't look identical to Apple's one, but it's close (and would probably be a good starting point if you need it to look similar)

  • Late to the party, but this question is answered here:

    http://stackoverflow.com/questions/997779/is-there-any-ready-made-calendar-control-for-iphone-apps

    balexandre : Thank you! I just asked to close my question as well, even if I did asked first

Virtual DOM to Webpage

I'm working on a system that stores data in XML files. The data in the files can be converted into a generic DOM but not without some processing. I have been tasking with looking into how to do the web access story for this system. (FWIW, the existing code base is in .NET)

The system can be thought of as an XML in XML database for handling generally static but end-user-time defined XML schemes. I'm not sure what the model is exactly as that's another guy's job but the bit I'm working with will be seeing serializable DOM objects of some kind.

The intended model is that the end user will write a web front end that accesses data from our system. The things that jump out at me as options are:

  • Build a SOAP (or equivalent) service that can present the processed XML and let the web server run from that with XSL or whatever.
  • Same as the SOAP solution but with server side XSL for security and rendering so the web server needs only drop in the text.
  • Build an assembly to so a web server can process files in process.
  • ???

We would like the system to be simple and cross platform (something that can be uses from a presentation layer written using LAMP, WAMP, RoR, ASP, etc).

From stackoverflow
  • It sounds to me like you're either not asking the right questions, or you're using the wrong terminology (or both.) But maybe that's just me.

    "generic DOM" -- any XML file should be convertable into a DOM; if it can't be, it's not well-formed XML. The DOM is simply an in-memory representation of the XML. (Commonly, it's used to mean the DOM inside of a Web browser; but DOM models can be and are created on the server as well.)

    Cross-platform -- I don't know of any way to write presentation code that can be plugged into LAMP, WAMP, RoR, ASP, etc. Maybe this is possible, but it seems unlikely to me.

    My best guess about what you need is that it's pretty simple: Associate the XML file with a CSS Style Sheet, and let the Web browser format the XML for display to the user.

    If that's not the answer you're looking for, maybe you could start with a sample of the XML that you need to display, and a prototype that shows how you'd like it to be displayed?

    BCS : The on disk file is Valid XML, it's just not in a form that the end user will be willing to play with. After processing, you get a much cleaner DOM that is reasonable to work with.
    BCS : I explicitly DON'T want my code serving up content directly to the web. I want some sort of web presentation player processing it first. As to the sample/prototype bit, I need a general solution as the end user will be defining the bulk of the XML schema.
    Dan Breslau : But what does the end user do in "playing with" or "working with" the XML? Is it just for display in a browser, or does the user want to process the file with some additional business logic? What is the difference between the "unclean" and "clean" DOM formats that you're referring to?
    BCS : As to what the user does: "whatever they want" although I suspect that XSL applied at the right spot would cover most of it. As to the clean/unclean thing: lots of annotations and whatnot.
    Dan Breslau : @ 2nd comment ("I need a general solution...") Do you mean that the end-user presents you with an arbitrary XSD *at runtime*, and you need to serve up XML to match? That sounds like it would require semantic processing; I couldn't say what a generic solution would even look like. Please refine the question as much as you can.
    BCS : I don't need to map pre-existing data to later provided XSD. Clients will define schema and then data entered and accessed only based on that schema.

What are the differences between the different types of Compare in TFS

When you right click on a file and select "Compare...", you get a few different options:

  1. Changeset
  2. Date
  3. Label
  4. Latest Version
  5. Workspace Version

The first 3 are pretty self explanatory. But what is the difference between the latest version and workspace version? 4 seems like you are comparing the code on your machine to the latest version in TFS 5 - shouldnt this be just like (4)? (I thought it might allow you to compare against multiple workspaces, but the dialog doesnt seem to have an option to select a different works space.)

From stackoverflow
  • Latest Version refers to the last version that was committed to the TFS Source Control while Workspace version refers to the last checked-in version in your local workspace.

    So basically the Workspace version Compare will will compare the file(s) you are comparing with your checked in files. While the Lastest Version Compare will compare it against files that may have been checked in by someone else on your team.

    Rajah : So what happens if I have not checked in my code and I have never edited that file before. What does the workspace version compare against? (As I have no files checked in and I wish to check the file I currently have checked out and made edits to). Very confusing....
    Robert Kozak : It will compare your version with the clean version in TFS without any other checked in versions from when you last got latest.
  • The confusion between 4 and 5 mainly comes (for me) on what you think you're clicking on. When you click on the file in Source Control view or in Pending Changes, TFS treats it as if you're clicking on the file in source control that you last synched to, not the local file.

    Most of the time 4 probably won't be used as (I assume) you'll be synched to latest most of the time.

  • THe difference that I have found between Latest Version Workspace Version

    Latest version - compares your current code file with the most current code file on TFS server. (This includes all the changes made by your fellow code monkeys and checked back in since you checked out the file). This form of comparison will show differences only if you have multiple checkouts enabled.

    Workspace Version - compares your current code file against the code at the time that you had checked out the file. If you have multiple checkouts enabled and some of your fellow code monkeys have checked in changes - then, you use this option to see what you originally changed. You then will have to compare against the latest version to see if there will be any conflicts while you are checking in your code file.

What's going on with the lambda expression in this python function?

Why does this attempt at creating a list of curried functions not work?

def p(x, num):
    print x, num

def test():
    a = []
    for i in range(10):
        a.append(lambda x: p (i, x))
    return a

>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test

What's going on here?

A function that actually does what I expect the above function to do is:

import functools
def test2():
    a = []
    for i in range (10):
        a.append(functools.partial(p, i))
    return a


>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
From stackoverflow
  • In Python, variables created in loops and branches aren't scoped. All of the functions you're creating with lambda have a reference to the same i variable, which is set to 9 on the last iteration of the loop.

    The solution is to create a function which returns a function, thus scoping the iterator variable. This is why the functools.partial() approach works. For example:

    def test():
        def makefunc(i):
            return lambda x: p(i, x)
        a = []
        for i in range(10):
            a.append(makefunc(i))
        return a
    
    David : Got it. Thanks very much!
  • I asked a similar question, and got two answers. One basically the same as the accepted answer here, and the other which is less clear but slightly more succint.

    http://stackoverflow.com/questions/728356/dynamically-creating-a-menu-in-tkinter-lambda-expressions

    mataap : Which includes (and I finally understand now) the lambda x=x : ... hack.
  • Well you can also bind the i to an outer lambda for the lazy.

    def p(x, num):
        print x, num
    
    def test():
        a = []
        for i in range(10):
            a.append((lambda i :lambda x: p (i, x))(i))
        return a
    

lots of boolean flag inputs to a class

I have a dialog that displays various things depending on state of the application, security for the current user etc. I am currently passing in several boolean flags and then enabling and/or hiding UI components depending on these flags.Eg:

new MyDialog(showOptionsTable, allowFooInput, allowBarInput, isSuperUser)

Initially this started out as a couple of flags and that was fine. But now with changing requirements, it has evolved into an input of five boolean flags.

What is the best practices way of handling behavior like this? Is this something that I should subclass depending on how the dialog should look?

From stackoverflow
  • Once you get more than two or three flags, I would consider creating a class to store these settings to keep your design clean.

    Kapsh : Do you mean a java bean with properties?
    Chris Ballance : Yes, A Java Bean would work nicely for this
  • use the decorator pattern in order to dynamically adding behavior to your dialog

    Chris Ballance : +1 for giving a relevant OO pattern.
    OscarRyz : can you post sample pseudo for the decorator pattern?
    dfa : http://en.wikipedia.org/wiki/Decorator_pattern contains the classic example using a Window and WindowDecorator
    OscarRyz : Thanks for the link. Not I get the concept of the Decorater pattern, but I don't understand how to apply it here. :-/
    dfa : you can write a Decorator for each boolean: i.e. OptionTableDecorator, SuperUserDecorator, etc. This design allow you to add new behaviour to your original dialog dynamically, your booleans is translated to a chain of decorator, that is much more simpler to maintain. Hope it helps :)
  • Set it up so MyDialog(false, false, .....) is the expected default behaviour. (ie: The most common case should take all false. You may need to reverse the semantics of the flags.)

    Now, define constants:

    OPTION1 = 1
    OPTION2 = 2
    OPTION3 = 4
    OPTION4 = 8
    ...
    

    Change the method to take an int options parameter

    public void MyDialog(int options) ...
    

    Now call it:

    MyDialog(OPTION1 | OPTION3)  // enable Opt1, opt2)
    

    inside the method:

    if (options & OPTION1) // use Option 1 config.
    

    etc.

    chris : That being said, refactoring and subclassing might very well be a better option.
    Michael Myers : I'd prefer an enum instead of raw ints.
    chris : Yeah, but keep it simple stupid -- That's just a prettification.
    Michael Myers : Prettification, and less bug-prone.
    Zack : yes. This is more of an old-school C way of doing it.
    Joachim Sauer : This might be the canonical way in C, but it's definitely a code smell in Java. At least *I* would criticize it in a code review. I don't want my API designers to require our API users to do bit manipulation for simply selecting a few options.
  • If the GUI depends on the state of the app ( where one state leads to another ) You can take a look at the State pattern. Where each new state will be handled by a different object and you can code whether the flags should go or no.

    ie.

    abstract class State { 
          public abstract boolean [] getFlags();
          public abstract State next();
     }
     class InitialState extends State  { 
          public boolean [] getFlags() {
              return new boolean [] { true, true, false, false, false };
          }
          public State next() { return new MediumState(); }
     }     
     class MediumState extends State { 
         public boolean [] getFlags() { 
             return new boolean[] { false, false, true, true, false };
         }
         public State next() { return new FinalState(); }
     }
     class Final extends State { 
         public boolean [] getFlags() { 
             return new boolean[]{false, false, false, false, true };
         }
         public State next() { return null;}
      }
    

    And the show your dialog using this states

    new MyDialog(showOptionsTable, new InitialState() );
    

    ....

    When the state of the application changes, you change the State object.

    public void actionPerfomed( ActionEvent e ) { 
        this.state = state.next();
        repaint();
     }
    

    To paint the sections of your dialog you query the state:

      if( state.getFlags()[SECURITY] ) { 
          /// show security stuff
      } if ( state.getFlags()[VIEW_ONLY] ) { 
          // enable/disable stuff 
      } ....
    

    You can go a step further ant let the State define what is presented.

    abstract class State { 
          public abstract JComponent getComponent();
          public abstract State next();
     }
    

    So each state shows a different section:

     Dialog.this.setContentPane( state.getComponent() );
    
    Zack : This would result in an exponential number of states being created when more check boxes are added. State pattern would probably be better if this portion of the code were unlikely to increase in the number of states. However, this doesn't seem to be the case.
  • Create a class to hold your configuration options:

    public class LayoutConfig
    {
        public boolean showOptionsTable = true;
        public boolean allowFooInput = true;
        public boolean allowBarInput = true;
        public boolean isSuperUser = true;
    }
    
    ...
    
    LayoutConfig config = new LayoutConfig();
    config.showOptionsTable = false;
    
    new MyDialog(config);
    

    This approach makes it easy to add new options without changes your interface. It will also enable you to add non-boolean options such as dates, numbers, colors, enums...

  • To build on Ben Noland answer, you could define some options as enum, then have a varargs constructor:

    class MyDialog {
       enum DialogOptions {
          SHOW_OPTIONS_TABLE, ALLOW_FOO_INPUT, ALLOW_BAR_INPUT, IS_SUPER_USER
       }
       public MyDialog(DialogOptions ...options) { ... }
    }
    
    ...
    new MyDialog(DialogOptions.ALLOW_FOO_INPUT, DialogOptions.IS_SUPER_USER);
    
    Kapsh : I suppose I should look into varargs considering that these options might change in the near future.
  • As with many things, "it depends".

    1. Ben Noland suggested a class to hold configuration options. This is doable, but favor immutability, and optionally use the builder pattern. Because booleans are built-in types, writing a small builder will really help people understand the code. If you compare this to MyDialog(true, true, ...) you know what I mean:

      Options.allowThis().allowThat().build()

    2. Chris suggested bit fields, but as some of the commenters point out, bit fields are evil because of many reasons outlined in Josh Bloch's Effective Java. Basically they are hard to debug and error prone (you can pass in any int and it will still compile). So if you go this route, use real enums and EnumSet.

    3. If you can reasonably subclass (or compose), meaning that you usually only use a couple of combinations of all the booleans, then do that.
    Kapsh : +1 Good summary!
    Rob : Don't understand why this was downvoted; I'd probably agree that Enum and an EnumSet are the way to go here.
  • I have found that this kind of thing becomes MUCH more readable if I use enums for the boolean choices.

    public enum ShowOptionsTable { YES, NO }
    public enum AllowFooInput { YES, NO }
    public enum AllowBarInput { YES, NO }
    public enum IsSuperUser { YES, NO }
    
    new MyDialog(ShowOptionsTable.YES, AllowFooInput.NO, AllowBarInput.YES,
                 IsSuperUser.NO);
    

    With enums like this, usage of code with a lot of boolean parameters becomes easy to understand. Also, since you are using objects rather than booleans as parameters, you have use other patterns to easily refactor things later if you want, to use a decorator or a facade or some other pattern.

  • I prefer flagged enums to a settings class if the parameters are all going to be boolean. If you can't guarantee that in the future though it would be better safe than sorry though. Here's another implementation for flags:

    [Flags]
    public enum LayoutParams
    {  
        OptionsTable = 1,  
        FooInput = 2,  
        BarInput = 4,  
        SuperUser = 8,
    }
    
    public MyDialog(LayoutParams layoutParams)
    {
        if (layoutParams & LayoutParams.OptionsTable)
        { /* ... Do Stuff ... */ }
    }
    
    public static MyDialog CreateBasic()
    {
        return new MyDialog(LayoutParams.OptionsTable | LayoutParams.BarInput);
    }
    
    Michael Myers : In Java, it would be `return new MyDialog(EnumSet.of(LayoutParams.OptionsTable, LayoutParams.BarInput));`
    Jeremy : You're right. I think in C#, apparently.
  • Depending on just how different your display is going to be, you might consider subclassing your display class (i.e. MyDialogSuperUser or somesuch). You need to consider just how orthogonal the inputs to your dialog class are and how to express that orthogonality.

  • I have a favorite way to handle this, but it's not valid for all use cases. If the booleans are not entirely independent (say there are some invalid combinations of booleans, or combinations of booleans are reached through identifiably scenarios.) I create an enum for the state and then define a constructor that holds onto the flags:

    public enum status {
        PENDING(false,false),
        DRAFT(true,false),
        POSTED(false,true),
        ;
        public boolean isSent;
        public boolean isReceived;
        status(boolean isSent, boolean isReceived) {
            this.isSent = isSent;
            this.isReceived = isReceived;
        }
    }
    

    The advantage to a piece of code like this is that you can construct your enum constants relatively tersely, but still allow code to only care about one particular aspect of state. For example:

    //I want to know specifically what the state is
    if (article.state == status.PENDING)
    // Do something
    
    //I really only care about whether or not it's been sent
    if (article.state.isSent)
    // Do something
    
    //I want to do something specific for all possible states
    switch(article.state)
    // A string of case statements
    

    Another plus is that illegal states are never reached if you define your enum well:

    if (article.state.isReceived && !article.state.isSent) {
    // This block can never execute ever.
    }
    

    Granted, it's not all the time that there's a logical relationship among booleans, but I do recommend mapping them out. If a subset of booleans have logical relationships, it might be worth breaking those off into an enum.

Jquery $(this) Child Selector

I'm using this on a page:

jQuery('.class1 a').click( function() {
  if ($(".class2").is(":hidden")) {
    $(".class2").slideDown("slow");
  } else {
    $(".class2").slideUp();
  }
});

With a structure in the page later that goes like this:

<div class="class1">
<a href="...">text</a>
<div class="class2">text</div>
</div>

This is working fine, except when you have multipule class1/class2 sets like so:

<div class="class1">
<a href="...">text</a>
<div class="class2">text</div>
</div>
<div class="class1">
<a href="...">text</a>
<div class="class2">text</div>
</div>
<div class="class1">
<a href="...">text</a>
<div class="class2">text</div>
</div>

How do I change the initial jquery code so that it only effects the class 2 under the current class1 that was clicked? I've tried variations of what was recommended on this page but havent gotten it to work yet: http://stackoverflow.com/questions/306583/jquery-this-selector-and-children

From stackoverflow
  • The best way with the HTML you have would probably be to use the next function, like so:

    var div = $(this).next('.class2');
    

    Since the click handler is happening to the <a>, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent and children. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:

    var div = $(this).parent().children('.class2');
    

    If you wanted the "search" to not be limited to immediate children, you would use find instead of children in the example above.

    Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div> tags are going to have those classes, make the selector be div.class1, div.class2.

  • http://www.visualjquery.com/ Traversing--> Finding--> Children

  • In the click event "this" is the a tag that was clicked

    jQuery('.class1 a').click( function() {
       var divToSlide = $(this).parent().find(".class2");
       if (divToSlide.is(":hidden")) {
          divToSlide.slideDown("slow");
       } else {
          divToSlide.slideUp();
       }
    });
    

    There's multiple ways to get to the div though you could also use .siblings, .next etc

  • This is a lot simpler with .slideToggle():

    jQuery('.class1 a').click( function() {
      $(this).next('.class2').slideToggle();
    });
    

    EDIT: made it .next instead of .siblings

    http://www.mredesign.com/demos/jquery-effects-1/

    You can also add cookie's to remember where you're at...

    http://c.hadcoleman.com/2008/09/jquery-slide-toggle-with-cookie/

Socket Server Disconnect and Reconnect Buffer Error?

I'm using the following TCP Sockets Server/Client example: http://www.codeguru.com/Csharp/Csharp/cs_network/sockets/article.php/c8781/

I'm also using the following CryptoStream example: http://www.obviex.com/samples/Encryption.aspx

Problem: Both Server and Clients communicate perfectly until I Stop the Server socket, wait a minute or so, then start the Server socket. Sometimes but not always I recieve a base64 error in the Encryption.aspx on line 'Convert.FromBase64String(cipherText);'...

I know there is incorrect / corrupted data in the buffer probably left-over from stopping the socket. Then the new data comes in and the error occurs.

Q. Will clearing the 'class SocketPacket; solve this issue?

Q. How do I clear the 'class SocketPacketsocketBuffer'?

Other suggestions are greatly appreciated..

From stackoverflow
  • One of the things you may find is happening is that one of the sockets is not being closed down properly. The thing with sockets is that you need to make sure they get correctly closed or you set the server socket to reuse the address.

    Try tcpview from sysinternals to view the status of sockets. You can also use netstat to view the status of the sockets.

Data Sanitization in PHP

Can someone recommend an up to date library for data Sanitization in PHP ?

I am looking for a library that proposes a set of functions for data sanitization. Email validation/sanitization (remove those %0A, \r...), strip htlm (stripslashes(htmlentities), remove script, SQL injection … any form of exploit related to data submitted by users.

CakePHP sanitization class (not the "framework") looks nice.. ?

From stackoverflow
  • Check out PHP Filter

    Török Gábor : Or directly the official manual entry of PHP's Data Filtering: http://www.php.net/filter
  • CakePHP is a framework, not a sanitation library.

    It's probably easier to just write your own sanitization functions.

    Joe Philllips : Fair enough, I didn't follow the link.
  • Zend Filter, Zend Filter Input and Zend_Validate

  • There is no such thing as data sanitization. Data isn't dangerous on it self - it's the context in which it's used, that makes it safe or unsafe. That means that it is pointless to try and validate/sanitize data on entry. Instead, your should escape it properly on output. See also my answer here.

    rick : If you need to allow markup in input, but you don't want xss attacks, then it's not "pointless" to validate/sanitize data on entry. Why would you store dangerous input?
    troelskn : I consider that an edge case and I'd use HtmlPurifier for that.
  • For filtering out xss attacks when you need to preserve html markup: htmlpurifier

    If you don't need to keep html markup, you can use htmlspecialchars or htmlentities