{"user":"8","tags":["c#","winforms","type-conversion","decimal","opacity"],"questionId":4,"creationDate":"2008-07-31T21:42:52Z","title":"While applying opacity to a form should we use a decimal or double value?","acceptedAnswerId":7,"type":"question","body":"I want to use a track-bar to change a form's opacity. This is my code: decimal trans = trackBar1.Value / 5000; this.Opacity = trans; When I build the application, it gives the following error: Cannot implicitly convert type 'decimal' to 'double'. I tried using trans and double but then the control doesn't work. This code worked fine in a past VB.NET project. "} {"user":"9","tags":["html","css","css3","internet-explorer-7"],"questionId":6,"creationDate":"2008-07-31T22:08:08Z","title":"Percentage width child element in absolutely positioned parent on Internet Explorer 7","acceptedAnswerId":31,"type":"question","body":"I have an absolutely positioned div containing several children, one of which is a relatively positioned div. When I use a percentage-based width on the child div, it collapses to '0' width on Internet Explorer 7, but not on Firefox or Safari. If I use pixel width, it works. If the parent is relatively positioned, the percentage width on the child works. Is there something I'm missing here? Is there an easy fix for this besides the pixel-based width on the child? Is there an area of the CSS specification that covers this? "} {"user":"9","questionId":4,"creationDate":"2008-07-31T22:17:57Z","answerId":7,"type":"answer","body":"An explicit cast to double isn't necessary. double trans = (double)trackBar1.Value / 5000.0; Identifying the constant as 5000.0 (or as 5000d) is sufficient: double trans = trackBar1.Value / 5000.0; double trans = trackBar1.Value / 5000d; "} {"user":"1","tags":["c#",".net","datetime"],"questionId":9,"creationDate":"2008-07-31T23:40:59Z","title":"Calculate age in C#","acceptedAnswerId":1404,"type":"question","body":"Given a DateTime representing a person's birthday, how do I calculate their age in years? "} {"user":"1","tags":["c#","datetime","time","datediff","relative-time-span"],"questionId":11,"creationDate":"2008-07-31T23:55:37Z","title":"Calculate relative time in C#","acceptedAnswerId":1248,"type":"question","body":"Given a specific DateTime value, how do I display relative time, like: 2 hours ago 3 days ago a month ago "} {"user":"1","questionId":11,"creationDate":"2008-07-31T23:56:41Z","answerId":12,"type":"answer","body":"Well, here's how we do it on Stack Overflow. var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks); double delta = Math.Abs(ts.TotalSeconds); if (delta < 60) { return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\"; } if (delta < 120) { return \"a minute ago\"; } if (delta < 2700) // 45 * 60 { return ts.Minutes + \" minutes ago\"; } if (delta < 5400) // 90 * 60 { return \"an hour ago\"; } if (delta < 86400) // 24 * 60 * 60 { return ts.Hours + \" hours ago\"; } if (delta < 172800) // 48 * 60 * 60 { return \"yesterday\"; } if (delta < 2592000) // 30 * 24 * 60 * 60 { return ts.Days + \" days ago\"; } if (delta < 31104000) // 12 * 30 * 24 * 60 * 60 { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1 ? \"one month ago\" : months + \" months ago\"; } int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1 ? \"one year ago\" : years + \" years ago\"; Suggestions? Comments? Ways to improve this algorithm? "} {"user":"9","tags":["javascript","html","browser","timezone","timezoneoffset"],"questionId":13,"creationDate":"2008-08-01T00:42:38Z","title":"Determine a User's Timezone","type":"question","body":"Is there any standard way for a Web Server to be able to determine a user's timezone within a web page? Perhaps from a HTTP header or part of the user-agent string? "} {"user":"11","tags":[".net","math"],"questionId":14,"creationDate":"2008-08-01T00:59:11Z","title":"Difference between Math.Floor() and Math.Truncate()","type":"question","body":"What is the difference between Math.Floor() and Math.Truncate() in .NET? "} {"user":"2","tags":["c#","linq","web-services",".net-3.5"],"questionId":16,"creationDate":"2008-08-01T04:59:33Z","title":"Filling a DataSet or DataTable from a LINQ query result set","acceptedAnswerId":12446,"type":"question","body":"How do you expose a LINQ query as an ASMX web service? Usually, from the business tier, I can return a typed DataSet or DataTable which can be serialized for transport over ASMX. How can I do the same for a LINQ query? Is there a way to populate a typed DataSet or DataTable via a LINQ query? public static MyDataTable CallMySproc() { string conn = \"...\"; MyDatabaseDataContext db = new MyDatabaseDataContext(conn); MyDataTable dt = new MyDataTable(); // execute a sproc via LINQ var query = from dr in db.MySproc().AsEnumerable select dr; // copy LINQ query resultset into a DataTable -this does not work ! dt = query.CopyToDataTable(); return dt; } How can I get the result set of a LINQ query into a DataSet or DataTable? Alternatively, is the LINQ query serializeable so that I can expose it as an ASMX web service? "} {"user":"2","tags":["mysql","database","binary-data","data-storage"],"questionId":17,"creationDate":"2008-08-01T05:09:55Z","title":"Binary Data in MySQL","acceptedAnswerId":26,"type":"question","body":"How do I store binary data in MySQL? "} {"user":"phpguy","questionId":17,"creationDate":"2008-08-01T05:12:44Z","answerId":18,"type":"answer","body":"For a table like this: CREATE TABLE binary_data ( id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY, description CHAR(50), bin_data LONGBLOB, filename CHAR(50), filesize CHAR(50), filetype CHAR(50) ); Here is a PHP example: // Example php script to demonstrate the storing of binary files into // an sql database. More information can be found at http://www.phpbuilder.com/ ?> Store binary data into SQL Database This file has the following Database ID: $id\"; mysql_close(); } else { // else show the form to submit new data: ?>
\" enctype=\"multipart/form-data\"> File Description:

File to upload/store in database:

"} {"user":"13","tags":["performance","algorithm","language-agnostic","unix","pi"],"questionId":19,"creationDate":"2008-08-01T05:21:22Z","title":"What is the fastest way to get the value of π?","acceptedAnswerId":531,"type":"question","body":"Solutions are welcome in any language. :-) I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically I'm using ways that don't involve using #defined constants like M_PI, or hard-coding the number in. The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable; I've included it as a baseline to compare the other versions against. In my tests, with built-ins, the 4 * atan(1) version is fastest on GCC 4.2, because it auto-folds the atan(1) into a constant. With -fno-builtin specified, the atan2(0, -1) version is fastest. Here's the main testing program (pitimes.c): #include #include #include #define ITERS 10000000 #define TESTWITH(x) { \\ diff = 0.0; \\ time1 = clock(); \\ for (i = 0; i < ITERS; ++i) \\ diff += (x) - M_PI; \\ time2 = clock(); \\ printf(\"%s\\t=> %e, time => %f\\n\", #x, diff, diffclock(time2, time1)); \\ } static inline double diffclock(clock_t time1, clock_t time0) { return (double) (time1 - time0) / CLOCKS_PER_SEC; } int main() { int i; clock_t time1, time2; double diff; /* Warmup. The atan2 case catches GCC's atan folding (which would * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin * is not used. */ TESTWITH(4 * atan(1)) TESTWITH(4 * atan2(1, 1)) #if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__)) extern double fldpi(); TESTWITH(fldpi()) #endif /* Actual tests start here. */ TESTWITH(atan2(0, -1)) TESTWITH(acos(-1)) TESTWITH(2 * asin(1)) TESTWITH(4 * atan2(1, 1)) TESTWITH(4 * atan(1)) return 0; } And the inline assembly stuff (fldpi.c), noting that it will only work for x86 and x64 systems: double fldpi() { double pi; asm(\"fldpi\" : \"=t\" (pi)); return pi; } And a build script that builds all the configurations I'm testing (build.sh): #!/bin/sh gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too, because the optimisations are different), I've also tried switching the order of the tests around. The atan2(0, -1) version still comes out top every time, though. "} {"user":"13","questionId":9,"creationDate":"2008-08-01T08:57:27Z","answerId":21,"type":"answer","body":"Many years ago, to provide an age calculator gimmick on my website, I wrote a function to calculate age to a fraction. This is a quick port of that function to C# (from the PHP version). I'm afraid I haven't been able to test the C# version, but hope you enjoy all the same! (Admittedly this is a bit gimmicky for the purposes of showing user profiles on Stack Overflow, but maybe readers will find some use for it. :-)) double AgeDiff(DateTime date1, DateTime date2) { double years = date2.Year - date1.Year; /* * If date2 and date1 + round(date2 - date1) are on different sides * of 29 February, then our partial year is considered to have 366 * days total, otherwise it's 365. Note that 59 is the day number * of 29 Feb. */ double fraction = 365 + (DateTime.IsLeapYear(date2.Year) && date2.DayOfYear >= 59 && (date1.DayOfYear < 59 || date1.DayOfYear > date2.DayOfYear) ? 1 : 0); /* * The only really nontrivial case is if date1 is in a leap year, * and date2 is not. So let's handle the others first. */ if (DateTime.IsLeapYear(date2.Year) == DateTime.IsLeapYear(date1.Year)) return years + (date2.DayOfYear - date1.DayOfYear) / fraction; /* * If date2 is in a leap year, but date1 is not and is March or * beyond, shift up by a day. */ if (DateTime.IsLeapYear(date2.Year)) { return years + (date2.DayOfYear - date1.DayOfYear - (date1.DayOfYear >= 59 ? 1 : 0)) / fraction; } /* * If date1 is not on 29 February, shift down date1 by a day if * March or later. Proceed normally. */ if (date1.DayOfYear != 59) { return years + (date2.DayOfYear - date1.DayOfYear + (date1.DayOfYear > 59 ? 1 : 0)) / fraction; } /* * Okay, here date1 is on 29 February, and date2 is not on a leap * year. What to do now? On 28 Feb in date2's year, the ``age'' * should be just shy of a whole number, and on 1 Mar should be * just over. Perhaps the easiest way is to a point halfway * between those two: 58.5. */ return years + (date2.DayOfYear - 58.5) / fraction; } "} {"user":"17","questionId":9,"creationDate":"2008-08-01T12:07:19Z","answerId":22,"type":"answer","body":"The best way that I know of because of leap years and everything is: DateTime birthDate = new DateTime(2000,3,1); int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D); Hope this helps. "} {"user":"22","tags":["mysql","database","triggers"],"questionId":24,"creationDate":"2008-08-01T12:12:19Z","title":"Throw an error in a MySQL trigger","acceptedAnswerId":49,"type":"question","body":"If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table? "} {"user":"23","tags":["c++","c","sockets","mainframe","zos"],"questionId":25,"creationDate":"2008-08-01T12:13:50Z","title":"How to use the C socket API in C++ on z/OS","acceptedAnswerId":1443907,"type":"question","body":"I've been having issues getting the C sockets API to work properly in C++. Specifically, although I am including sys/socket.h, I still get compile time errors telling me that AF_INET is not defined. Am I missing something obvious, or could this be related to the fact that I'm doing this coding on z/OS and my problems are much more complicated? Update: Upon further investigation, I discovered that there is an #ifdef that I'm hitting. Apparently z/OS isn't happy unless I define which \"type\" of sockets I'm using with: #define _OE_SOCKETS Now, I personally have no idea what this _OE_SOCKETS is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works? "} {"user":"48","questionId":17,"creationDate":"2008-08-01T12:16:22Z","answerId":26,"type":"answer","body":"The answer by phpguy is correct but I think there is a lot of confusion in the additional details there. The basic answer is in a BLOB data type / attribute domain. BLOB is short for Binary Large Object and that column data type is specific for handling binary data. See the relevant manual page for MySQL. "} {"user":"17","questionId":11,"creationDate":"2008-08-01T12:17:19Z","answerId":27,"type":"answer","body":"@jeff IMHO yours seems a little long. However it does seem a little more robust with support for \"yesterday\" and \"years\". But in my experience when this is used the person is most likely to view the content in the first 30 days. It is only the really hardcore people that come after that. So that is why I usually elect to keep this short and simple. This is the method I am currently using on one of my websites. This only returns a relative day, hour, time. And then the user has to slap on \"ago\" in the output. public static string ToLongString(this TimeSpan time) { string output = String.Empty; if (time.Days > 0) output += time.Days + \" days \"; if ((time.Days == 0 || time.Days == 1) && time.Hours > 0) output += time.Hours + \" hr \"; if (time.Days == 0 && time.Minutes > 0) output += time.Minutes + \" min \"; if (output.Length == 0) output += time.Seconds + \" sec\"; return output.Trim(); } "} {"user":"19","questionId":13,"creationDate":"2008-08-01T12:19:17Z","answerId":29,"type":"answer","body":"There are no HTTP headers that will report the clients timezone so far although it has been suggested to include it in the HTTP specification. If it was me, I would probably try to fetch the timezone using clientside JavaScript and then submit it to the server using Ajax or something. "} {"user":"13","questionId":25,"creationDate":"2008-08-01T12:22:40Z","answerId":30,"type":"answer","body":"I've had no trouble using the BSD sockets API in C++, in GNU/Linux. Here's the sample program I used: #include int main() { return AF_INET; } So my take on this is that z/OS is probably the complicating factor here, however, because I've never used z/OS before, much less programmed in it, I can't say this definitively. :-P "} {"user":"maclema","questionId":6,"creationDate":"2008-08-01T12:22:51Z","answerId":31,"type":"answer","body":"The parent div needs to have a defined width, either in pixels or as a percentage. In Internet Explorer 7, the parent div needs a defined width for child percentage divs to work correctly. "} {"user":"13","questionId":14,"creationDate":"2008-08-01T12:26:39Z","answerId":33,"type":"answer","body":"Math.Floor rounds down, Math.Ceiling rounds up, and Math.Truncate rounds towards zero. Thus, Math.Truncate is like Math.Floor for positive numbers, and like Math.Ceiling for negative numbers. Here's the reference. For completeness, Math.Round rounds to the nearest integer. If the number is exactly midway between two integers, then it rounds towards the even one. Reference. See also: Pax Diablo's answer. Highly recommended! "} {"user":"maclema","tags":["actionscript-3","flex","bytearray"],"questionId":34,"creationDate":"2008-08-01T12:30:57Z","title":"Unloading a ByteArray in Actionscript 3","type":"question","body":"How do I forcefully unload a ByteArray from memory in ActionScript 3? I have tried (without success): byteArray.length = 0; byteArray = new ByteArray(); And for ( var i:int=0; i < byteArray.length; i++ ) { byteArray[i] = null; } "} {"user":"32","tags":["sql","sql-server","datatable","rdbms"],"questionId":36,"creationDate":"2008-08-01T12:35:56Z","title":"Check for changes to an SQL Server table?","acceptedAnswerId":352,"type":"question","body":"How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is .NET and C#. I'd like to be able to support any SQL Server 2000 SP4 or newer. My application is a bolt-on data visualization for another company's product. Our customer base is in the thousands, so I don't want to have to put in requirements that we modify the third-party vendor's table at every installation. By \"changes to a table\" I mean changes to table data, not changes to table structure. Ultimately, I would like the change to trigger an event in my application, instead of having to check for changes at an interval. The best course of action given my requirements (no triggers or schema modification, SQL Server 2000 and 2005) seems to be to use the BINARY_CHECKSUM function in T-SQL. The way I plan to implement is this: Every X seconds run the following query: SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); And compare that against the stored value. If the value has changed, go through the table row by row using the query: SELECT row_id, BINARY_CHECKSUM(*) FROM sample_table WITH (NOLOCK); And compare the returned checksums against stored values. "} {"user":"23","questionId":25,"creationDate":"2008-08-01T12:36:00Z","answerId":37,"type":"answer","body":"Sure I can post a test app. #include int main() { return AF_INET; } Compile/Link Output: cxx -Wc,xplink -Wl,xplink -o inet_test inet.C \"./inet.C\", line 5.16: CCN5274 (S) The name lookup for \"AF_INET\" did not find a declaration. CCN0797(I) Compilation failed for file ./inet.C. Object file not created. A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any #ifdef statements. I have however noticed it contains a the following: #ifdef __cplusplus extern \"C\" { #endif which encapsulates basically the whole file. Not sure if it matters. "} {"user":"33","tags":["c#",".net","vb.net","timer"],"questionId":39,"creationDate":"2008-08-01T12:43:11Z","title":"Reliable timer in a console application","acceptedAnswerId":45,"type":"question","body":"I am aware that in .NET there are three timer types (see Comparing the Timer Classes in the .NET Framework Class Library). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable. The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy. The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything so the application closes. I tried adding a while true loop, but then the main thread is too busy when the timer does go off. "} {"user":"37","tags":["php","plugins","architecture","hook"],"questionId":42,"creationDate":"2008-08-01T12:50:18Z","title":"Best way to allow plugins for a PHP application","acceptedAnswerId":77,"type":"question","body":"I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface. How does one go about writing 'hooks' into their code so that plugins can attach to specific events? "} {"user":"35","questionId":39,"creationDate":"2008-08-01T12:55:42Z","answerId":44,"type":"answer","body":"Consider using a ManualResetEvent to block the main thread at the end of its processing, and call Reset() on it once the timer's processing has finished. If this is something that needs to run constantly, consider moving this into a service process instead of a console app. "} {"user":"39","questionId":39,"creationDate":"2008-08-01T12:56:37Z","answerId":45,"type":"answer","body":"You can use something like Console.ReadLine() to block the main thread, so other background threads (like timer threads) will still work. You may also use an AutoResetEvent to block the execution, then (when you need to) you can call Set() method on that AutoResetEvent object to release the main thread. Also ensure that your reference to Timer object doesn't go out of scope and garbage collected. "} {"user":"40","tags":["html","form-submit","html-form","submit-button"],"questionId":48,"creationDate":"2008-08-01T13:01:17Z","title":"Multiple submit buttons in an HTML form","acceptedAnswerId":31910,"type":"question","body":"Let's say you create a Wizard in an HTML form. One button goes back, and one goes forward. Since the back button appears first in the markup when you press Enter it will use that button to submit the form. Example:
What I would like to do, is get to decide which button is used to submit the form when a user presses Enter. That way, when you press Enter the Wizard will move to the next page, not the previous. Do you have to use tabindex to do this? "} {"user":"43","questionId":24,"creationDate":"2008-08-01T13:02:51Z","answerId":49,"type":"answer","body":"Here is one hack that may work. It isn't clean, but it looks like it might work: Essentially, you just try to update a column that doesn't exist. "} {"user":"17","questionId":36,"creationDate":"2008-08-01T13:07:52Z","answerId":51,"type":"answer","body":"Why don't you want to use triggers? They are a good thing if you use them correctly. If you use them as a way to enforce referential integrity that is when they go from good to bad. But if you use them for monitoring, they are not really considered taboo. "} {"user":"23","questionId":34,"creationDate":"2008-08-01T13:08:59Z","answerId":52,"type":"answer","body":"Have a look at this article http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html IANA actionscript programmer, however the feeling I'm getting is that, because the garbage collector might not run when you want it to. Hence http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/ So I'd recommend trying out their collection code and see if it helps private var gcCount:int; private function startGCCycle():void{ gcCount = 0; addEventListener(Event.ENTER_FRAME, doGC); } private function doGC(evt:Event):void{ flash.system.System.gc(); if(++gcCount > 1){ removeEventListener(Event.ENTER_FRAME, doGC); setTimeout(lastGC, 40); } } private function lastGC():void{ flash.system.System.gc(); } "} {"user":"34","questionId":34,"creationDate":"2008-08-01T13:08:59Z","answerId":53,"type":"answer","body":"(I'm not positive about this, but...) AS3 uses a non-deterministic garbage collection. Which means that unreferenced memory will be freed up whenever the runtime feels like it (typically not unless there's a reason to run, since it's an expensive operation to execute). This is the same approach used by most modern garbage collected languages (like C# and Java as well). Assuming there are no other references to the memory pointed to by byteArray or the items within the array itself, the memory will be freed at some point after you exit the scope where byteArray is declared. You can force a garbage collection, though you really shouldn't. If you do, do it only for testing... if you do it in production, you'll hurt performance much more than help it. To force a GC, try (yes, twice): flash.system.System.gc(); flash.system.System.gc(); You can read more here. "} {"user":"39","questionId":48,"creationDate":"2008-08-01T13:10:16Z","answerId":56,"type":"answer","body":"Give your submit buttons same name like this: When the user presses enter and the Request goes to server, you can check the value for submitButton on your server-side code which contains a collection of form name/value pairs. For example in classic ASP: If Request.Form(\"submitButton\") = \"Previous Page\" Then ' Code for Previous Page ElseIf Request.Form(\"submitButton\") = \"Next Page\" Then ' Code for Next Page End If Reference: Using multiple submit buttons on a single form "} {"user":"37","questionId":48,"creationDate":"2008-08-01T13:14:30Z","answerId":58,"type":"answer","body":"Would it be possible for you to change the previous button type into a button like this: Now the Next button would be the default, plus you could also add the default attribute to it so that your browser will highlight it like so: Hope that helps. "} {"user":"45","tags":["c#","linq",".net-3.5"],"questionId":59,"creationDate":"2008-08-01T13:14:33Z","title":"How do I get a distinct, ordered list of names from a DataTable using LINQ?","acceptedAnswerId":43110,"type":"question","body":"Let's say I have a DataTable with a Name column. I want to have a collection of the unique names ordered alphabetically. The following query ignores the order by clause. var names = (from DataRow dr in dataTable.Rows orderby (string)dr[\"Name\"] select (string)dr[\"Name\"]).Distinct(); Why does the orderby not get enforced? "} {"user":"41","questionId":34,"creationDate":"2008-08-01T13:14:40Z","answerId":60,"type":"answer","body":"Unfortunately when it comes to memory management in Flash/actionscript there isn't a whole lot you can do. ActionScript was designed to be easy to use (so they didn't want people to have to worry about memory management) The following is a workaround, instead of creating a ByteArray variable try this. var byteObject:Object = new Object(); byteObject.byteArray = new ByteArray(); ... //Then when you are finished delete the variable from byteObject delete byteObject.byteArray; Where byteArray is a dynamic property of byteObject, you can free the memory that was allocated for it. "} {"user":"maclema","tags":["office-2007","file-type"],"questionId":61,"creationDate":"2008-08-01T13:17:20Z","title":"Office 2007 File Type, Mime Types and Identifying Characters","type":"question","body":"Where can I find a list of the MIME types and identifying characters for Office 2007 files? I have an upload form that is restricting uploads based on extension and identifying characters, but I cannot seem to find the Office 2007 MIME types. "} {"user":"45","questionId":59,"creationDate":"2008-08-01T13:18:37Z","answerId":62,"type":"answer","body":"The problem is that the Distinct operator does not grant that it will maintain the original order of values. So your query will need to work like this var names = (from DataRow dr in dataTable.Rows select (string)dr[\"Name\"]).Distinct().OrderBy( name => name ); "} {"user":"35","questionId":61,"creationDate":"2008-08-01T13:20:44Z","answerId":65,"type":"answer","body":"Office 2007 MIME Types for IIS .docm, application/vnd.ms-word.document.macroEnabled.12 .docx, application/vnd.openxmlformats-officedocument.wordprocessingml.document .dotm, application/vnd.ms-word.template.macroEnabled.12 .dotx, application/vnd.openxmlformats-officedocument.wordprocessingml.template .potm, application/vnd.ms-powerpoint.template.macroEnabled.12 .potx, application/vnd.openxmlformats-officedocument.presentationml.template .ppam, application/vnd.ms-powerpoint.addin.macroEnabled.12 .ppsm, application/vnd.ms-powerpoint.slideshow.macroEnabled.12 .ppsx, application/vnd.openxmlformats-officedocument.presentationml.slideshow .pptm, application/vnd.ms-powerpoint.presentation.macroEnabled.12 .pptx, application/vnd.openxmlformats-officedocument.presentationml.presentation .xlam, application/vnd.ms-excel.addin.macroEnabled.12 .xlsb, application/vnd.ms-excel.sheet.binary.macroEnabled.12 .xlsm, application/vnd.ms-excel.sheet.macroEnabled.12 .xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .xltm, application/vnd.ms-excel.template.macroEnabled.12 .xltx, application/vnd.openxmlformats-officedocument.spreadsheetml.template "} {"user":"17","tags":["linq",".net-3.5"],"questionId":66,"creationDate":"2008-08-01T13:20:46Z","title":"Paging a collection with LINQ","acceptedAnswerId":4521,"type":"question","body":"How do you page through a collection in LINQ given that you have a startIndex and a count? "} {"user":"17","questionId":66,"creationDate":"2008-08-01T13:22:04Z","answerId":68,"type":"answer","body":"It is very simple with the Skip and Take extension methods. var query = from i in ideas select i; var paggedCollection = query.Skip(startIndex).Take(count); "} {"user":"49","questionId":19,"creationDate":"2008-08-01T13:37:59Z","answerId":71,"type":"answer","body":"Here's a general description of a technique for calculating pi that I learnt in high school. I only share this because I think it is simple enough that anyone can remember it, indefinitely, plus it teaches you the concept of \"Monte-Carlo\" methods -- which are statistical methods of arriving at answers that don't immediately appear to be deducible through random processes. Draw a square, and inscribe a quadrant (one quarter of a semi-circle) inside that square (a quadrant with radius equal to the side of the square, so it fills as much of the square as possible) Now throw a dart at the square, and record where it lands -- that is, choose a random point anywhere inside the square. Of course, it landed inside the square, but is it inside the semi-circle? Record this fact. Repeat this process many times -- and you will find there is a ratio of the number of points inside the semi-circle versus the total number thrown, call this ratio x. Since the area of the square is r times r, you can deduce that the area of the semi circle is x times r times r (that is, x times r squared). Hence x times 4 will give you pi. This is not a quick method to use. But it's a nice example of a Monte Carlo method. And if you look around, you may find that many problems otherwise outside your computational skills can be solved by such methods. "} {"user":"25","tags":["ruby","rdoc"],"questionId":72,"creationDate":"2008-08-01T13:38:27Z","title":"How do I add existing comments to RDoc in Ruby?","type":"question","body":"I want to format my existing comments as 'RDoc comments' so they can be viewed using ri. What are some recommended resources for starting out using RDoc? "} {"user":"13","questionId":25,"creationDate":"2008-08-01T13:40:16Z","answerId":73,"type":"answer","body":"@Jax: The extern \"C\" thing matters, very very much. If a header file doesn't have one, then (unless it's a C++-only header file), you would have to enclose your #include with it: extern \"C\" { #include // include other similarly non-compliant header files } Basically, anytime where a C++ program wants to link to C-based facilities, the extern \"C\" is vital. In practical terms, it means that the names used in external references will not be mangled, like normal C++ names would. Reference. "} {"user":"50","questionId":42,"creationDate":"2008-08-01T13:44:35Z","answerId":76,"type":"answer","body":"I believe the easiest way would be to follow Jeff's own advice and have a look around existing code. Try looking at Wordpress, Drupal, Joomla and other well known PHP-based CMS's to see how their API hooks look and feel. This way you can even get ideas you may have not thought of previously to make things a little more rubust. A more direct answer would be to write general files that they would \"include_once\" into their file that would provide the usability they would need. This would be broken up into categories and NOT provided in one MASSIVE \"hooks.php\" file. Be careful though, because what ends up happening is that files that they include end up having more and more dependencies and functionality improves. Try to keep API dependencies low. I.E fewer files for them to include. "} {"user":"40","questionId":42,"creationDate":"2008-08-01T13:46:00Z","answerId":77,"type":"answer","body":"You could use an Observer pattern. A simple functional way to accomplish this: Output: This is my CRAZY application 4 + 5 = 9 4 * 5 = 20 Notes: For this example source code, you must declare all your plugins before the actual source code that you want to be extendable. I've included an example of how to handle single or multiple values being passed to the plugin. The hardest part of this is writing the actual documentation which lists what arguments get passed to each hook. This is just one method of accomplishing a plugin system in PHP. There are better alternatives, I suggest you check out the WordPress Documentation for more information. Sorry, it appears underscore characters are replaced by HTML entities by Markdown? I can re-post this code when this bug gets fixed. Edit: Nevermind, it only appears that way when you are editing "} {"user":"55","questionId":4,"creationDate":"2008-08-01T13:53:06Z","answerId":78,"type":"answer","body":"It sounds like this.Opacity is a double value, and the compiler doesn't like you trying to cram a decimal value into it. "} {"user":"58","tags":["eclipse","svn","aptana","subclipse"],"questionId":79,"creationDate":"2008-08-01T13:56:33Z","title":"Getting Subclipse in Aptana to work with the newest release of Subversion","acceptedAnswerId":62853,"type":"question","body":"The version of Subclipse (1.2.4) currently available through Aptana's automatic Plugins Manager does not work with the newest version of Subversion. I see on the Subclipse website however that they have 1.4.2 out for Eclipse. So I added a new remote update site to my Update manager. When I tried to install it, it told me I needed Mylyn 3.0.0. So after much searching I found Mylyn 3.0.0 and added another new remote update site to my update manager. Then when I tried to install that, it told me I needed org.eclipse.ui 3.3.0 or equivalent. Looking at the configuration details for Aptana, it looks like it is built against eclipse 3.2.2. Does anyone know if there is a way to upgrade the version of Eclipse Aptana that is built against to 3.3.0? Or if there is some other way to get Subclipse to work with the very newest version of Subversion? I know this isn't necessarily a \"programming\" question, but I hope it's ok since it's highly relevant to the programming experience. "} {"user":"26","tags":["flex","actionscript-3","air"],"questionId":80,"creationDate":"2008-08-01T13:57:07Z","title":"SQLStatement.execute() - multiple queries in one statement","acceptedAnswerId":124,"type":"question","body":"I've written a database generation script in SQL and want to execute it in my Adobe AIR application: Create Table tRole ( roleID integer Primary Key ,roleName varchar(40) ); Create Table tFile ( fileID integer Primary Key ,fileName varchar(50) ,fileDescription varchar(500) ,thumbnailID integer ,fileFormatID integer ,categoryID integer ,isFavorite boolean ,dateAdded date ,globalAccessCount integer ,lastAccessTime date ,downloadComplete boolean ,isNew boolean ,isSpotlight boolean ,duration varchar(30) ); Create Table tCategory ( categoryID integer Primary Key ,categoryName varchar(50) ,parent_categoryID integer ); ... I execute this in Adobe AIR using the following methods: public static function RunSqlFromFile(fileName:String):void { var file:File = File.applicationDirectory.resolvePath(fileName); var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ) var strSql:String = stream.readUTFBytes(stream.bytesAvailable); NonQuery(strSql); } public static function NonQuery(strSQL:String):void { var sqlConnection:SQLConnection = new SQLConnection(); sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH)); var sqlStatement:SQLStatement = new SQLStatement(); sqlStatement.text = strSQL; sqlStatement.sqlConnection = sqlConnection; try { sqlStatement.execute(); } catch (error:SQLError) { Alert.show(error.toString()); } } No errors are generated, however only tRole exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there a way to call multiple queries in one statement? "} {"user":"41","questionId":34,"creationDate":"2008-08-01T14:03:22Z","answerId":81,"type":"answer","body":"I believe you have answered your own question... System.totalMemory gives you the total amount of memory being \"used\", not allocated. It is accurate that your application may only be using 20mb, but it has 5mb that is free for future allocations. I'm not sure if the Adobe docs would shed light on the way that it manages memory... "} {"user":"51","questionId":36,"creationDate":"2008-08-01T14:06:28Z","answerId":82,"type":"answer","body":"Have a DTS job (or a job that is started by a windows service) that runs at a given interval. Each time it is run, it gets information about the given table by using the system INFORMATION_SCHEMA tables, and records this data in the data repository. Compare the data returned regarding the structure of the table with the data returned the previous time. If it is different, then you know that the structure has changed. Example query to return information regarding all of the columns in table ABC (ideally listing out just the columns from the INFORMATION_SCHEMA table that you want, instead of using *select ** like I do here): select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'ABC' You would monitor different columns and INFORMATION_SCHEMA views depending on how exactly you define \"changes to a table\". "} {"user":"60","questionId":16,"creationDate":"2008-08-01T14:10:55Z","answerId":84,"type":"answer","body":"If you use a return type of IEnumerable, you can return your query variable directly. "} {"user":"59","tags":["php","sql","database","flat-file"],"questionId":85,"creationDate":"2008-08-01T14:19:52Z","title":"Flat File Databases","acceptedAnswerId":154,"type":"question","body":"What are your best practices around creating flat file database structures in PHP? A lot of the more mature PHP flat file frameworks I see out there attempt to implement SQL-like query syntax, which is over the top for my purposes in most cases (I would just use a database at that point). Are there any elegant tricks out there to get good performance and features with the small code overhead one would want by taking on this problem in the first place? "} {"user":"39","questionId":4,"creationDate":"2008-08-01T14:23:28Z","answerId":86,"type":"answer","body":"A more generic answer for the generic question \"Decimal vs Double?\": Decimal for monetary calculations to preserve the precision, Double for scientific calculations that do not get affected by small differences. Since Double is a type which is native to the CPU (internal representation is stored in base 2), calculations made with Double perform better then Decimal (which is represented in base 10 internally). "} {"user":"59","questionId":85,"creationDate":"2008-08-01T14:26:22Z","answerId":87,"type":"answer","body":"One framework I'm considering would be for a blogging platform. Since just about any possible view of data you would want would be sorted by date, I was thinking about this structure: One directory per content node: ./content/YYYYMMDDHHMMSS/ Subdirectories of each node including /tags /authors /comments As well as simple text files in the node directory for pre- and post-rendered content and the like. This would allow a simple PHP glob() call (and probably a reversal of the result array) to query on just about anything within the content structure: glob(\"content/*/tags/funny\"); Would return paths including all articles tagged \"funny\". "} {"user":"61","tags":["linux","winapi","visual-c++","unix","timer"],"questionId":88,"creationDate":"2008-08-01T14:36:18Z","title":"Is gettimeofday() guaranteed to be of microsecond resolution?","acceptedAnswerId":98,"type":"question","body":"So I find myself porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux). I have implemented QueryPerformanceCounter by giving the uSeconds since the process start up: BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount) { gettimeofday(¤tTimeVal, NULL); performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec); performanceCount->QuadPart *= (1000 * 1000); performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec); return true; } This, coupled with QueryPerformanceFrequency() giving a constant 1000000 as the frequency, works well on my machine, giving me a 64 bit variable that contains uSeconds since the program's start up. So is this portable? I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however. "} {"user":"Ted Dziuba","questionId":79,"creationDate":"2008-08-01T14:41:01Z","answerId":89,"type":"answer","body":"I've had problems with JavaHL in Eclipse Ganymede, when it worked fine in Eclipse Europa. I'm not sure how Aptana is different, but try either upgrading JavaHL or switching to the pure-java SVNKit implementation within the Subclipse config. "} {"user":"58","tags":["svn","tortoisesvn","branch","branching-and-merging"],"questionId":90,"creationDate":"2008-08-01T14:41:24Z","title":"Good branching and merging tutorials for TortoiseSVN?","type":"question","body":"Are there any really good tutorials explaining branching and merging with Apache Subversion? All the better if it's specific to TortoiseSVN client. "} {"user":"61","questionId":90,"creationDate":"2008-08-01T14:45:37Z","answerId":92,"type":"answer","body":"Version Control with Subversion A very good resource for source control in general. Not really TortoiseSVN specific, though. "} {"user":"25","questionId":88,"creationDate":"2008-08-01T14:46:53Z","answerId":93,"type":"answer","body":"From my experience, and from what I've read across the internet, the answer is \"No,\" it is not guaranteed. It depends on CPU speed, operating system, flavor of Linux, etc. "} {"user":"2089740","questionId":88,"creationDate":"2008-08-01T14:53:47Z","answerId":98,"type":"answer","body":"Maybe. But you have bigger problems. gettimeofday() can result in incorrect timings if there are processes on your system that change the timer (ie, ntpd). On a \"normal\" linux, though, I believe the resolution of gettimeofday() is 10us. It can jump forward and backward and time, consequently, based on the processes running on your system. This effectively makes the answer to your question no. You should look into clock_gettime(CLOCK_MONOTONIC) for timing intervals. It suffers from several less issues due to things like multi-core systems and external clock settings. Also, look into the clock_getres() function. "} {"user":"25","questionId":88,"creationDate":"2008-08-01T14:55:08Z","answerId":99,"type":"answer","body":" The actual resolution of gettimeofday() depends on the hardware architecture. Intel processors as well as SPARC machines offer high resolution timers that measure microseconds. Other hardware architectures fall back to the system’s timer, which is typically set to 100 Hz. In such cases, the time resolution will be less accurate. I obtained this answer from High Resolution Time Measurement and Timers, Part I "} {"user":"59","questionId":85,"creationDate":"2008-08-01T14:58:15Z","answerId":100,"type":"answer","body":"That's true. serialize() can be pretty useful for that as well. I think the trick to coming up with a viable system is finding some way to index the data nodes without killing yourself with complexity. "} {"user":"72","questionId":13,"creationDate":"2008-08-01T15:11:59Z","answerId":103,"type":"answer","body":"Javascript is the easiest way to get the client's local time. I would suggest using an XMLHttpRequest to send back the local time, and if that fails, fall back to the timezone detected based on their IP address. As far as geolocation, I've used MaxMind GeoIP on several projects and it works well, though I'm not sure if they provide timezone data. It's a service you pay for and they provide monthly updates to your database. They provide wrappers in several web languages. "} {"user":"39","tags":[".net","performance","memory-leaks","com-interop"],"questionId":104,"creationDate":"2008-08-01T15:12:34Z","title":"Anatomy of a \"Memory Leak\"","acceptedAnswerId":112,"type":"question","body":"In .NET perspective: What is a Memory Leak? How can you determine whether your application leaks? What are the effects? How can you prevent a memory leak? If your application has memory leak, does it go away when the process exits or is killed? Or do memory leaks in your application affect other processes on the system even after process completion? And what about unmanaged code accessed via COM Interop and/or P/Invoke? I have some answers for these questions myself, but they are incomplete. What do you think? "} {"user":"61","questionId":104,"creationDate":"2008-08-01T15:19:25Z","answerId":107,"type":"answer","body":"I guess in a managed environment, a leak would be you keeping an unnecessary reference to a large chunk of memory around. "} {"user":"72","tags":["windows","svn","64bit"],"questionId":108,"creationDate":"2008-08-01T15:22:29Z","title":"Best Subversion clients for Windows Vista (64bit)","acceptedAnswerId":111,"type":"question","body":"I've been using TortoiseSVN in a Windows environment for quite some time. It seems very feature-complete and nicely integrated into the Windows shell, and more importantly, it's fairly painless to teach to colleagues with little or no experience with source control. However, since we have moved to Windows Vista 64bit, Tortoise has been very buggy and has seemed to cause lots of explorer.exe abnormalities and crashes. This has happened both with older versions of the software and the latest version (1.5.1 build 13563). I was curious if anyone has suggestions for other Subversion clients that will run on Windows (specifically Vista 64bit). Developers here use a variety of text editors so using Visual Studio or Dreamweaver for SVN is not ideal. I have heard great things about Cornerstone, and would love something similar for Windows if it exists. I'm correlating the Vista/explorer problems with Tortoise because they normally occur when I'm using the functionality in Tortoise. Sometimes bringing up the \"merge\" screen will cause the GUI to start acting very strange and eventually hang or crash. I did not see 1.5.2 -- I'm installing now, maybe that will fix some of my issues. "} {"user":"71","tags":["c#","sql","vb.net","ascii","hex"],"questionId":109,"creationDate":"2008-08-01T15:23:05Z","title":"Decoding T-SQL CAST in C#/VB.NET","acceptedAnswerId":2585,"type":"question","body":"Recently our site has been deluged with the resurgence of the Asprox botnet SQL injection attack. Without going into details, the attack attempts to execute SQL code by encoding the T-SQL commands in an ASCII encoded BINARY string. It looks something like this: DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x44004500...06F007200%20AS%20NVARCHAR(4000));EXEC(@S);-- I was able to decode this in SQL, but I was a little wary of doing this since I didn't know exactly what was happening at the time. I tried to write a simple decode tool, so I could decode this type of text without even touching SQL Server. The main part I need decoded is: CAST(0x44004500...06F007200 AS NVARCHAR(4000)) I've tried all of the following commands with no luck: txtDecodedText.Text = System.Web.HttpUtility.UrlDecode(txtURLText.Text); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Convert.FromBase64String(txtURLText.Text)); What is the proper way to translate this encoding without using SQL Server? Is it possible? I'll take VB.NET code since I'm familiar with that too. Okay, I'm sure I'm missing something here, so here's where I'm at. Since my input is a basic string, I started with just a snippet of the encoded portion - 4445434C41 (which translates to DECLA) - and the first attempt was to do this... txtDecodedText.Text = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(txtURL.Text)); ...and all it did was return the exact same thing that I put in, since it converted each character into is byte. I realized that I need to parse each two characters into a byte manually since I don't know of any methods yet that will do that, so now my little decoder looks something like this: while (!boolIsDone) { bytURLChar = byte.Parse(txtURLText.Text.Substring(intParseIndex, 2)); bytURL[intURLIndex] = bytURLChar; intParseIndex += 2; intURLIndex++; if (txtURLText.Text.Length - intParseIndex < 2) { boolIsDone = true; } } txtDecodedText.Text = Encoding.UTF8.GetString(bytURL); Things look good for the first couple of pairs, but then the loop balks when it gets to the \"4C\" pair and says that the string is in the incorrect format. Interestingly enough, when I step through the debugger and to the GetString method on the byte array that I was able to parse up to that point, I get \",-+\" as the result. How do I figure out what I'm missing - do I need to do a \"direct cast\" for each byte instead of attempting to parse it? "} {"user":"36","questionId":104,"creationDate":"2008-08-01T15:23:33Z","answerId":110,"type":"answer","body":"I will concur with Bernard as to in .net what a mem leak would be. You could profile your application to see its memory use, and determine that if its managing a lot of memory when it should not be you could say it has a leak. In managed terms I will put my neck on the line to say it does go away once the process is killed/removed. Unmanaged code is its own beast and if a leak exists within it, it will follow a standard mem. leak definition. "} {"user":"146270","questionId":108,"creationDate":"2008-08-01T15:27:23Z","answerId":111,"type":"answer","body":"I have been using the 64Bit version of TortoiseSVN for ages and I have never had issues with it on Windows 64Bit or Vista 64Bit. I am currently not aware of any other similiar SVN clients that do work on Vista. Is it possible the problem could lie within the configuration of TortoiseSVN or even the installation of Vista? Is the problem occurring on Vista native or SP 1? "} {"user":"34","questionId":104,"creationDate":"2008-08-01T15:28:12Z","answerId":112,"type":"answer","body":"The best explanation I've seen is in Chapter 7 of the free Foundations of Programming ebook. Basically, in .NET a memory leak occurs when referenced objects are rooted and thus cannot be garbage collected. This occurs accidentally when you hold on to references beyond the intended scope. You'll know that you have leaks when you start getting outofmemoryexceptions or your memory usage goes up beyond what you'd expect (perfmon has nice memory counters). Understanding .NET's memory model is your best way of avoiding it. Specifically, understanding how the garbage collector works and how references work (again, I refer you to chapter 7 of the ebook). Also, be mindful of common pitfalls, probably the most common being events. If object A registered to an event on object B, then object A will stick around until object B disappears because B holds a reference to A. The solution is to unregister your events when you're done. Of course, a good memory profile will let you see your object graphs and explore the nesting/referencing of your objects to see where references are coming from and what root object is responsible (red-gate ants profile, JetBrains dotMemory, memprofiler are really good choices, or you can use the text-only windbg and sos, but I'd strongly recommend a commercial/visual product unless you're a real guru). I believe unmanaged code is subject to typical memory leaks of unamanged code, except that references shared between the two are managed by the garbage collector. Could be wrong about this last point. "} {"user":"60","questionId":108,"creationDate":"2008-08-01T15:32:11Z","answerId":113,"type":"answer","body":"I'll second Diago's answer. I use TortoiseSVN on Vista x64 pretty heavily. I did upgrade directly from an older version to 1.5.2 though, and never used 1.5.1. Have you tried 1.5.2? "} {"user":"17","questionId":108,"creationDate":"2008-08-01T15:32:42Z","answerId":114,"type":"answer","body":"TortoiseSVN in combination with VisualSVN for Visual Studio. "} {"user":"58","questionId":108,"creationDate":"2008-08-01T15:34:43Z","answerId":116,"type":"answer","body":"I too get explorer crashes in Vista (I'm not in the 64Bit version though). I'm using Vista Super Saijen (or whatever they are calling the most expensive version). I'm not having any bugs with Tortoise. My explorer does, however, crash about every other day (sometimes multiple times a day if it's having an \"off\" day). I'm not positive it's being caused by TortoiseSVN though. From what I hear, the explorer just crashes a lot in Vista... Have you tried uninstalling Tortoise and using Windows for a day or two and seeing if it still crashes? Do you restart your computer at least once a day (It seems the longer I go between restarts, the worse the crashes get)? "} {"user":"83","tags":["sql","asp.net","xml","sitemap"],"questionId":120,"creationDate":"2008-08-01T15:50:08Z","title":"ASP.NET Site Maps","type":"question","body":"Has anyone got experience creating SQL-based ASP.NET site-map providers? I've got the default XML file web.sitemap working properly with my Menu and SiteMapPath controls, but I'll need a way for the users of my site to create and modify pages dynamically. I need to tie page viewing permissions into the standard ASP.NET membership system as well. "} {"user":"78","tags":["java","xml","csv","data-conversion"],"questionId":123,"creationDate":"2008-08-01T16:08:52Z","title":"Java lib or app to convert CSV to XML file?","acceptedAnswerId":183,"type":"question","body":"Is there an existing application or library in Java which will allow me to convert a CSV data file to XML file? The XML tags would be provided through possibly the first row containing column headings. "} {"user":"26","questionId":80,"creationDate":"2008-08-01T16:09:47Z","answerId":124,"type":"answer","body":"I wound up using this. It is a kind of a hack, but it actually works pretty well. The only thing is you have to be very careful with your semicolons. : D var strSql:String = stream.readUTFBytes(stream.bytesAvailable); var i:Number = 0; var strSqlSplit:Array = strSql.split(\";\"); for (i = 0; i < strSqlSplit.length; i++){ NonQuery(strSqlSplit[i].toString()); } "} {"user":"58","tags":["java","php","oop","theory"],"questionId":126,"creationDate":"2008-08-01T16:10:30Z","title":"How would you access Object properties from within an object method?","acceptedAnswerId":127,"type":"question","body":"What is the \"purist\" or \"correct\" way to access an object's properties from within an object method that is not a getter/setter method? I know that from outside of the object you should use a getter/setter, but from within would you just do: Java: String property = this.property; PHP: $property = $this->property; or would you do: Java: String property = this.getProperty(); PHP: $property = $this->getProperty(); Forgive me if my Java is a little off, it's been a year since I programmed in Java... EDIT: It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though... "} {"user":"35","questionId":126,"creationDate":"2008-08-01T16:13:47Z","answerId":127,"type":"answer","body":"This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called). "} {"user":"26","questionId":126,"creationDate":"2008-08-01T16:19:04Z","answerId":128,"type":"answer","body":"It depends on how the property is used. For example, say you have a student object that has a name property. You could use your Get method to pull the name from the database, if it hasn't been retrieved already. This way you are reducing unnecessary calls to the database. Now let's say you have a private integer counter in your object that counts the number of times the name has been called. You may want to not use the Get method from inside the object because it would produce an invalid count. "} {"user":"48","tags":["mysql","sql-server","csv","sql-server-2005","bcp"],"questionId":129,"creationDate":"2008-08-01T16:22:42Z","title":"How to export data from SQL Server 2005 to MySQL","type":"question","body":"I've been banging my head against SQL Server 2005 trying to get a lot of data out. I've been given a database with nearly 300 tables in it and I need to turn this into a MySQL database. My first call was to use bcp but unfortunately it doesn't produce valid CSV - strings aren't encapsulated, so you can't deal with any row that has a string with a comma in it (or whatever you use as a delimiter) and I would still have to hand write all of the create table statements, as obviously CSV doesn't tell you anything about the data types. What would be better is if there was some tool that could connect to both SQL Server and MySQL, then do a copy. You lose views, stored procedures, trigger, etc, but it isn't hard to copy a table that only uses base types from one DB to another... is it? Does anybody know of such a tool? I don't mind how many assumptions it makes or what simplifications occur, as long as it supports integer, float, datetime and string. I have to do a lot of pruning, normalising, etc. anyway so I don't care about keeping keys, relationships or anything like that, but I need the initial set of data in fast! "} {"user":"59","questionId":123,"creationDate":"2008-08-01T16:31:43Z","answerId":133,"type":"answer","body":"This may be too basic or limited of a solution, but couldn't you do a String.split() on each line of the file, remembering the result array of the first line to generate the XML, and just spit each line's array data out with the proper XML elements padding each iteration of a loop? "} {"user":"71","tags":[".net","database","xsd"],"questionId":134,"creationDate":"2008-08-01T16:33:38Z","title":"XSD DataSets and ignoring foreign keys","acceptedAnswerId":206,"type":"question","body":"I have a pretty standard table set-up in a current application using the .NET XSD DataSet and TableAdapter features. My contracts table consists of some standard contract information, with a column for the primary department. This column is a foreign key to my Departments table, where I store the basic department name, id, notes. This is all setup and functioning in my SQL Server. When I use the XSD tool, I can drag both tables in at once and it auto detects/creates the foreign key I have between these two tables. This works great when I'm on my main page and am viewing contract data. However, when I go to my administrative page to modify the department data. I typically do something like this: Dim dtDepartment As New DepartmentDataTable() Dim taDepartment As New DepartmentTableAdapter() taDepartment.Fill(dtDepartment) However, at this point an exception is thrown saying to the effect that there is a foreign key reference broken here, I'm guessing since I don't have the Contract DataTable filled. How can I fix this problem? I know I can simply remove the foreign key from the XSD to make things work fine, but having the additional integrity check there and having the XSD schema match the SQL schema in the database is nice. "} {"user":"72","questionId":129,"creationDate":"2008-08-01T16:36:42Z","answerId":135,"type":"answer","body":"Rolling your own PHP solution will certainly work though I'm not sure if there is a good way to automatically duplicate the schema from one DB to the other (maybe this was your question). If you are just copying data, and/or you need custom code anyway to convert between modified schemas between the two DB's, I would recommend using PHP 5.2+ and the PDO libraries. You'll be able to connect using PDO ODBC (and use MSSQL drivers). I had a lot of problems getting large text fields and multi-byte characters from MSSQL into PHP using other libraries. "} {"user":"72","questionId":126,"creationDate":"2008-08-01T16:43:30Z","answerId":139,"type":"answer","body":" Am I just going overboard here? Perhaps ;) Another approach would be to utilize a private/protected method to actually do the getting (caching/db/etc), and a public wrapper for it that increments the count: PHP: public function getName() { $this->incrementNameCalled(); return $this->_getName(); } protected function _getName() { return $this->name; } and then from within the object itself: PHP: $name = $this->_getName(); This way you can still use that first argument for something else (like sending a flag for whether or not to used cached data here perhaps). "} {"user":"71","questionId":129,"creationDate":"2008-08-01T16:47:54Z","answerId":141,"type":"answer","body":"Another tool to try would be the SQLMaestro suite - http://www.sqlmaestro.com It is a little tricky nailing down the precise tool, but they have a variety of tools, both free and for purchase that handle a wide variety of tasks for multiple database platforms. I'd suggest trying the Data Wizard tool first for MySQL, since I believe that will have the proper \"import\" tool you need. "} {"user":"42","questionId":126,"creationDate":"2008-08-01T16:56:55Z","answerId":142,"type":"answer","body":"Well, it seems with C# 3.0 properties' default implementation, the decision is taken for you; you HAVE to set the property using the (possibly private) property setter. I personally only use the private member-behind when not doing so would cause the object to fall in an less than desirable state, such as when initializing or when caching/lazy loading is involved. "} {"user":"86","questionId":126,"creationDate":"2008-08-01T17:01:27Z","answerId":143,"type":"answer","body":"As stated in some of the comments: Sometimes you should, sometimes you shouldn't. The great part about private variables is that you are able to see all the places they are used when you change something. If your getter/setter does something you need, use it. If it doesn't matter you decide. The opposite case could be made that if you use the getter/setter and somebody changes the getter/setter they have to analyze all the places the getter and setter is used internally to see if it messes something up. "} {"user":"87","tags":["c#",".net","compression","decompression"],"questionId":145,"creationDate":"2008-08-01T17:13:08Z","title":"Compressing / Decompressing Folders & Files","type":"question","body":"Does anyone know of a good way to compress or decompress files and folders in C# quickly? Handling large files might be necessary. "} {"user":"30","tags":["php","apache","logging","download","analytics"],"questionId":146,"creationDate":"2008-08-01T17:14:58Z","title":"How do I track file downloads","acceptedAnswerId":152,"type":"question","body":"I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it. Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded? Is the play link a link to the actual mp3 file or to some javascript code that pops up a player? If the latter, you can easily add your own logging code in there to track the number of hits to it. If the former, you'll need something that can track the web server log itself and make that distinction. My hosting plan comes with webalizer, which does this nicely. It's javascript code, so that answers that. However, it would be nice to know how to track downloads using the other method (without switching hosts). "} {"user":"146637","questionId":42,"creationDate":"2008-08-01T17:23:43Z","answerId":147,"type":"answer","body":"The hook and listener method is the most commonly used, but there are other things you can do. Depending on the size of your app, and who your going to allow see the code (is this going to be a FOSS script, or something in house) will influence greatly how you want to allow plugins. kdeloach has a nice example, but his implementation and hook function is a little unsafe. I would ask for you to give more information of the nature of php app your writing, And how you see plugins fitting in. +1 to kdeloach from me. "} {"user":"71","questionId":146,"creationDate":"2008-08-01T17:24:24Z","answerId":148,"type":"answer","body":"Is the play link a link to the actual mp3 file or to some javascript code that pops up a player? If the latter, you can easily add your own logging code in there to track the number of hits to it. If the former, you'll need something that can track the web server log itself and make that distinction. My hosting plan comes with webalizer, which does this nicely. "} {"user":"80","questionId":145,"creationDate":"2008-08-01T17:28:24Z","answerId":149,"type":"answer","body":"As of .Net 1.1 the only available method is reaching into the java libraries. Using the Zip Classes in the J# Class Libraries to Compress Files and Data with C# Not sure if this has changed in recent versions. "} {"user":"44","questionId":145,"creationDate":"2008-08-01T17:30:56Z","answerId":151,"type":"answer","body":"I've always used the SharpZip Library. Here's a link "} {"user":"146637","questionId":146,"creationDate":"2008-08-01T17:33:58Z","answerId":152,"type":"answer","body":"The funny thing is i wrote a php media gallery for all my music 2 days ago. I had a similar problem. Im using http://musicplayer.sourceforge.net/ for the player. and the playlis are built via php. all music request go there a script called xfer.php?file=WHATEVER $filename = base64_url_decode($_REQUEST['file']); header(\"Cache-Control: public\"); header(\"Content-Description: File Transfer\"); header('Content-disposition: attachment; filename='.basename($filename)); header(\"Content-Transfer-Encoding: binary\"); header('Content-Length: '. filesize($filename)); // Put either file counting code here. either a db or static files // readfile($filename); //and spit the user the file function base64_url_decode($input) { return base64_decode(strtr($input, '-_,', '+/=')); } And when you call files use something like function base64_url_encode($input) { return strtr(base64_encode($input), '+/=', '-_,'); } http://us.php.net/manual/en/function.base64-encode.php If you are using some javascript or a flash player (JW player for example) that requires the actual link to be an mp3 file or whatever, you can append the text \"&type=.mp3\" so the final linke becomes something like \"www.example.com/xfer.php?file=34842ffjfjxfh&type=.mp3\". That way it looks like it ends with an mp3 extension without affecting the file link. "} {"user":"59","questionId":146,"creationDate":"2008-08-01T17:42:04Z","answerId":153,"type":"answer","body":"You could even set up an Apache .htaccess directive that converts *.mp3 requests into the querystring dubayou is working with. It might be an elegant way to keep the direct request and still be able to slipstream log function into the response. "} {"user":"146637","questionId":85,"creationDate":"2008-08-01T17:45:06Z","answerId":154,"type":"answer","body":"Well, what is the nature of the flat databases. Are they large or small. Is it simple arrays with arrays in them? if its something simple say userprofiles built as such: $user = array(\"name\" => \"dubayou\", \"age\" => 20, \"websites\" => array(\"dubayou.com\",\"willwharton.com\",\"codecream.com\"), \"and_one\" => \"more\"); and to save or update the db record for that user. $dir = \"../userdata/\"; //make sure to put it bellow what the server can reach. file_put_contents($dir.$user['name'],serialize($user)); and to load the record for the user function &get_user($name){ return unserialize(file_get_contents(\"../userdata/\".$name)); } but again this implementation will vary on the application and nature of the database you need. "} {"user":"9","questionId":108,"creationDate":"2008-08-01T17:47:54Z","answerId":155,"type":"answer","body":"I used to have lots of Explorer crashes (on 32-bit) caused by Tortoise. They seem to have gone away since I used the Include/Exclude path settings in the \"Icon Overlays\" configuration of TSVN. Constraining icon overlays to specific directories where I keep my source made this much more stable. "} {"user":"70","questionId":146,"creationDate":"2008-08-01T17:51:55Z","answerId":158,"type":"answer","body":"Use your httpd log files. Install http://awstats.sourceforge.net/ "} {"user":"42","questionId":104,"creationDate":"2008-08-01T17:52:46Z","answerId":159,"type":"answer","body":"Strictly speaking, a memory leak is consuming memory that is \"no longer used\" by the program. \"No longer used\" has more than one meaning, it could mean \"no more reference to it\", that is, totally unrecoverable, or it could mean, referenced, recoverable, unused but the program keeps the references anyway. Only the later applies to .Net for perfectly managed objects. However, not all classes are perfect and at some point an underlying unmanaged implementation could leak resources permanently for that process. In all cases, the application consumes more memory than strictly needed. The sides effects, depending on the ammount leaked, could go from none, to slowdown caused by excessive collection, to a series of memory exceptions and finally a fatal error followed by forced process termination. You know an application has a memory problem when monitoring shows that more and more memory is allocated to your process after each garbage collection cycle. In such case, you are either keeping too much in memory, or some underlying unmanaged implementation is leaking. For most leaks, resources are recovered when the process is terminated, however some resources are not always recovered in some precise cases, GDI cursor handles are notorious for that. Of course, if you have an interprocess communication mechanism, memory allocated in the other process would not be freed until that process frees it or terminates. "} {"user":"17","questionId":129,"creationDate":"2008-08-01T17:54:08Z","answerId":160,"type":"answer","body":"The best way that I have found is the MySQL Migration Toolkit provided by MySQL. I have used it successfully for some large migration projects. "} {"user":"33","questionId":104,"creationDate":"2008-08-01T17:57:14Z","answerId":161,"type":"answer","body":"I would define memory leaks as an object not freeing up all the memory allocated after it has completed. I have found this can happen in your application if you are using Windows API and COM (i.e. unmanaged code that has a bug in it or is not being managed correctly), in the framework and in third party components. I have also found not tiding up after using certain objects like pens can cause the issue. I personally have suffered Out of Memory Exceptions which can be caused but are not exclusive to memory leaks in dot net applications. (OOM can also come from pinning see Pinning Artical). If you are not getting OOM errors or need to confirm if it is a memory leak causing it then the only way is to profile your application. I would also try and ensure the following: a) Everything that implements Idisposable is disposed either using a finally block or the using statement these include brushes, pens etc.(some people argue to set everything to nothing in addition) b)Anything that has a close method is closed again using finally or the using statement (although I have found using does not always close depending if you declared the object outside the using statement) c)If you are using unmanaged code/windows API's that these are dealt with correctly after. (some have clean up methods to release resources) Hope this helps. "} {"user":"83","tags":[".net","asp.net","svn","versioning"],"questionId":163,"creationDate":"2008-08-01T18:00:13Z","title":"How do I sync the SVN revision number with my ASP.NET web site?","acceptedAnswerId":170,"type":"question","body":"Stack Overflow has a subversion version number at the bottom: svn revision: 679 I want to use such automatic versioning with my .NET Web Site/Application, Windows Forms, WPD projects/solutions. How do I implement this? "} {"user":"91","tags":["windows","embed","media"],"questionId":164,"creationDate":"2008-08-01T18:02:22Z","title":"Embedding Windows Media Player for all browsers","acceptedAnswerId":699,"type":"question","body":"We are using WMV videos on an internal site, and we are embedding them into web sites. Now, this works quite well on Internet Explorer, but not on Firefox. I've found ways to make it work in Firefox, but then it stops working in Internet Explorer. We do not want to use Silverlight just yet, especially since we cannot be sure that all clients will be running Windows XP with Windows Media Player installed. Is there some sort of Universal Code that embeds WMP into both Internet Explorer and Firefox, or do we need to implement some user-agent-detection and deliver different HTML for different browsers? "} {"user":"user2189331","questionId":145,"creationDate":"2008-08-01T18:04:25Z","answerId":165,"type":"answer","body":"You can use a 3rd-party library such as SharpZip as Tom pointed out. Another way (without going 3rd-party) is to use the Windows Shell API. You'll need to set a reference to the Microsoft Shell Controls and Automation COM library in your C# project. Gerald Gibson has an example at: http://geraldgibson.net/dnn/Home/CZipFileCompression/tabid/148/Default.aspx Internet Archive's copy of the dead page "} {"user":"17","questionId":163,"creationDate":"2008-08-01T18:08:16Z","answerId":166,"type":"answer","body":"You can do it by adding the following anywhere in your code $Id:$ So for example @Jeff did:
svn revision: $Id:$
and when checked in the server replaced $Id:$ with the current revision number. I also found this reference. There is also $Date:$, $Rev:$, $Revision:$ "} {"user":"30","questionId":164,"creationDate":"2008-08-01T18:08:53Z","answerId":167,"type":"answer","body":"You could use conditional comments to get IE and Firefox to do different things

Firefox only code

The browsers themselves will ignore code that isn't meant for them to read. "} {"user":"93","questionId":126,"creationDate":"2008-08-01T18:23:59Z","answerId":169,"type":"answer","body":"Personally, I feel like it's important to remain consistent. If you have getters and setters, use them. The only time I would access a field directly is when the accessor has a lot of overhead. It may feel like you're bloating your code unnecessarily, but it can certainly save a whole lot of headache in the future. The classic example: Later on, you may desire to change the way that field works. Maybe it should be calculated on-the-fly or maybe you would like to use a different type for the backing store. If you are accessing properties directly, a change like that can break an awful lot of code in one swell foop. "} {"user":"59","questionId":163,"creationDate":"2008-08-01T18:24:30Z","answerId":170,"type":"answer","body":"Looks like Jeff is using CruiseControl.NET based on some leafing through the podcast transcripts. This seems to have automated deployment capabilities from source control to production. Might this be where the insertion is happening? "} {"user":"83","tags":["sql-server","database","svn","version-control"],"questionId":173,"creationDate":"2008-08-01T18:33:08Z","title":"Versioning SQL Server database","acceptedAnswerId":516,"type":"question","body":"I want to get my databases under version control. Does anyone have any advice or recommended articles to get me started? I'll always want to have at least some data in there (as alumb mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurement. "} {"user":"96","tags":["c#","html","web-services","printing"],"questionId":174,"creationDate":"2008-08-01T18:33:48Z","title":"How do I print an HTML document from a web service?","type":"question","body":"I want to print HTML from a C# web service. The Web Browser control is overkill, and does not function well in a service environment, nor does it function well on a system with very tight security constraints. Is there any sort of free .NET library that will support the printing of a basic HTML page? Here is the code I have so far, which does not run properly. public void PrintThing(string document) { if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { Thread thread = new Thread((ThreadStart) delegate { PrintDocument(document); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } else { PrintDocument(document); } } protected void PrintDocument(string document) { WebBrowser browser = new WebBrowser(); browser.DocumentText = document; while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } browser.Print(); } This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing Print() to ShowPrintPreviewDialog() yields the following IE script error: Error: 'dialogArguments.___IE_PrintType' is null or not an object URL: res://ieframe.dll/preview.dlg And a small empty print preview dialog appears. "} {"user":"2089740","tags":["youtube","reverse-engineering"],"questionId":175,"creationDate":"2008-08-01T18:36:14Z","title":"Annotating YouTube videos programmatically","type":"question","body":"I want to be able to display a normal YouTube video with overlaid annotations, consisting of coloured rectangles for each frame. The only requirement is that this should be done programmatically. YouTube has annotations now, but require you to use their front end to create them by hand. I want to be able to generate them. What's the best way of doing this? Some ideas: Build your own Flash player (ew?) Somehow draw over the YouTube Flash player. Will this work? Reverse engineer & hijack YouTube's annotation system. Either messing with the local files or redirecting its attempt to download the annotations. (using Greasemonkey? Firefox plugin?) Idea that doesn't count: download the video "} {"user":"91","tags":["linux","apache","virtualhost"],"questionId":176,"creationDate":"2008-08-01T18:37:40Z","title":"error_log per Virtual Host?","acceptedAnswerId":207,"type":"question","body":"On one Linux Server running Apache and PHP 5, we got multiple Virtual Hosts with separate logfiles and everything. The only thing we cannot seem to separate between virtual hosts is the php error_log. Overriding this setting in the of the httpd.conf does not seem to do anything. Did I overlook something? Is there a way to have separate php error_logs for each Virtual Host? "} {"user":"2089740","tags":["algorithm","language-agnostic","colors","color-space"],"questionId":180,"creationDate":"2008-08-01T18:42:19Z","title":"Function for creating color wheels","acceptedAnswerId":539,"type":"question","body":"This is something I've pseudo-solved many times and never quite found a solution. That's stuck with me. The problem is to come up with a way to generate N colors, that are as distinguishable as possible where N is a parameter. "} {"user":"86","questionId":123,"creationDate":"2008-08-01T18:51:12Z","answerId":183,"type":"answer","body":"Maybe this might help: JSefa You can read CSV file with this tool and serialize it to XML. "} {"user":"55","questionId":123,"creationDate":"2008-08-01T19:21:57Z","answerId":190,"type":"answer","body":"I don't understand why you would want to do this. It sounds almost like cargo cult coding. Converting a CSV file to XML doesn't add any value. Your program is already reading the CSV file, so arguing that you need XML doesn't work. On the other hand, reading the CSV file, doing something with the values, and then serializing to XML does make sense (well, as much as using XML can make sense... ;)) but you would supposedly already have a means of serializing to XML. "} {"user":"91","tags":["c#",".net","asp.net","internationalization","globalization"],"questionId":192,"creationDate":"2008-08-01T19:23:13Z","title":"Floating Point Number parsing: Is there a Catch All algorithm?","acceptedAnswerId":258,"type":"question","body":"One of the fun parts of multi-cultural programming is number formats. Americans use 10,000.50 Germans use 10.000,50 French use 10 000,50 My first approach would be to take the string, parse it backwards, until I encounter a separator and use this as my decimal separator. There is an obvious flaw with that: 10.000 would be interpreted as 10. Another approach: if the string contains 2 different non-numeric characters, use the last one as the decimal separator and discard the others. If I only have one, check if it occurs more than once and discard it if it does. If it only appears once, check if it has 3 digits after it. If yes, discard it, otherwise use it as decimal separator. The obvious \"best solution\" would be to detect the User's culture or Browser, but that does not work if you have a Frenchman using an en-US Windows/Browser. Does the .net Framework contain some mythical black magic floating point parser that is better than Double.(Try)Parse() in trying to auto-detect the number format? "} {"user":"60","tags":["sql-server","migration"],"questionId":194,"creationDate":"2008-08-01T19:26:37Z","title":"Upgrading SQL Server 6.5","acceptedAnswerId":197,"type":"question","body":"Yes, I know. The existence of a running copy of SQL Server 6.5 in 2008 is absurd. That stipulated, what is the best way to migrate from 6.5 to 2005? Is there any direct path? Most of the documentation I've found deals with upgrading 6.5 to 7. Should I forget about the native SQL Server upgrade utilities, script out all of the objects and data, and try to recreate from scratch? I was going to attempt the upgrade this weekend, but server issues pushed it back till next. So, any ideas would be welcomed during the course of the week. Update. This is how I ended up doing it: Back up the database in question and Master on 6.5. Execute SQL Server 2000's instcat.sql against 6.5's Master. This allows SQL Server 2000's OLEDB provider to connect to 6.5. Use SQL Server 2000's standalone \"Import and Export Data\" to create a DTS package, using OLEDB to connect to 6.5. This successfully copied all 6.5's tables to a new 2005 database (also using OLEDB). Use 6.5's Enterprise Manager to script out all of the database's indexes and triggers to a .sql file. Execute that .sql file against the new copy of the database, in 2005's Management Studio. Use 6.5's Enterprise Manager to script out all of the stored procedures. Execute that .sql file against the 2005 database. Several dozen sprocs had issues making them incompatible with 2005. Mainly non-ANSI joins and quoted identifier issues. Corrected all of those issues and re-executed the .sql file. Recreated the 6.5's logins in 2005 and gave them appropriate permissions. There was a bit of rinse/repeat when correcting the stored procedures (there were hundreds of them to correct), but the upgrade went great otherwise. Being able to use Management Studio instead of Query Analyzer and Enterprise Manager 6.5 is such an amazing difference. A few report queries that took 20-30 seconds on the 6.5 database are now running in 1-2 seconds, without any modification, new indexes, or anything. I didn't expect that kind of immediate improvement. "} {"user":"80","questionId":173,"creationDate":"2008-08-01T19:28:25Z","answerId":195,"type":"answer","body":"This is one of the \"hard problems\" surrounding development. As far as I know there are no perfect solutions. If you only need to store the database structure and not the data you can export the database as SQL queries. (in Enterprise Manager: Right click on database -> Generate SQL script. I recommend setting the \"create one file per object\" on the options tab) You can then commit these text files to svn and make use of svn's diff and logging functions. I have this tied together with a Batch script that takes a couple parameters and sets up the database. I also added some additional queries that enter default data like user types and the admin user. (If you want more info on this, post something and I can put the script somewhere accessible) If you need to keep all of the data as well, I recommend keeping a back up of the database and using Redgate (http://www.red-gate.com/) products to do the comparisons. They don't come cheap, but they are worth every penny. "} {"user":"71","questionId":194,"creationDate":"2008-08-01T19:34:49Z","answerId":197,"type":"answer","body":"Hey, I'm still stuck in that camp too. The third party application we have to support is FINALLY going to 2K5, so we're almost out of the wood. But I feel your pain 8^D That said, from everything I heard from our DBA, the key is to convert the database to 8.0 format first, and then go to 2005. I believe they used the built in migration/upgrade tools for this. There are some big steps between 6.5 and 8.0 that are better solved there than going from 6.5 to 2005 directly. Your BIGGEST pain, if you didn't know already, is that DTS is gone in favor of SSIS. There is a shell type module that will run your existing DTS packages, but you're going to want to manually recreate them all in SSIS. Ease of this will depend on the complexity of the packages themselves, but I've done a few at work so far and they've been pretty smooth. "} {"user":"50","questionId":180,"creationDate":"2008-08-01T19:36:46Z","answerId":199,"type":"answer","body":"I've read somewhere the human eye can't distinguish between less than 4 values apart. so This is something to keep in mind. The following algorithm does not compensate for this. I'm not sure this is exactly what you want, but this is one way to randomly generate non-repeating color values: (beware, inconsistent pseudo-code ahead) //colors entered as 0-255 [R, G, B] colors = []; //holds final colors to be used rand = new Random(); //assumes n is less than 16,777,216 randomGen(int n){ while (len(colors) < n){ //generate a random number between 0,255 for each color newRed = rand.next(256); newGreen = rand.next(256); newBlue = rand.next(256); temp = [newRed, newGreen, newBlue]; //only adds new colors to the array if temp not in colors { colors.append(temp); } } } One way you could optimize this for better visibility would be to compare the distance between each new color and all the colors in the array: for item in color{ itemSq = (item[0]^2 + item[1]^2 + item[2]^2])^(.5); tempSq = (temp[0]^2 + temp[1]^2 + temp[2]^2])^(.5); dist = itemSq - tempSq; dist = abs(dist); } //NUMBER can be your chosen distance apart. if dist < NUMBER and temp not in colors { colors.append(temp); } But this approach would significantly slow down your algorithm. Another way would be to scrap the randomness and systematically go through every 4 values and add a color to an array in the above example. "} {"user":"35","questionId":134,"creationDate":"2008-08-01T19:52:14Z","answerId":206,"type":"answer","body":"You can try turning Check-constraints off on the DataSet (it's in its properties), or altering the properties of that relationship, and change the key to a simple reference - up to you. "} {"user":"50","questionId":176,"creationDate":"2008-08-01T19:58:45Z","answerId":207,"type":"answer","body":"To set the Apache (not the PHP) log, the easiest way to do this would be to do: # Stuff, # More Stuff, ErrorLog /path/where/you/want/the/error.log If there is no leading \"/\" it is assumed to be relative. Apache Error Log Page "} {"user":"39","questionId":192,"creationDate":"2008-08-01T20:02:08Z","answerId":210,"type":"answer","body":"I don't know the ASP.NET side of the problem but .NET has a pretty powerful class: System.Globalization.CultureInfo. You can use the following code to parse a string containing a double value: double d = double.Parse(\"100.20\", CultureInfo.CurrentCulture); // -- OR -- double d = double.Parse(\"100.20\", CultureInfo.CurrentUICulture); If ASP.NET somehow (i.e. using HTTP Request headers) passes current user's CultureInfo to either CultureInfo.CurrentCulture or CultureInfo.CurrentUICulture, these will work fine. "} {"user":"96","questionId":192,"creationDate":"2008-08-01T20:05:12Z","answerId":212,"type":"answer","body":"You can't please everyone. If I enter ten as 10.000, and someone enters ten thousand as 10.000, you cannot handle that without some knowledge of the culture of the input. Detect the culture somehow (browser, system setting - what is the use case? ASP? Internal app, or open to the world?), or provide an example of the expected formatting, and use the most lenient parser you can. Probably something like: double d = Double.Parse(\"5,000.00\", NumberStyles.Any, CultureInfo.InvariantCulture); "} {"user":"146637","tags":["php","arrays","cloud","tag-cloud"],"questionId":227,"creationDate":"2008-08-01T21:40:55Z","title":"What's the best way to generate a tag cloud from an array using h1 through h6 for sizing?","acceptedAnswerId":2943318,"type":"question","body":"I have the following arrays: $artist = array(\"the roots\", \"michael jackson\", \"billy idol\", \"more\", \"and more\", \"and_YET_MORE\"); $count = array(5, 3, 9, 1, 1, 3); I want to generate a tag cloud that will have artists with a higher number in $count enclosed in h6 tags and the lowest enclosed h1 tags. "} {"user":"91","questionId":9,"creationDate":"2008-08-01T21:46:12Z","answerId":229,"type":"answer","body":"Another function, not my me but found on the web and a bit refined: public static int GetAge(DateTime birthDate) { DateTime n = DateTime.Now; // To avoid a race condition around midnight int age = n.Year - birthDate.Year; if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day)) age--; return age; } Just two things that come into my mind: What about people from countries that do not use the gregorian calendar? DateTime.Now is in the server-specific culture i think. I have absolutely 0 knowledge about actually working with Asian calendars and I do not know if there is an easy way to convert dates between calendars, but just in case you're wondering about those chinese guys from the year 4660 :-) "} {"user":"62","tags":["windows","mailto"],"questionId":231,"creationDate":"2008-08-01T22:08:14Z","title":"Register Windows program with the mailto protocol programmatically","acceptedAnswerId":1812,"type":"question","body":"How do I make it so mailto: links will be registered with my program? How would I then handle that event in my program? Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as \"set as default email client\". Edit: Removed reference to Delphi, because the answer is independent of your language. "} {"user":"71","questionId":231,"creationDate":"2008-08-01T22:12:30Z","answerId":233,"type":"answer","body":"From what I've seen, there are a few registry keys that set the default mail client. One of them being: System Key: [HKEY_CLASSES_ROOT\\mailto\\shell\\open\\command] Value Name: (Default) Data Type: REG_SZ (String Value) Value Data: Mail program command-line. I'm not familar with Delphi 7, but I'm sure there are some registry editing libraries in there that you could use to modify this value. Some places list more than this key, others just this key, so you may need to test a little bit to find the proper one(s). "} {"user":"91","tags":["mysql","sql-server","sql-server-2005"],"questionId":234,"creationDate":"2008-08-01T22:13:34Z","title":"SQL Server 2005 implementation of MySQL REPLACE INTO?","acceptedAnswerId":12202,"type":"question","body":"MySQL has this incredibly useful yet properitary REPLACE INTO SQL Command. I wonder: Can this easily be emulated in SQL Server 2005? Starting a new Transaction, doing a Select() and then either UPDATE or INSERT and COMMIT is always a little bit of a pain, especially when doing it in the application and therefore always keeping 2 versions of the statement. I wonder if there is an easy and universal way to implement such a function into SQL Server 2005? "} {"user":"91","questionId":231,"creationDate":"2008-08-01T22:18:21Z","answerId":235,"type":"answer","body":"Here is the official Microsoft Solution to programmatically change the default mail client. It's Visual Basic, but I hope the concept is clear from this: http://support.microsoft.com/kb/299853 "} {"user":"48","questionId":176,"creationDate":"2008-08-01T22:20:05Z","answerId":236,"type":"answer","body":"The default behaviour is for error_log() to output to the Apache error log. If this isn't happening check your php.ini settings for the error_log directive - leave it unset to use the Apache log file for the current vhost. "} {"user":"34","questionId":234,"creationDate":"2008-08-01T22:22:37Z","answerId":238,"type":"answer","body":"The functionality you're looking for is traditionally called an UPSERT. Atleast knowing what it's called might help you find what you're looking for. I don't think SQL Server 2005 has any great ways of doing this. 2008 introduces the MERGE statement that can be used to accomplish this as shown in: http://www.databasejournal.com/features/mssql/article.php/3739131 or http://blogs.conchango.com/davidportas/archive/2007/11/14/SQL-Server-2008-MERGE.aspx Merge was available in the beta of 2005, but they removed it out in the final release. "} {"user":"71","questionId":234,"creationDate":"2008-08-01T22:31:36Z","answerId":243,"type":"answer","body":"What the upsert/merge is doing is something to the effect of... IF EXISTS (SELECT * FROM [Table] WHERE Id = X) UPDATE [Table] SET... ELSE INSERT INTO [Table] So hopefully the combination of those articles and this pseudo code can get things moving. "} {"user":"71","tags":[".net","database","sqlite"],"questionId":246,"creationDate":"2008-08-01T22:34:42Z","title":"Create a SQLite database based on an XSD Data Set","acceptedAnswerId":176741,"type":"question","body":"Does anybody know if there is a way to create a SQLite database based on an XSD DataSet? In the past I've just used a basic SQLite manager, but want to fuse things a bit more with my .NET development if possible. "} {"user":"55","questionId":227,"creationDate":"2008-08-01T23:10:56Z","answerId":253,"type":"answer","body":"Off the top of my head... $artist = array(\"the roots\",\"michael jackson\",\"billy idol\",\"more\",\"and more\",\"and_YET_MORE\"); $count = array(5,3,9,1,1,3); $highest = max($count); for (int $x = 0; x < count($artist); $x++) { $normalized = $count[$x] / $highest; $heading = ceil($normalized * 6); // 6 heading types echo \"\".$artist[$x].\"\"; } "} {"user":"55","questionId":192,"creationDate":"2008-08-01T23:17:53Z","answerId":258,"type":"answer","body":"I think the best you can do in this case is to take their input and then show them what you think they meant. If they disagree, show them the format you're expecting and get them to enter it again. "} {"user":"91","tags":["c#",".net","scripting","compiler-construction"],"questionId":260,"creationDate":"2008-08-01T23:22:08Z","title":"Adding scripting functionality to .NET applications","acceptedAnswerId":307,"type":"question","body":"I have a little game written in C#. It uses a database as back-end. It's a trading card game, and I wanted to implement the function of the cards as a script. What I mean is that I essentially have an interface, ICard, which a card class implements (public class Card056 : ICard) and which contains function that are called by the game. Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies). Is that possible? Register a class from a source file and then instantiate it, etc. ICard Cards[current] = new MyGame.CardLibrary.Card056(); Cards[current].OnEnterPlay(ref currentGameState); The language is C#, but extra bonus if it's possible to write the script in any .NET language. "} {"user":"61","tags":["c","linux","gtk","x11"],"questionId":263,"creationDate":"2008-08-01T23:27:24Z","title":"GTK implementation of MessageBox","acceptedAnswerId":607,"type":"question","body":"I have been trying to implement Win32's MessageBox using GTK. The app using SDL/OpenGL, so this isn't a GTK app. I handle the initialisation (gtk_init) sort of stuff inside the MessageBox function as follows: int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type) { GtkWidget *window = NULL; GtkWidget *dialog = NULL; gtk_init(>kArgc, >kArgv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window), \"delete_event\", G_CALLBACK(delete_event), NULL); g_signal_connect(G_OBJECT(window), \"destroy\", G_CALLBACK(destroy), NULL); // gcallback calls gtk_main_quit() gtk_init_add((GtkFunction)gcallback, NULL); if (type & MB_YESNO) { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text); } else { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text); } gtk_window_set_title(GTK_WINDOW(dialog), caption); gint result = gtk_dialog_run(GTK_DIALOG(dialog)); gtk_main(); gtk_widget_destroy(dialog); if (type & MB_YESNO) { switch (result) { default: case GTK_RESPONSE_DELETE_EVENT: case GTK_RESPONSE_NO: return IDNO; break; case GTK_RESPONSE_YES: return IDYES; break; } } return IDOK; } Now, I am by no means an experienced GTK programmer, and I realise that I'm probably doing something(s) horribly wrong. However, my problem is that the last dialog popped up with this function stays around until the process exits. Any ideas? "} {"user":"104","tags":["c++","berkeley-db"],"questionId":264,"creationDate":"2008-08-01T23:28:51Z","title":"BerkeleyDB Concurrency","type":"question","body":" What's the optimal level of concurrency that the C++ implementation of BerkeleyDB can reasonably support? How many threads can I have hammering away at the DB before throughput starts to suffer because of resource contention? I've read the manual and know how to set the number of locks, lockers, database page size, etc., but I'd just like some advice from someone who has real-world experience with BDB concurrency. My application is pretty simple, I'll be doing gets and puts of records that are about 1KB each. No cursors, no deleting. "} {"user":"105","tags":["svn","collaboration"],"questionId":265,"creationDate":"2008-08-01T23:29:32Z","title":"Best Practice: Collaborative Environment, Bin Directory, SVN","acceptedAnswerId":266,"type":"question","body":"What are the best practices for checking in BIN directories in a collaborative development environment using SVN? Should project level references be excluded from checkin? Is it easier to just add all bin directories? I develop a lot of DotNetNuke sites and it seems that in a multi-developer environment, it's always a huge task to get the environment setup correctly. The ultimate goal (of course) is to have a new developer checkout the trunk from SVN, restore the DNN database and have it all just 'work'... "} {"user":"34","questionId":265,"creationDate":"2008-08-01T23:40:28Z","answerId":266,"type":"answer","body":"Any assemblies that are expected to be in the GAC should stay in the GAC. This includes System.web.dll or any other 3rd party dll that you'll deploy to the GAC in production. This means a new developer would have to install these assemblies. All other 3rd party assemblies should be references through a relative path. My typical structure is: -Project --Project.sln --References ---StructureMap.dll ---NUnit.dll ---System.Web.Mvc.dll --Project.Web ---Project.Web.Proj ---Project.Web.Proj files --Project ---Project.Proj ---Project.Proj files Project.Web and Project reference the assemblies in the root/References folder relatively. These .dlls are checked into subversion. Aside from that, */bin */bin/* obj should be in your global ignore path. With this setup, all references to assemblies are either through the GAC (so should work across all computers), or relative to each project within your solution. "} {"user":"101","questionId":265,"creationDate":"2008-08-01T23:44:05Z","answerId":268,"type":"answer","body":"Is this a .Net specific question? Generally the best practice is to not check in anything which is built automatically from files that are already in SCM. All of that is ideally created as part of your automatic build process. If the bin directory you're referring to contains third-party binaries, rather than a build of your project, ignore (downvote?) this advice. "} {"user":"91","questionId":260,"creationDate":"2008-08-01T23:49:57Z","answerId":269,"type":"answer","body":"Yes, I thought about that, but I soon figured out that another Domain-Specific-Language (DSL) would be a bit too much. Essentially, they need to interact with my gamestate in possibly unpredictable ways. For example, a card could have a rule \"When this cards enter play, all your undead minions gain +3 attack against flying enemies, except when the enemy is blessed\". As trading card games are turn based, the GameState Manager will fire OnStageX events and let the cards modify other cards or the GameState in whatever way the card needs. If I try to create a DSL, I have to implement a rather large feature set and possibly constantly update it, which shifts the maintenance work to another part without actually removing it. That's why I wanted to stay with a \"real\" .NET language to essentially be able to just fire the event and let the card manipulate the gamestate in whatever way (within the limits of the code access security). "} {"user":"40","questionId":227,"creationDate":"2008-08-01T23:58:35Z","answerId":274,"type":"answer","body":"@Ryan That's correct but it actually makes the tags with the least number, larger. This code has been tested: $artist = array(\"the roots\",\"michael jackson\",\"billy idol\",\"more\",\"and more\",\"and_YET_MORE\"); $count = array(5,3,9,1,1,3); $highest = max($count); for ($x = 0; $x < count($artist); $x++) { $normalized = ($highest - $count[$x]+1) / $highest; $heading = ceil($normalized * 6); // 6 heading types echo \"{$artist[$x]}\"; } "} {"user":"109","tags":["c#","sorting","dictionary"],"questionId":289,"creationDate":"2008-08-02T00:40:58Z","title":"How do you sort a dictionary by value?","acceptedAnswerId":298,"type":"question","body":"I often have to sort a dictionary, consisting of keys & values, by value. For example, I have a hash of words and respective frequencies, that I want to order by frequency. There is a SortedList which is good for a single value (say frequency), that I want to map it back to the word. SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way? "} {"user":"106","questionId":174,"creationDate":"2008-08-02T00:42:35Z","answerId":290,"type":"answer","body":"I know that Visual Studio itself (at least in 2003 version) references the IE dll directly to render the \"Design View\". It may be worth looking into that. Otherwise, I can't think of anything beyond the Web Browser control. "} {"user":"109","questionId":289,"creationDate":"2008-08-02T00:43:38Z","answerId":291,"type":"answer","body":"Looking around, and using some C# 3.0 features we can do this: foreach (KeyValuePair item in keywordCounts.OrderBy(key=> key.Value)) { // do something with item.Key and item.Value } This is the cleanest way I've seen and is similar to the Ruby way of handling hashes. "} {"user":"91","questionId":289,"creationDate":"2008-08-02T00:47:48Z","answerId":292,"type":"answer","body":"On a high level, you have no other choice then to walk through the whole Dictionary and look at each value. Maybe this helps: http://bytes.com/forum/thread563638.html Copy/Pasting from John Timney: Dictionary s = new Dictionary(); s.Add(\"1\", \"a Item\"); s.Add(\"2\", \"c Item\"); s.Add(\"3\", \"b Item\"); List> myList = new List>(s); myList.Sort( delegate(KeyValuePair firstPair, KeyValuePair nextPair) { return firstPair.Value.CompareTo(nextPair.Value); } ); "} {"user":"40","questionId":176,"creationDate":"2008-08-02T01:10:41Z","answerId":297,"type":"answer","body":"I usually just specify this in an .htaccess file or the vhost.conf on the domain I'm working on. Add this to one of these files: php_admin_value error_log \"/var/www/vhosts/example.com/error_log\" "} {"user":"49","questionId":289,"creationDate":"2008-08-02T01:15:42Z","answerId":298,"type":"answer","body":"using System.Linq.Enumerable; ... List> myList = aDictionary.ToList(); myList.Sort( delegate(KeyValuePair pair1, KeyValuePair pair2) { return pair1.Value.CompareTo(pair2.Value); } ); Since you're targeting .net 2.0 or above, you can simplify this into lambda syntax -- it's equivalent but shorter. If you're targeting .net 2.0 you can only use this syntax if you're using the compiler from vs2008 (or above). var myList = aDictionary.ToList(); myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value)); "} {"user":"91","questionId":109,"creationDate":"2008-08-02T01:38:14Z","answerId":304,"type":"answer","body":"Try removing the 0x first and then call Encoding.UTF8.GetString. I think that may work. Essentially: 0x44004500 Remove the 0x, and then always two bytes are one character: 44 00 = D 45 00 = E 6F 00 = o 72 00 = r So it's definitely a Unicode/UTF format with two bytes/character. "} {"user":"49","questionId":260,"creationDate":"2008-08-02T01:49:46Z","answerId":307,"type":"answer","body":"Oleg Shilo's C# Script solution (at The Code Project) really is a great introduction to providing script abilities in your application. A different approach would be to consider a language that is specifically built for scripting, such as IronRuby, IronPython, or Lua. IronPython and IronRuby are both available today. For a guide to embedding IronPython read How to embed IronPython script support in your existing app in 10 easy steps. Lua is a scripting language commonly used in games. There is a Lua compiler for .NET, available from CodePlex -- http://www.codeplex.com/Nua That codebase is a great read if you want to learn about building a compiler in .NET. A different angle altogether is to try PowerShell. There are numerous examples of embedding PowerShell into an application -- here's a thorough project on the topic: Powershell Tunnel "} {"user":"106","tags":["sql","database","oracle","version-control"],"questionId":308,"creationDate":"2008-08-02T01:52:54Z","title":"Is there a version control system for database structure changes?","acceptedAnswerId":360,"type":"question","body":"I often run into the following problem. I work on some changes to a project that require new tables or columns in the database. I make the database modifications and continue my work. Usually, I remember to write down the changes so that they can be replicated on the live system. However, I don't always remember what I've changed and I don't always remember to write it down. So, I make a push to the live system and get a big, obvious error that there is no NewColumnX, ugh. Regardless of the fact that this may not be the best practice for this situation, is there a version control system for databases? I don't care about the specific database technology. I just want to know if one exists. If it happens to work with MS SQL Server, then great. "} {"user":"55","questionId":308,"creationDate":"2008-08-02T01:56:51Z","answerId":310,"type":"answer","body":"Most database engines should support dumping your database into a file. I know MySQL does, anyway. This will just be a text file, so you could submit that to Subversion, or whatever you use. It'd be easy to run a diff on the files too. "} {"user":"59","tags":["security","php"],"questionId":328,"creationDate":"2008-08-02T02:41:34Z","title":"PHP Session Security","acceptedAnswerId":7488,"type":"question","body":"What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place! "} {"user":"59","questionId":328,"creationDate":"2008-08-02T02:43:42Z","answerId":329,"type":"answer","body":"One guideline is to call session_regenerate_id every time a session's security level changes. This helps prevent session hijacking. "} {"user":"63","tags":["c++","oop","class","nested-class"],"questionId":330,"creationDate":"2008-08-02T02:51:36Z","title":"Should I use nested classes in this case?","acceptedAnswerId":332,"type":"question","body":"I am working on a collection of classes used for video playback and recording. I have one main class which acts like the public interface, with methods like play(), stop(), pause(), record() etc... Then I have workhorse classes which do the video decoding and video encoding. I just learned about the existence of nested classes in C++, and I'm curious to know what programmers think about using them. I am a little wary and not really sure what the benefits/drawbacks are, but they seem (according to the book I'm reading) to be used in cases such as mine. The book suggests that in a scenario like mine, a good solution would be to nest the workhorse classes inside the interface class, so there are no separate files for classes the client is not meant to use, and to avoid any possible naming conflicts? I don't know about these justifications. Nested classes are a new concept to me. Just want to see what programmers think about the issue. "} {"user":"58","questionId":328,"creationDate":"2008-08-02T02:55:07Z","answerId":331,"type":"answer","body":"I think one of the major problems (which is being addressed in PHP 6) is register_globals. Right now one of the standard methods used to avoid register_globals is to use the $_REQUEST, $_GET or $_POST arrays. The \"correct\" way to do it (as of 5.2, although it's a little buggy there, but stable as of 6, which is coming soon) is through filters. So instead of: $username = $_POST[\"username\"]; you would do: $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); or even just: $username = filter_input(INPUT_POST, 'username'); "} {"user":"59","questionId":330,"creationDate":"2008-08-02T03:00:24Z","answerId":332,"type":"answer","body":"I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a \"multimedia driver\" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media type and situation) and perform the abstract operations on the workhorse structure. My philosophy would be to go ahead and make both structures accessible to the client in a polished way, just under the assumption they would be used in tandem. I would reference something like a QTextDocument in Qt. You provide a direct interface to the bare metal data handling, but pass the authority along to an object like a QTextEdit to do the manipulation. "} {"user":"50","questionId":328,"creationDate":"2008-08-02T03:16:19Z","answerId":335,"type":"answer","body":"This is pretty trivial and obvious, but be sure to session_destroy after every use. This can be difficult to implement if the user does not log out explicitly, so a timer can be set to do this. Here is a good tutorial on setTimer() and clearTimer(). "} {"user":"61","tags":["language-agnostic","types"],"questionId":336,"creationDate":"2008-08-02T03:34:44Z","title":"When to use unsigned values over signed ones?","acceptedAnswerId":339,"type":"question","body":"When is it appropriate to use an unsigned variable over a signed one? What about in a for loop? I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus. for (unsigned int i = 0; i < someThing.length(); i++) { SomeThing var = someThing.at(i); // You get the idea. } I know Java doesn't have unsigned values, and that must have been a concious decision on Sun Microsystems' part. "} {"user":"111","tags":["python","xml"],"questionId":337,"creationDate":"2008-08-02T03:35:55Z","title":"XML Processing in Python","acceptedAnswerId":342,"type":"question","body":"I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it. Unfortunately, whilst I know the XML model fairly well in .NET, I'm uncertain what the pros and cons are of the XML models in Python. Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple. "} {"user":"61","questionId":337,"creationDate":"2008-08-02T03:43:33Z","answerId":338,"type":"answer","body":"Dive Into Python has a chapter. Can't vouch for how good it would be though. "} {"user":"59","questionId":336,"creationDate":"2008-08-02T03:49:21Z","answerId":339,"type":"answer","body":"I was glad to find a good conversation on this subject, as I hadn't really given it much thought before. In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case). If you're going to do bitwise things like masks, unsigned starts to make more sense. Or, if you're desperate to get that extra positive range by taking advantage of the sign bit. Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against). "} {"user":"59","questionId":337,"creationDate":"2008-08-02T04:01:34Z","answerId":342,"type":"answer","body":"Personally, I've played with several of the built-in options on an XML-heavy project and have settled on pulldom as the best choice for less complex documents. Especially for small simple stuff, I like the event-driven theory of parsing rather than setting up a whole slew of callbacks for a relatively simple structure. Here is a good quick discussion of how to use the API. What I like: you can handle the parsing in a for loop rather than using callbacks. You also delay full parsing (the \"pull\" part) and only get additional detail when you call expandNode(). This satisfies my general requirement for \"responsible\" efficiency without sacrificing ease of use and simplicity. "} {"user":"100","questionId":260,"creationDate":"2008-08-02T04:18:15Z","answerId":344,"type":"answer","body":"You might be able to use IronRuby for that. Otherwise I'd suggest you have a directory where you place precompiled assemblies. Then you could have a reference in the DB to the assembly and class, and use reflection to load the proper assemblies at runtime. If you really want to compile at run-time you could use the CodeDOM, then you could use reflection to load the dynamic assembly. MSDN article which might help. "} {"user":"50","questionId":336,"creationDate":"2008-08-02T04:31:54Z","answerId":347,"type":"answer","body":"In your example above, when 'i' will always be positive and a higher range would be beneficial, unsigned would be useful. Like if you're using 'declare' statements, such as: #declare BIT1 (unsigned int 1) #declare BIT32 (unsigned int reallybignumber) Especially when these values will never change. However, if you're doing an accounting program where the people are irresponsible with their money and are constantly in the red, you will most definitely want to use 'signed'. I do agree with saint though that a good rule of thumb is to use signed, which C actually defaults to, so you're covered. "} {"user":"5","questionId":36,"creationDate":"2008-08-02T05:20:22Z","answerId":352,"type":"answer","body":"Take a look at the CHECKSUM command: SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); That will return the same number each time it's run as long as the table contents haven't changed. See my post on this for more information: CHECKSUM Here's how I used it to rebuild cache dependencies when tables changed: ASP.NET 1.1 database cache dependency (without triggers) "} {"user":"116","questionId":336,"creationDate":"2008-08-02T05:51:57Z","answerId":354,"type":"answer","body":"size_t is often a good choice for this, or size_type if you're using an STL class. "} {"user":"116","questionId":308,"creationDate":"2008-08-02T06:05:04Z","answerId":356,"type":"answer","body":"For Oracle, I use Toad, which can dump a schema to a number of discrete files (e.g., one file per table). I have some scripts that manage this collection in Perforce, but I think it should be easily doable in just about any revision control system. "} {"user":"119","questionId":260,"creationDate":"2008-08-02T06:16:23Z","answerId":359,"type":"answer","body":"You could use any of the DLR languages, which provide a way to really easily host your own scripting platform. However, you don't have to use a scripting language for this. You could use C# and compile it with the C# code provider. As long as you load it in its own AppDomain, you can load and unload it to your heart's content. "} {"user":"109","questionId":308,"creationDate":"2008-08-02T06:23:33Z","answerId":360,"type":"answer","body":"In Ruby on Rails, there's a concept of a migration -- a quick script to change the database. You generate a migration file, which has rules to increase the db version (such as adding a column) and rules to downgrade the version (such as removing a column). Each migration is numbered, and a table keeps track of your current db version. To migrate up, you run a command called \"db:migrate\" which looks at your version and applies the needed scripts. You can migrate down in a similar way. The migration scripts themselves are kept in a version control system -- whenever you change the database you check in a new script, and any developer can apply it to bring their local db to the latest version. "} {"user":"115","tags":["string","language-agnostic","cross-platform"],"questionId":361,"creationDate":"2008-08-02T06:57:57Z","title":"Generate list of all possible permutations of a string","acceptedAnswerId":362,"type":"question","body":"How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters. Any language would work, but it should be portable. "} {"user":"80","questionId":361,"creationDate":"2008-08-02T07:48:07Z","answerId":362,"type":"answer","body":"There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable index in the code below keeps track of the start of the last and the next iteration) Some pseudocode: list = originalString.split('') index = (0,0) list = [\"\"] for iteration n in 1 to y: index = (index[1], len(list)) for string s in list.subset(index[0] to end): for character c in originalString: list.add(s + c) you'd then need to remove all strings less than x in length, they'll be the first (x-1) * len(originalString) entries in the list. "} {"user":"117","questionId":308,"creationDate":"2008-08-02T07:48:56Z","answerId":363,"type":"answer","body":"There's a PHP5 \"database migration framework\" called Ruckusing. I haven't used it, but the examples show the idea, if you use the language to create the database as and when needed, you only have to track source files. "} {"user":"122","questionId":361,"creationDate":"2008-08-02T07:56:07Z","answerId":364,"type":"answer","body":"I just whipped this up quick in Ruby: def perms(x, y, possible_characters) all = [\"\"] current_array = all.clone 1.upto(y) { |iteration| next_array = [] current_array.each { |string| possible_characters.each { |c| value = string + c next_array.insert next_array.length, value all.insert all.length, value } } current_array = next_array } all.delete_if { |string| string.length < x } end You might look into language API for built in permutation type functions, and you might be able to write more optimized code, but if the numbers are all that high, I'm not sure there is much of a way around having a lot of results. Anyways, the idea behind the code is start with string of length 0, then keep track of all the strings of length Z where Z is the current size in the iteration. Then, go through each string and append each character onto each string. Finally at the end, remove any that were below the x threshold and return the result. I didn't test it with potentially meaningless input (null character list, weird values of x and y, etc). "} {"user":"116","questionId":88,"creationDate":"2008-08-02T08:08:22Z","answerId":367,"type":"answer","body":"High Resolution, Low Overhead Timing for Intel Processors If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained counter you can get for performance measurement. Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy. When I run this on my box, I get 11867927879484732 11867927879692217 it took this long to call printf: 207485 Here's the Intel developer's guide that gives tons of detail. #include #include inline uint64_t rdtsc() { uint32_t lo, hi; __asm__ __volatile__ ( \"xorl %%eax, %%eax\\n\" \"cpuid\\n\" \"rdtsc\\n\" : \"=a\" (lo), \"=d\" (hi) : : \"%ebx\", \"%ecx\"); return (uint64_t)hi << 32 | lo; } main() { unsigned long long x; unsigned long long y; x = rdtsc(); printf(\"%lld\\n\",x); y = rdtsc(); printf(\"%lld\\n\",y); printf(\"it took this long to call printf: %lld\\n\",y-x); } "} {"user":"49","tags":["email","email-spam"],"questionId":371,"creationDate":"2008-08-02T08:19:18Z","title":"How do you make sure email you send programmatically is not automatically marked as spam?","acceptedAnswerId":396,"type":"question","body":"This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly spamish terminology. Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it. This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam I figure this is a big topic in which I am essentially an ignorant simpleton. "} {"user":"124","questionId":371,"creationDate":"2008-08-02T08:32:04Z","answerId":375,"type":"answer","body":"You can tell your users to add your From address to their contacts when they complete their order, which, if they do so, will help a lot. Otherwise, I would try to get a log from some of your users. Sometimes they have details about why it was flagged as spam in the headers of the message, which you could use to tweak the text. Other things you can try: Put your site name or address in the subject Keep all links in the message pointing to your domain (and not email.com) Put an address or other contact information in the email "} {"user":"122","tags":["java","generics","warnings","casting","type-safety"],"questionId":382,"creationDate":"2008-08-02T08:58:27Z","title":"What is the meaning of the type safety warning in certain Java generics casts?","acceptedAnswerId":384,"type":"question","body":"What is the meaning of the Java warning? Type safety: The cast from Object to List is actually checking against the erased type List I get this warning when I try to cast an Object to a type with generic information, such as in the following code: Object object = getMyList(); List list = (List) object; "} {"user":"122","questionId":382,"creationDate":"2008-08-02T08:58:48Z","answerId":384,"type":"answer","body":"This warning is there because Java is not actually storing type information at run-time in an object that uses generics. Thus, if object is actually a List, there will be no ClassCastException at run-time except until an item is accessed from the list that doesn't match the generic type defined in the variable. This can cause further complications if items are added to the list, with this incorrect generic type information. Any code still holding a reference to the list but with the correct generic type information will now have an inconsistent list. To remove the warning, try: List list = (List) object; However, note that you will not be able to use certain methods such as add because the compiler doesn't know if you are trying to add an object of incorrect type. The above will work in a lot of situations, but if you have to use add, or some similarly restricted method, you will just have to suffer the yellow underline in Eclipse (or a SuppressWarning annotation). "} {"user":"134","tags":["search","lucene"],"questionId":387,"creationDate":"2008-08-02T09:28:17Z","title":"Lucene Score results","type":"question","body":"In Lucene if you had multiple indexes that covered only one partition each. Why does the same search on different indexes return results with different scores? The results from different servers match exactly. i.e. if I searched for : Name - John Smith DOB - 11/11/1934 Partition 0 would return a score of 0.345 Partition 1 would return a score of 0.337 Both match exactly on name and DOB. "} {"user":"118","questionId":361,"creationDate":"2008-08-02T09:40:54Z","answerId":388,"type":"answer","body":"I'm not sure why you would want to do this in the first place. The resulting set for any moderately large values of x and y will be huge, and will grow exponentially as x and/or y get bigger. Lets say your set of possible characters is the 26 lowercase letters of the alphabet, and you ask your application to generate all permutations where length = 5. Assuming you don't run out of memory you'll get 11,881,376 (i.e. 26 to the power of 5) strings back. Bump that length up to 6, and you'll get 308,915,776 strings back. These numbers get painfully large, very quickly. Here's a solution I put together in Java. You'll need to provide two runtime arguments (corresponding to x and y). Have fun. public class GeneratePermutations { public static void main(String[] args) { int lower = Integer.parseInt(args[0]); int upper = Integer.parseInt(args[1]); if (upper < lower || upper == 0 || lower == 0) { System.exit(0); } for (int length = lower; length <= upper; length++) { generate(length, \"\"); } } private static void generate(int length, String partial) { if (length <= 0) { System.out.println(partial); } else { for (char c = 'a'; c <= 'z'; c++) { generate(length - 1, partial + c); } } } } "} {"user":"134","questionId":387,"creationDate":"2008-08-02T09:51:00Z","answerId":391,"type":"answer","body":"The scoring contains the Inverse Document Frequency(IDF). If the term \"John Smith\" is in one partition, 0, 100 times and in partition 1, once. The score for searching for John Smith would be higher search in partition 1 as the term is more scarce. To get round this you would wither have to have your index being over all partitions, or you would need to override the IDF. "} {"user":"91","questionId":387,"creationDate":"2008-08-02T09:52:36Z","answerId":392,"type":"answer","body":"Because the score is determined on the index if I am not completely mistaken. If you have different indexes (more/less or different data that was indexed), the score will differ: http://lucene.apache.org/core/3_6_0/scoring.html (Warning: Contains Math :-)) "} {"user":"136","questionId":371,"creationDate":"2008-08-02T10:21:54Z","answerId":396,"type":"answer","body":"Use email authentication methods, such as SPF, and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site. Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail. Make sure that the IP-address that you're using is not on a blacklist Make sure that the reply-to address is a valid, existing address. Use the full, real name of the addressee in the To field, not just the email-address (e.g. \"John Smith\" ). Monitor your abuse accounts, such as abuse@yourdomain.com and postmaster@yourdomain.com. That means - make sure that these accounts exist, read what's sent to them, and act on complaints. Finally, make it really easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation. That said, getting Hotmail to accept your emails remains a black art. "} {"user":"135","questionId":72,"creationDate":"2008-08-02T10:22:41Z","answerId":397,"type":"answer","body":"RDoc uses SimpleMarkup so it's fairly simple to create lists, etc. using *, - or a number. It also treats lines that are indented at the same column number as part of the same paragraph until there is an empty line which signifies a new paragraph. Do you have a few examples of comments you want RDoc'ed so we could show you how to do them and then you could extrapolate that for the rest of your comments? "} {"user":"136","tags":["iphone","objective-c"],"questionId":402,"creationDate":"2008-08-02T10:47:08Z","title":"iPhone app in landscape mode, 2008 systems","acceptedAnswerId":2530953,"type":"question","body":"Note: this question is from 2008 and now is of only historic interest. What's the best way to create an iPhone application that runs in landscape mode from the start, regardless of the position of the device? Both programmatically and using the Interface Builder. "} {"user":"137","questionId":164,"creationDate":"2008-08-02T11:05:55Z","answerId":407,"type":"answer","body":"The best way to deploy video on the web is using Flash - it's much easier to embed cleanly into a web page and will play on more or less any browser and platform combination. The only reason to use Windows Media Player is if you're streaming content and you need extraordinarily strong digital rights management, and even then providers are now starting to use Flash even for these. See BBC's iPlayer for a superb example. I would suggest that you switch to Flash even for internal use. You never know who is going to need to access it in the future, and this will give you the best possible future compatibility. EDIT - March 20 2013. Interesting how these old questions resurface from time to time! How different the world is today and how dated this all seems. I would not recommend a Flash only route today by any means - best practice these days would probably be to use HTML 5 to embed H264 encoded video, with a Flash fallback as described here: http://diveintohtml5.info/video.html "} {"user":"137","questionId":48,"creationDate":"2008-08-02T11:24:57Z","answerId":411,"type":"answer","body":"If the fact that the first button is used by default is consistent across browsers, why not put them the right way round in the source code, then use CSS to switch their apparent positions? float them left and right to switch them around visually, for example. "} {"user":"123","questionId":108,"creationDate":"2008-08-02T11:30:47Z","answerId":412,"type":"answer","body":"Tortoise SVN with Ankhsvn for VS 2005 "} {"user":"268","tags":["com","vb6"],"questionId":419,"creationDate":"2008-08-02T11:52:01Z","title":"Unload a COM control when working in VB6 IDE","acceptedAnswerId":17396,"type":"question","body":"Part of my everyday work is maintaining and extending legacy VB6 applications. A common engine is written in C/C++ and VB6 uses these functions in order to improve performance. When it comes to asynchronous programming, a C interface is not enough and we rely on COM controls to fire events to VB6. My problem is that when I register the control in VB6, VB loads this control in memory and does not unload it until I quit the VB6 IDE. As the control is loaded the whole time, I am unable to recompile it in VC6, because the DLL file is locked. A solution I found is not to enable the control in VB but use the CreateObject() with the full name of my control. The problem then is that I must declare my control as an Object because VB6 knows nothing of the interface I am using and I do not have access to IntelliSense, which is a pain. Any idea how I can tell VB6 to unload controls after quitting the application or directly in the IDE ? "} {"user":"123","tags":["internet-explorer","windows-mobile","pocketpc"],"questionId":427,"creationDate":"2008-08-02T12:12:02Z","title":"Programmatically launch IE Mobile favorites screen","type":"question","body":"Is there any way to launch IE Mobile's \"Favorites\" screen directly by specifying any command line parameter? "} {"user":"136","questionId":192,"creationDate":"2008-08-02T12:28:12Z","answerId":430,"type":"answer","body":"The difference between 12.345 in French and English is a factor of 1000. If you supply an expected range where max < 1000*min, you can easily guess. Take for example the height of a person (including babies and children) in mm. By using a range of 200-3000, an input of 1.800 or 1,800 can unambiguously be interpreted as 1 meter and 80 centimeters, whereas an input of 912.300 or 912,300 can unambiguously be interpreted as 91 centimeters and 2.3 millimeters. "} {"user":"136","tags":["ruby-on-rails","ruby","http"],"questionId":438,"creationDate":"2008-08-02T12:56:58Z","title":"Implementation of \"Remember me\" in a Rails application","acceptedAnswerId":77397,"type":"question","body":"My Rails-app has a sign in box with a \"remember me\" checkbox. Users who check that box should remain logged in even after closing their browser. I'm keeping track of whether users are logged in by storing their id in the user's session. But sessions are implemented in Rails as session cookies, which are not persistent. I can make them persistent: class ApplicationController < ActionController::Base before_filter :update_session_expiration_date private def update_session_expiration_date options = ActionController::Base.session_options unless options[:session_expires] options[:session_expires] = 1.year.from_now end end end But that seems like a hack, which is surprising for such common functionality. Is there any better way? Edit Gareth's answer is pretty good, but I would still like an answer from someone familiar with Rails 2 (because of it's unique CookieSessionStore). "} {"user":"17","questionId":371,"creationDate":"2008-08-02T13:45:57Z","answerId":451,"type":"answer","body":"Yahoo uses a method called Sender ID, which can be configured at The SPF Setup Wizard and entered in to your DNS. Also one of the important ones for Exchange, Hotmail, AOL, Yahoo, and others is to have a Reverse DNS for your domain. Those will knock out most of the issues. However you can never prevent a person intentionally blocking your or custom rules. "} {"user":"144","questionId":17,"creationDate":"2008-08-02T14:57:13Z","answerId":467,"type":"answer","body":"While you haven't said what you're storing, and you may have a great reason for doing so, often the answer is 'as a filesystem reference' and the actual data is on the filesystem somewhere. http://www.onlamp.com/pub/a/onlamp/2002/07/11/MySQLtips.html "} {"user":"147","tags":["python","osx","fonts","photoshop"],"questionId":469,"creationDate":"2008-08-02T15:11:16Z","title":"How can I find the full path to a font from its display name on a Mac?","acceptedAnswerId":3040,"type":"question","body":"I am using the Photoshop's javascript API to find the fonts in a given PSD. Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc. This is all happening in a python program running on OSX so I guess I'm looking for one of: Some Photoshop javascript A Python function An OSX API that I can call from python "} {"user":"71","tags":[".net","web-services"],"questionId":470,"creationDate":"2008-08-02T15:11:47Z","title":"Homegrown consumption of web services","acceptedAnswerId":473,"type":"question","body":"I've been writing a few web services for a .net app, now I'm ready to consume them. I've seen numerous examples where there is homegrown code for consuming the service as opposed to using the auto generated methods that Visual Studio creates when adding the web reference. Is there some advantages to this? "} {"user":"147","questionId":337,"creationDate":"2008-08-02T15:21:03Z","answerId":471,"type":"answer","body":"ElementTree has a nice pythony API. I think it's even shipped as part of python 2.5 It's in pure python and as I say, pretty nice, but if you wind up needing more performance, then lxml exposes the same API and uses libxml2 under the hood. You can theoretically just swap it in when you discover you need it. "} {"user":"49","questionId":470,"creationDate":"2008-08-02T15:33:13Z","answerId":473,"type":"answer","body":"No, what you're doing is fine. Don't let those people confuse you. If you've written the web services with .net then the reference proxies generated by .net are going to be quite suitable. The situation you describe (where you are both producer and consumer) is the ideal situation. If you need to connect to a web services that is unknown at compile time, then you would want a more dynamic approach, where you deduce the 'shape' of the web service. But start by using the auto generated proxy class, and don't worry about it until you hit a limitation. And when you do -- come back to stack overflow ;-) "} {"user":"77","tags":["c#","winforms","data-binding"],"questionId":482,"creationDate":"2008-08-02T16:09:56Z","title":"WinForms ComboBox data binding gotcha","acceptedAnswerId":509,"type":"question","body":"Assume you are doing something like the following List myitems = new List { \"Item 1\", \"Item 2\", \"Item 3\" }; ComboBox box = new ComboBox(); box.DataSource = myitems; ComboBox box2 = new ComboBox(); box2.DataSource = myitems So now we have 2 combo boxes bound to that array, and everything works fine. But when you change the value of one combo box, it changes BOTH combo boxes to the one you just selected. Now, I know that Arrays are always passed by reference (learned that when i learned C :D), but why on earth would the combo boxes change together? I don't believe the combo box control is modifying the collection at all. As a work around, don't this would achieve the funcionality that is expected / desired ComboBox box = new ComboBox(); box.DataSource = myitems.ToArray(); "} {"user":"147","questionId":438,"creationDate":"2008-08-02T16:10:42Z","answerId":483,"type":"answer","body":"You should almost certainly not be extending the session cookie to be long lived. Although not dealing specifically with rails this article goes to some length to explain 'remember me' best practices. In summary though you should: Add an extra column to the user table to accept a large random value Set a long lived cookie on the client which combines the user id and the random value When a new session starts, check for the existence of the id/value cookie and authenticate the new user if they match. The author also recommends invalidating the random value and resetting the cookie at every login. Personally I don't like that as you then can't stay logged into a site on two computers. I would tend to make sure my password changing function also reset the random value thus locking out sessions on other machines. As a final note, the advice he gives on making certain functions (password change/email change etc) unavailable to auto authenticated sessions is well worth following but rarely seen in the real world. "} {"user":"50","questionId":469,"creationDate":"2008-08-02T16:56:53Z","answerId":497,"type":"answer","body":"open up a terminal (Applications->Utilities->Terminal) and type this in: locate InsertFontHere This will spit out every file that has the name you want. Warning: there may be alot to wade through. "} {"user":"147","tags":["python","windows","image","pdf"],"questionId":502,"creationDate":"2008-08-02T17:01:58Z","title":"Get a preview JPEG of a PDF on Windows?","acceptedAnswerId":7090,"type":"question","body":"I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF. On the Mac I am spawning sips. Is there something similarly simple I can do on Windows? "} {"user":"143","questionId":482,"creationDate":"2008-08-02T17:18:12Z","answerId":509,"type":"answer","body":"This has to do with how data bindings are set up in the dotnet framework, especially the BindingContext. On a high level it means that if you haven't specified otherwise each form and all the controls of the form share the same BindingContext. When you are setting the DataSource property the ComboBox will use the BindingContext to get a ConcurrenyMangager that wraps the list. The ConcurrenyManager keeps track of such things as the current selected position in the list. When you set the DataSource of the second ComboBox it will use the same BindingContext (the forms) which will yield a reference to the same ConcurrencyManager as above used to set up the data bindings. To get a more detailed explanation see BindingContext. "} {"user":"151","tags":["ruby-on-rails","ruby","crash"],"questionId":514,"creationDate":"2008-08-02T17:26:39Z","title":"Frequent SystemExit in Ruby when making HTTP calls","acceptedAnswerId":519,"type":"question","body":"I have a Ruby on Rails Website that makes HTTP calls to an external Web Service. About once a day I get a SystemExit (stacktrace below) error email where a call to the service has failed. If I then try the exact same query on my site moments later it works fine. It's been happening since the site went live and I've had no luck tracking down what causes it. Ruby is version 1.8.6 and rails is version 1.2.6. Anyone else have this problem? This is the error and stacktrace. A SystemExit occurred /usr/local/lib/ruby/gems/1.8/gems/rails-1.2.6/lib/fcgi_handler.rb:116:in exit' /usr/local/lib/ruby/gems/1.8/gems/rails-1.2.6/lib/fcgi_handler.rb:116:in exit_now_handler' /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/inflector.rb:250:in to_proc' /usr/local/lib/ruby/1.8/net/protocol.rb:133:in call' /usr/local/lib/ruby/1.8/net/protocol.rb:133:in sysread' /usr/local/lib/ruby/1.8/net/protocol.rb:133:in rbuf_fill' /usr/local/lib/ruby/1.8/timeout.rb:56:in timeout' /usr/local/lib/ruby/1.8/timeout.rb:76:in timeout' /usr/local/lib/ruby/1.8/net/protocol.rb:132:in rbuf_fill' /usr/local/lib/ruby/1.8/net/protocol.rb:116:in readuntil' /usr/local/lib/ruby/1.8/net/protocol.rb:126:in readline' /usr/local/lib/ruby/1.8/net/http.rb:2017:in read_status_line' /usr/local/lib/ruby/1.8/net/http.rb:2006:in read_new' /usr/local/lib/ruby/1.8/net/http.rb:1047:in request' /usr/local/lib/ruby/1.8/net/http.rb:945:in request_get' /usr/local/lib/ruby/1.8/net/http.rb:380:in get_response' /usr/local/lib/ruby/1.8/net/http.rb:543:in start' /usr/local/lib/ruby/1.8/net/http.rb:379:in get_response' "} {"user":"150","questionId":173,"creationDate":"2008-08-02T17:33:54Z","answerId":516,"type":"answer","body":"Martin Fowler wrote my favorite article on the subject, http://martinfowler.com/articles/evodb.html. I choose not to put schema dumps in under version control as alumb and others suggest because I want an easy way to upgrade my production database. For a web application where I'll have a single production database instance, I use two techniques: Database Upgrade Scripts A sequence database upgrade scripts that contain the DDL necessary to move the schema from version N to N+1. (These go in your version control system.) A _version_history_ table, something like create table VersionHistory ( Version int primary key, UpgradeStart datetime not null, UpgradeEnd datetime ); gets a new entry every time an upgrade script runs which corresponds to the new version. This ensures that it's easy to see what version of the database schema exists and that database upgrade scripts are run only once. Again, these are not database dumps. Rather, each script represents the changes necessary to move from one version to the next. They're the script that you apply to your production database to \"upgrade\" it. Developer Sandbox Synchronization A script to backup, sanitize, and shrink a production database. Run this after each upgrade to the production DB. A script to restore (and tweak, if necessary) the backup on a developer's workstation. Each developer runs this script after each upgrade to the production DB. A caveat: My automated tests run against a schema-correct but empty database, so this advice will not perfectly suit your needs. "} {"user":"153","questionId":469,"creationDate":"2008-08-02T17:42:28Z","answerId":518,"type":"answer","body":"I haven't been able to find anything that does this directly. I think you'll have to iterate through the various font folders on the system: /System/Library/Fonts, /Library/Fonts, and there can probably be a user-level directory as well ~/Library/Fonts. "} {"user":"136","questionId":514,"creationDate":"2008-08-02T17:50:34Z","answerId":519,"type":"answer","body":"Using fcgi with Ruby is known to be very buggy. Practically everybody has moved to Mongrel for this reason, and I recommend you do the same. "} {"user":"154","questionId":173,"creationDate":"2008-08-02T17:54:50Z","answerId":521,"type":"answer","body":"You didn't mention any specifics about your target environment or constraints, so this may not be entirely applicable... but if you're looking for a way to effectively track an evolving DB schema and aren't adverse to the idea of using Ruby, ActiveRecord's migrations are right up your alley. Migrations programatically define database transformations using a Ruby DSL; each transformation can be applied or (usually) rolled back, allowing you to jump to a different version of your DB schema at any given point in time. The file defining these transformations can be checked into version control like any other piece of source code. Because migrations are a part of ActiveRecord, they typically find use in full-stack Rails apps; however, you can use ActiveRecord independent of Rails with minimal effort. See here for a more detailed treatment of using AR's migrations outside of Rails. "} {"user":"156","questionId":88,"creationDate":"2008-08-02T17:57:06Z","answerId":522,"type":"answer","body":" So it says microseconds explicitly, but says the resolution of the system clock is unspecified. I suppose resolution in this context means how the smallest amount it will ever be incremented? The data structure is defined as having microseconds as a unit of measurement, but that doesn't mean that the clock or operating system is actually capable of measuring that finely. Like other people have suggested, gettimeofday() is bad because setting the time can cause clock skew and throw off your calculation. clock_gettime(CLOCK_MONOTONIC) is what you want, and clock_getres() will tell you the precision of your clock. "} {"user":"154","questionId":337,"creationDate":"2008-08-02T18:04:10Z","answerId":525,"type":"answer","body":"Since you mentioned that you'll be building \"fairly simple\" XML, the minidom module (part of the Python Standard Library) will likely suit your needs. If you have any experience with the DOM representation of XML, you should find the API quite straight forward. "} {"user":"86","questionId":180,"creationDate":"2008-08-02T18:16:07Z","answerId":529,"type":"answer","body":"Isn't it also a factor which order you set up the colors? Like if you use Dillie-Os idea you need to mix the colors as much as possible. 0 64 128 256 is from one to the next. but 0 256 64 128 in a wheel would be more \"apart\" Does this make sense? "} {"user":"86","questionId":264,"creationDate":"2008-08-02T18:21:21Z","answerId":530,"type":"answer","body":"Doesn't this depend on the hardware as well as number of threads and stuff? I would make a simple test and run it with increasing amounts of threads hammering and see what seems best. "} {"user":"157","questionId":19,"creationDate":"2008-08-02T18:22:52Z","answerId":531,"type":"answer","body":"The Monte Carlo method, as mentioned, applies some great concepts but it is, clearly, not the fastest --not by a long shot, not by any reasonable usefulness. Also, it all depends on what kind of accuracy you are looking for. The fastest pi I know of is the digits hard coded. Looking at Pi and Pi[PDF], there are a lot of formulas. Here is a method that converges quickly (~14digits per iteration). The current fastest application, PiFast, uses this formula with the FFT. I'll just write the formula, since the code is straight forward. This formula was almost found by Ramanujan and discovered by Chudnovsky. It is actually how he calculated several billion digits of the number --so it isn't a method to disregard. The formula will overflow quickly since we are dividing factorials, it would be advantageous then to delay such calculating to remove terms. where, Below is the Brent–Salamin algorithm. Wikipedia mentions that when a and b are 'close enough' then (a+b)^2/4t will be an approximation of pi. I'm not sure what 'close enough' means, but from my tests, one iteration got 2digits, two got 7, and three had 15, of course this is with doubles, so it might have error based on its representation and the 'true' calculation could be more accurate. let pi_2 iters = let rec loop_ a b t p i = if i = 0 then a,b,t,p else let a_n = (a +. b) /. 2.0 and b_n = sqrt (a*.b) and p_n = 2.0 *. p in let t_n = t -. (p *. (a -. a_n) *. (a -. a_n)) in loop_ a_n b_n t_n p_n (i - 1) in let a,b,t,p = loop_ (1.0) (1.0 /. (sqrt 2.0)) (1.0/.4.0) (1.0) iters in (a +. b) *. (a +. b) /. (4.0 *. t) Lastly, how about some pi golf (800 digits)? 160 characters! int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,printf(\"%.4d\",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);} "} {"user":"86","questionId":265,"creationDate":"2008-08-02T18:30:34Z","answerId":532,"type":"answer","body":"Maven helps quite a lot with this problem when I'm coding java. We commit the pom.xml to the scs and the maven repository contains all our dependencies. For me that seems like a nice way to do it. "} {"user":"154","tags":["python","continuous-integration","extreme-programming"],"questionId":535,"creationDate":"2008-08-02T18:43:54Z","title":"Continuous Integration System for a Python Codebase","acceptedAnswerId":541,"type":"question","body":"I am starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase? "} {"user":"161","questionId":502,"creationDate":"2008-08-02T18:49:07Z","answerId":536,"type":"answer","body":"You can use ImageMagick's convert utility for this, see some examples in http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html : Convert taxes.pdf taxes.jpg Will convert a two page PDF file into [2] jpeg files: taxes.jpg.0, taxes.jpg.1 I can also convert these JPEGS to a thumbnail as follows: convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg I can even convert the PDF directly to a jpeg thumbnail as follows: convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg This will result in a thumbnail.jpg.0 and thumbnail.jpg.1 for the two pages. "} {"user":"156","questionId":263,"creationDate":"2008-08-02T18:49:30Z","answerId":537,"type":"answer","body":"A few things: You are creating (and not using) an unnecessary toplevel window, named window. You can just delete these lines: window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window), \"delete_event\", G_CALLBACK(delete_event), NULL); g_signal_connect(G_OBJECT(window), \"destroy\", G_CALLBACK(destroy), NULL); Also, the flow doesn't seem quite right. gtk_main() starts the GTK main loop, which blocks until something exits it. gtk_dialog_run() also starts a main loop, but it exits as soon as one of the buttons is clicked. I think it might be enough for you to remove the gtk_init_add() and gtk_main() calls, and simply deal with the return value. Also the gtk_widget_destroy() call is unnecessary, as the dialog window is automatically destroyed when gtk_dialog_run() returns. "} {"user":"156","questionId":535,"creationDate":"2008-08-02T18:56:56Z","answerId":538,"type":"answer","body":"One possibility is Hudson. It's written in Java, but there's integration with Python projects: Hudson embraces Python I've never tried it myself, however. (Update, Sept. 2011: After a trademark dispute Hudson has been renamed to Jenkins.) "} {"user":"157","questionId":180,"creationDate":"2008-08-02T19:03:52Z","answerId":539,"type":"answer","body":"My first thought on this is \"how generate N vectors in a space that maximize distance from each other.\" You can see that the RGB (or any other scale you use that forms a basis in color space) are just vectors. Take a look at Random Point Picking. Hope this is a good start for you! Once you have a set of vectors that are maximized a part, you can save them in a hash table or something for later, and just perform random rotations on them to get all the colors you desire that are maximally apart from each other! Edit: Thinking about this problem more, it would be better to map the colors in a linear manor, possibly (0,0,0) --> (255,255,255) lexicographically, and then distribute them evenly. I really don't know how well this will work, but it should since, lets say: n = 10 we know we have 16777216 colors (256^3). We can use buckles algorithm 515 to find the lexicographically indexed color.. You'll probably have to edit the algorithm to avoid overflow and probably add some minor speed improvements. "} {"user":"154","questionId":123,"creationDate":"2008-08-02T19:06:38Z","answerId":540,"type":"answer","body":"As far as I know, there's no ready-made library to do this for you, but producing a tool capable of translating from CSV to XML should only require you to write a crude CSV parser and hook up JDOM (or your XML Java library of choice) with some glue code. "} {"user":"157","questionId":535,"creationDate":"2008-08-02T19:06:40Z","answerId":541,"type":"answer","body":"We run Buildbot - Trac at work, I haven't used it too much since my code base isn't part of the release cycle yet. But we run the tests on different environments (OSX/Linux/Win) and it sends emails --and it's written in python. "} {"user":"136","tags":["security","http","authentication","language-agnostic","article"],"questionId":549,"creationDate":"2008-08-02T19:51:50Z","title":"The definitive guide to form-based website authentication","acceptedAnswerId":477578,"type":"question","body":"Form-based authentication for websites We believe that Stack Overflow should not just be a resource for very specific technical questions, but also for general guidelines on how to solve variations on common problems. \"Form based authentication for websites\" should be a fine topic for such an experiment. It should include topics such as: How to log in How to remain logged in Managing cookies (including recommended settings) SSL/HTTPS encryption How to store passwords Using secret questions Forgotten username/password functionality Use of nonces to prevent cross-site request forgeries (CSRF) OpenID \"Remember me\" checkbox Browser autocompletion of usernames and passwords Secret URLs (public URL protected by digest) Checking password strength E-mail validation and much more about form based authentication... It should not include things like: Roles and authorization HTTP basic authentication Please help us by: Suggesting subtopics Submitting good articles about this subject Editing the official answer "} {"user":"156","questionId":387,"creationDate":"2008-08-02T20:03:06Z","answerId":551,"type":"answer","body":"You may also be interested in the output of the explain() method, and the resulting Explanation object, which will give you an idea of how things are scored the way they are. "} {"user":"136","questionId":549,"creationDate":"2008-08-02T20:40:45Z","answerId":555,"type":"answer","body":"Definitive Article Sending credentials The only practical way to send credentials 100% securely is by using SSL. Using JavaScript to hash the password is not safe. Common pitfalls for client-side password hashing: If the connection between the client and server is unencrypted, everything you do is vulnerable to man-in-the-middle attacks. An attacker could replace the incoming javascript to break the hashing or send all credentials to their server, they could listen to client responses and impersonate the users perfectly, etc. etc. SSL with trusted Certificate Authorities is designed to prevent MitM attacks. The hashed password received by the server is less secure if you don't do additional, redundant work on the server. There's another secure method called SRP, but it's patented (although it is freely licensed) and there are few good implementations available. Storing passwords Don't ever store passwords as plaintext in the database. Not even if you don't care about the security of your own site. Assume that some of your users will reuse the password of their online bank account. So, store the hashed password, and throw away the original. And make sure the password doesn't show up in access logs or application logs. The best hashing function seems to be bcrypt. Hashes by themselves are also insecure. For instance, identical passwords mean identical hashes--this makes hash lookup tables an effective way of cracking lots of passwords at once. Instead, store the salted hash. A salt is a string appended to the password prior to hashing - use a different (random) salt per user. The salt is a public value, so you can store them with the hash in the database. See here for more on this. This means that you can't send the user their forgotten passwords (because you only have the hash). Don't reset the user's password unless you have authenticated the user (users must prove that they are able to read emails sent to the stored (and validated) email address.) Security questions Security questions are insecure - avoid using them. Why? Anything a security question does, a password does better. Read PART III: Using Secret Questions in @Jens Roland answer here in this wiki. Session cookies After the user logs in, the server sends the user a session cookie. The server can retrieve the username or id from the cookie, but nobody else can generate such a cookie (TODO explain mechanisms). Cookies can be hijacked: they are only as secure as the rest of the client's machine and other communications. They can be read from disk, sniffed in network traffic, lifted by a cross-site scripting attack, phished from a poisoned DNS so the client sends their cookies to the wrong servers. Don't send persistent cookies. Cookies should expire at the end of the client session (browser close or leaving your domain). If you want to autologin your users, you can set a persistent cookie, but it should be distinct from a full-session cookie. You can set an additional flag that the user has auto-logged in, and needs to login for real for sensitive operations. This is popular with shopping sites that want to provide you with a seamless, personalized shopping experience but still protect your financial details. For example, when you return to visit Amazon, they show you a page that looks like you're logged in, but when you go to place an order (or change your shipping address, credit card etc.), they ask you to confirm your password. Financial web sites such as banks and credit cards, on the other hand, only have sensitive data and should not allow auto-login or a low-security mode. List of external resources Dos and Don'ts of Client Authentication on the Web (PDF) 21 page academic article with many great tips. Ask YC: Best Practices for User Authentication Forum discussion on the subject You're Probably Storing Passwords Incorrectly Introductory article about storing passwords Discussion: Coding Horror: You're Probably Storing Passwords Incorrectly Forum discussion about a Coding Horror article. Never store passwords in a database! Another warning about storing passwords in the database. Password cracking Wikipedia article on weaknesses of several password hashing schemes. Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes Discussion about rainbow tables and how to defend against them, and against other threads. Includes extensive discussion. "} {"user":"157","tags":["unit-testing","language-agnostic","testing"],"questionId":561,"creationDate":"2008-08-02T21:34:24Z","title":"How to use combinations of sets as test data","acceptedAnswerId":794,"type":"question","body":"I would like to test a function with a tuple from a set of fringe cases and normal values. For example, while testing a function which returns true whenever given three lengths that form a valid triangle, I would have specific cases, negative / small / large numbers, values close-to being overflowed, etc.; what is more, main aim is to generate combinations of these values, with or without repetition, in order to get a set of test data. (inf,0,-1), (5,10,1000), (10,5,5), (0,-1,5), (1000,inf,inf), ... As a note: I actually know the answer to this, but it might be helpful for others, and a challenge for people here! --will post my answer later on. "} {"user":"Aaron","tags":["c#","asp.net","medium-trust"],"questionId":562,"creationDate":"2008-08-02T21:39:11Z","title":"How to write to Web.Config in Medium Trust?","type":"question","body":"Uploading my first decently sized web app to my shared host provided me with a fresh set of challenges, by which I mean, sleepless nights. The issue was that I had most certainly not developed my application for medium trust (or had any clue what that was.) I mitigated all of the issues, save one. I had written an installer for the admin to be able to specify their connectionstring and other preferences, but I cannot find a way to write to a web.config in medium trust. Does anyone have a solution, or should I just be putting preferences in another file? "} {"user":"25","tags":["c#","java","integer","int"],"questionId":564,"creationDate":"2008-08-02T21:47:34Z","title":"What is the difference between an int and an Integer in Java and C#?","acceptedAnswerId":566,"type":"question","body":"I was reading More Joel on Software when I came across Joel Spolsky saying something about a particular type of programmer knowing the difference between an int and an Integer in Java/C# (Object Oriented Programming Languages). So, what is the difference? "} {"user":"154","questionId":564,"creationDate":"2008-08-02T21:55:45Z","answerId":566,"type":"answer","body":"In Java, the 'int' type is a primitive , whereas the 'Integer' type is an object. In C#, the 'int' type is the same as System.Int32 and is a value type (ie more like the java 'int'). An integer (just like any other value types) can be boxed (\"wrapped\") into an object. The differences between objects and primitives are somewhat beyond the scope of this question, but to summarize: Objects provide facilities for polymorphism, are passed by reference (or more accurately have references passed by value), and are allocated from the heap. Conversely, primitives are immutable types that are passed by value and are often allocated from the stack. "} {"user":"58","questionId":564,"creationDate":"2008-08-02T22:05:08Z","answerId":568,"type":"answer","body":"Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer: Integer i = new Integer(6); You could call some method on i: String s = i.toString();//sets s the string representation of i Whereas with an int: int i = 6; You cannot call any methods on it, because it is simply a primitive. So: String s = i.toString();//will not work!!! would produce an error, because int is not an object. int is one of the few primitives in Java (along with char and some others). I'm not 100% sure, but I'm thinking that the Integer object more or less just has an int property and a whole bunch of methods to interact with that property (like the toString() method for example). So Integer is a fancy way to work with an int (Just as perhaps String is a fancy way to work with a group of chars). I know that Java isn't C, but since I've never programmed in C this is the closest I could come to the answer. Hope this helps! Integer object javadoc Integer Ojbect vs. int primitive comparison "} {"user":"163","questionId":371,"creationDate":"2008-08-02T23:00:53Z","answerId":576,"type":"answer","body":"Sign up for an account on as many major email providers as possible (gmail/yahoo/hotmail/aol/etc). If you make changes to your emails, either major rewording, changes to the code that sends the emails, changes to your email servers, etc, make sure to send test messages to all your accounts and verify that they are not being marked as spam. "} {"user":"91","tags":["sql-server","sql-server-2005","deployment","release-management"],"questionId":580,"creationDate":"2008-08-02T23:30:59Z","title":"Deploying SQL Server Databases from Test to Live","acceptedAnswerId":586,"type":"question","body":"I wonder how you guys manage deployment of a database between 2 SQL Servers, specifically SQL Server 2005. Now, there is a development and a live one. As this should be part of a buildscript (standard windows batch, even do with current complexity of those scripts, i might switch to PowerShell or so later), Enterprise Manager/Management Studio Express do not count. Would you just copy the .mdf File and attach it? I am always a bit careful when working with binary data, as this seems to be a compatiblity issue (even though development and live should run the same version of the server at all time). Or - given the lack of \"EXPLAIN CREATE TABLE\" in T-SQL - do you do something that exports an existing database into SQL-Scripts which you can run on the target server? If yes, is there a tool that can automatically dump a given Database into SQL Queries and that runs off the command line? (Again, Enterprise Manager/Management Studio Express do not count). And lastly - given the fact that the live database already contains data, the deployment may not involve creating all tables but rather checking the difference in structure and ALTER TABLE the live ones instead, which may also need data verification/conversion when existing fields change. Now, i hear a lot of great stuff about the Red Gate products, but for hobby projects, the price is a bit steep. So, what are you using to automatically deploy SQL Server Databases from Test to Live? "} {"user":"149","questionId":562,"creationDate":"2008-08-02T23:33:30Z","answerId":582,"type":"answer","body":"That actually sounds like IIS's Low level. If it is, then you won't be able to write to any file, not just the web.config. Here are the levels from IIS's help file: Full (internal) - Specifies unrestricted permissions. Grants the ASP.NET application permissions to access any resource that is subject to operating system security. All privileged operations are supported. High (web_hightrust.config) - Specifies a high level of code access security, which means that the application cannot do any one of the following things by default: Call unmanaged code. Call serviced components. Write to the event log. Access Message Queuing service queues. Access ODBC, OleDb, or Oracle data sources. Medium (web_mediumtrust.config) - Specifies a medium level of code access security, which means that, in addition to High Trust Level restrictions, the ASP.NET application cannot do any of the following things by default: Access files outside the application directory. Access the registry. Make network or Web service calls. Low (web_lowtrust.config) - Specifies a low level of code access security, which means that, in addition to Medium Trust Level restrictions, the application cannot do any of the following things by default: Write to the file system. Call the Assert method. Minimal (web_minimaltrust.config) - Specifies a minimal level of code access security, which means that the application has only execute permissions. I would suggest that if you are dead set on having an installer, have it create a web.config in memory that the user can save locally and FTP up afterward. "} {"user":"39","questionId":564,"creationDate":"2008-08-02T23:37:10Z","answerId":583,"type":"answer","body":"In C#, int is just an alias for System.Int32, string for System.String, double for System.Double etc... Personally I prefer int, string, double, etc. because they don't require a using System; statement :) A silly reason, I know... "} {"user":"149","questionId":580,"creationDate":"2008-08-02T23:40:04Z","answerId":585,"type":"answer","body":"For my projects I alternate between SQL Compare from REd Gate and the Database Publishing Wizard from Microsoft which you can download free here. The Wizard isn't as slick as SQL Compare or SQL Data Compare but it does the trick. One issue is that the scripts it generates may need some rearranging and/or editing to flow in one shot. On the up side, it can move your schema and data which isn't bad for a free tool. "} {"user":"34","questionId":580,"creationDate":"2008-08-02T23:51:09Z","answerId":586,"type":"answer","body":"I've taken to hand-coding all of my DDL (creates/alter/delete) statements, adding them to my .sln as text files, and using normal versioning (using subversion, but any revision control should work). This way, I not only get the benefit of versioning, but updating live from dev/stage is the same process for code and database - tags, branches and so on work all the same. Otherwise, I agree redgate is expensive if you don't have a company buying it for you. If you can get a company to buy it for you though, it really is worth it! "} {"user":"172","tags":["php","windows","exchange-server","webdav","mapi"],"questionId":588,"creationDate":"2008-08-03T00:03:58Z","title":"Best way to access Exchange using PHP?","acceptedAnswerId":633,"type":"question","body":"I'm writing a CMS application in PHP and one of the requirements is that it must be able to interface with the customer's Exchange server. I've written up this functionality a few times before and have always used WebDAV to do it, but now I'm leaning away from that. I will be running the site on IIS OR Apache (no preference) on Windows server 2008. A few things I would need to do include adding contacts to a given user's address book, sending emails as a given user and running reports on contacts for a user. All of this is pretty easy to do with WebDAV, but if there is a better way that doesn't require any functionality that is likely to be deprecated any time soon. Any ideas? Update: Justin, I love the idea of using com objects, I just worry about maintaining a 3rd product to make everything work... John, I can write a web service in C# to interface with for these functions and access it with my PHP app, but it's also a little bit out of the way. So far, I'm not 100% convinced that either of these is better than WebDAV... Can anyone show me where I'm being silly? "} {"user":"116","questionId":561,"creationDate":"2008-08-03T00:04:59Z","answerId":589,"type":"answer","body":"Interesting question! I would do this by picking combinations, something like the following in python. The hardest part is probably first pass verification, i.e. if f(1,2,3) returns true, is that a correct result? Once you have verified that, then this is a good basis for regression testing. Probably it's a good idea to make a set of test cases that you know will be all true (e.g. 3,4,5 for this triangle case), and a set of test cases that you know will be all false (e.g. 0,1,inf). Then you can more easily verify the tests are correct. # xpermutations from http://code.activestate.com/recipes/190465 from xpermutations import * lengths=[-1,0,1,5,10,0,1000,'inf'] for c in xselections(lengths,3): # or xuniqueselections print c (-1,-1,-1); (-1,-1,0); (-1,-1,1); (-1,-1,5); (-1,-1,10); (-1,-1,0); (-1,-1,1000); (-1,-1,inf); (-1,0,-1); (-1,0,0); ... "} {"user":"116","questionId":580,"creationDate":"2008-08-03T00:22:03Z","answerId":590,"type":"answer","body":"If you have a company buying it, Toad from Quest Software has this kind of management functionality built in. It's basically a two-click operation to compare two schemas and generate a sync script from one to the other. They have editions for most of the popular databases, including of course Sql Server. "} {"user":"111","questionId":580,"creationDate":"2008-08-03T00:37:03Z","answerId":591,"type":"answer","body":"I work the same way Karl does, by keeping all of my SQL scripts for creating and altering tables in a text file that I keep in source control. In fact, to avoid the problem of having to have a script examine the live database to determine what ALTERs to run, I usually work like this: On the first version, I place everything during testing into one SQL script, and treat all tables as a CREATE. This means I end up dropping and readding tables a lot during testing, but that's not a big deal early into the project (since I'm usually hacking the data I'm using at that point anyway). On all subsequent versions, I do two things: I make a new text file to hold the upgrade SQL scripts, that contain just the ALTERs for that version. And I make the changes to the original, create a fresh database script as well. This way an upgrade just runs the upgrade script, but if we have to recreate the DB we don't need to run 100 scripts to get there. Depending on how I'm deploying the DB changes, I'll also usually put a version table in the DB that holds the version of the DB. Then, rather than make any human decisions about which scripts to run, whatever code I have running the create/upgrade scripts uses the version to determine what to run. The one thing this will not do is help if part of what you're moving from test to production is data, but if you want to manage structure and not pay for a nice, but expensive DB management package, is really not very difficult. I've also found it's a pretty good way of keeping mental track of your DB. "} {"user":"116","tags":["python","sql","database","oracle","cx-oracle"],"questionId":594,"creationDate":"2008-08-03T01:15:08Z","title":"cx_Oracle: How do I iterate over a result set?","acceptedAnswerId":595,"type":"question","body":"There are several ways to iterate over a result set. What are the tradeoff of each? "} {"user":"116","questionId":594,"creationDate":"2008-08-03T01:17:36Z","answerId":595,"type":"answer","body":"The canonical way is to use the built-in cursor iterator. curs.execute('select * from people') for row in curs: print row You can use fetchall() to get all rows at once. for row in curs.fetchall(): print row It can be convenient to use this to create a Python list containing the values returned: curs.execute('select first_name from people') names = [row[0] for row in curs.fetchall()] This can be useful for smaller result sets, but can have bad side effects if the result set is large. You have to wait for the entire result set to be returned to your client process. You may eat up a lot of memory in your client to hold the built-up list. It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways. If you know there's a single row being returned in the result set you can call fetchone() to get the single row. curs.execute('select max(x) from t') maxValue = curs.fetchone()[0] Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator. row = curs.fetchone() while row: print row row = curs.fetchone() "} {"user":"76","questionId":580,"creationDate":"2008-08-03T01:38:02Z","answerId":597,"type":"answer","body":"I agree that scripting everything is the best way to go and is what I advocate at work. You should script everything from DB and object creation to populating your lookup tables. Anything you do in UI only won't translate (especially for changes... not so much for first deployments) and will end up requiring a tools like what Redgate offers. "} {"user":"175","questionId":371,"creationDate":"2008-08-03T01:39:56Z","answerId":598,"type":"answer","body":"Confirm that you have the correct email address before sending out emails. If someone gives the wrong email address on sign-up, beat them over the head about it ASAP. Always include clear \"how to unsubscribe\" information in EVERY email. Do not require the user to login to unsubscribe, it should be a unique url for 1-click unsubscribe. This will prevent people from marking your mails as spam because \"unsubscribing\" is too hard. "} {"user":"175","questionId":173,"creationDate":"2008-08-03T01:49:58Z","answerId":599,"type":"answer","body":"The typical solution is to dump the database as necessary and backup those files. Depending on your development platform, there may be opensource plugins available. Rolling your own code to do it is usually fairly trivial. Note: You may want to backup the database dump instead of putting it into version control. The files can get huge fast in version control, and cause your entire source control system to become slow (I'm recalling a CVS horror story at the moment). "} {"user":"175","questionId":438,"creationDate":"2008-08-03T01:53:49Z","answerId":600,"type":"answer","body":"This is a pretty good write-up of one guys experience of creating 30-day persistent sessions. WARNING: blog post is from 2006 http://grahamglass.blogs.com/main/2006/05/rails_sessionsr.html "} {"user":"user2189331","tags":["c#","c++","random"],"questionId":601,"creationDate":"2008-08-03T02:05:59Z","title":"Robust Random Number Generation","acceptedAnswerId":602,"type":"question","body":"I'm looking for a performant, reasonably robust RNG using no special hardware. It can use mathematical methods (Mersenne Twister, etc), it can \"collect entropy\" from the machine, whatever. On Linux/etc we have a drand48() which generates 48 random bits. I'd like a similar function/class for C++ or C# which can generate more than 32 bits of randomness and which low-order bits are equally as random as high-order bits. It doesn't have to be cryptographically secure but it must not use or be based on the C-language rand() or .NET System.Random. Any source code, links to source, etc. would be appreciated! Failing that, what TYPE of RNG should I be looking for? "} {"user":"13","questionId":601,"creationDate":"2008-08-03T02:18:57Z","answerId":602,"type":"answer","body":"For C++, Boost.Random is probably what you're looking for. It has support for MT (among many other algorithms), and can collect entropy via the nondet_random class. Check it out! :-) "} {"user":"116","questionId":601,"creationDate":"2008-08-03T02:26:33Z","answerId":605,"type":"answer","body":"The Gnu Scientific Library (GSL) has a pretty extensive set of RN generators, test harness, etc. If you're on linux, it's probably already available on your system. "} {"user":"156","questionId":263,"creationDate":"2008-08-03T02:30:05Z","answerId":607,"type":"answer","body":"Hmm, ok. I'd suggest code like this, then: typedef struct { int type; int result; } DialogData; static gboolean display_dialog(gpointer user_data) { DialogData *dialog_data = user_data; GtkWidget *dialog; if (dialog_data->type & MB_YESNO) dialog = gtk_message_dialog_new(...); else dialog = gtk_message_dialog_new(...); // Set title, etc. dialog_data->result = gtk_dialog_run(...); gtk_main_quit(); // Quits the main loop run in MessageBox() return FALSE; } int MessageBox(...) { DialogData dialog_data; dialog_data.type = type; gtk_idle_add(display_dialog, &dialog_data); gtk_main(); // Do stuff based on dialog_data.result } The struct is because you need to pass around a couple pieces of data. The gtk_idle_add() call adds a method to be run when the main loop is running and idle, and the FALSE return value from the display_dialog() call means that it's only run once. After we get the result from the dialog, we quit the main loop. That'll cause the gtk_main() in your main MessageBox() method to return, and you'll be able to access the result from there. Hope this helps! "} {"user":"13","questionId":564,"creationDate":"2008-08-03T02:32:50Z","answerId":608,"type":"answer","body":"I'll add to the excellent answers given above, and talk about boxing and unboxing, and how this applies to Java (although C# has it too). I'll use just Java terminology, because I am more au fait with that. As the answers mentioned, int is just a number (called the unboxed type), whereas Integer is an object (which contains the number, hence a boxed type). In Java terms, that means (apart from not being able to call methods on int), you cannot store int or other non-object types in collections (List, Map, etc.). In order to store them, you must first box them up in its corresponding boxed type. Java 5 onwards have something called auto-boxing and auto-unboxing which allow the boxing/unboxing to be done behind the scenes. Compare and contrast: Java 5 version: Deque queue; void add(int n) { queue.add(n); } int remove() { return queue.remove(); } Java 1.4 or earlier (no generics either): Deque queue; void add(int n) { queue.add(Integer.valueOf(n)); } int remove() { return ((Integer) queue.remove()).intValue(); } It must be noted that despite the brevity in the Java 5 version, both versions generate identical bytecode. Thus, although auto-boxing and auto-unboxing is very convenient because you write less code, these operations do happen behind the scenes, with the same runtime costs, so you still have to be aware of their existence. Hope this helps! "} {"user":"179","tags":["c++","visual-studio","compatibility","windows-nt"],"questionId":609,"creationDate":"2008-08-03T02:48:43Z","title":"Build for Windows NT 4.0 using Visual Studio 2005?","type":"question","body":"An MFC application that I'm trying to migrate uses afxext.h, which causes _AFXDLL to get set, which causes this error if I set /MT: Please use the /MD switch for _AFXDLL builds My research to date indicates that it is impossible to build an application for execution on Windows NT 4.0 using Visual Studio (C++, in this case) 2005. Is this really true? Are there any workaround available? "} {"user":"173","questionId":588,"creationDate":"2008-08-03T03:07:30Z","answerId":611,"type":"answer","body":"I'm not a PHP dev but Google says that PHP 5+ can instantiate COM components. If you can install Outlook on a box you could write a PHP web service around the COM component to handle the requests you need. $outlook = COM(\"Outlook.Application\") Outlook API referance "} {"user":"183","questionId":514,"creationDate":"2008-08-03T05:22:20Z","answerId":619,"type":"answer","body":"It's been awhile since I used FCGI but I think a FCGI process could throw a SystemExit if the thread was taking too long. This could be the web service not responding or even a slow DNS query. Some google results show a similar error with Python and FCGI so moving to mongrel would be a good idea. This post is my reference I used to setup mongrel and I still refer back to it. "} {"user":"184","tags":["performance","algorithm","primes"],"questionId":622,"creationDate":"2008-08-03T05:45:21Z","title":"Most efficient code for the first 10000 prime numbers?","acceptedAnswerId":623,"type":"question","body":"I want to print the first 10000 prime numbers. Can anyone give me the most efficient code for this? Clarifications: It does not matter if your code is inefficient for n >10000. The size of the code does not matter. You cannot just hard code the values in any manner. "} {"user":"154","questionId":622,"creationDate":"2008-08-03T06:03:35Z","answerId":623,"type":"answer","body":"The Sieve of Atkin is probably what you're looking for, its upper bound running time is O(N/log log N). If you only run the numbers 1 more and 1 less than the multiples of 6, it could be even faster, as all prime numbers above 3 are 1 away from some multiple of six. Resource for my statement "} {"user":"136","tags":["ruby","lambda","proc"],"questionId":626,"creationDate":"2008-08-03T06:40:54Z","title":"When to use lambda, when to use Proc.new?","acceptedAnswerId":723,"type":"question","body":"In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and Proc.new on the other. What are those differences? Can you give guidelines on how to decide which one to choose? In Ruby 1.9, proc and lambda are different. What's the deal? "} {"user":"122","questionId":626,"creationDate":"2008-08-03T07:28:54Z","answerId":629,"type":"answer","body":"I found this page which shows what the difference between Proc.new and lambda are. According to the page, the only difference is that a lambda is strict about the number of arguments it accepts, whereas Proc.new converts missing arguments to nil. Here is an example IRB session illustrating the difference: irb(main):001:0> l = lambda { |x, y| x + y } => # irb(main):002:0> p = Proc.new { |x, y| x + y } => # irb(main):003:0> l.call \"hello\", \"world\" => \"helloworld\" irb(main):004:0> p.call \"hello\", \"world\" => \"helloworld\" irb(main):005:0> l.call \"hello\" ArgumentError: wrong number of arguments (1 for 2) from (irb):1 from (irb):5:in `call' from (irb):5 from :0 irb(main):006:0> p.call \"hello\" TypeError: can't convert nil into String from (irb):2:in `+' from (irb):2 from (irb):6:in `call' from (irb):6 from :0 The page also recommends using lambda unless you specifically want the error tolerant behavior. I agree with this sentiment. Using a lambda seems a tad more concise, and with such an insignificant difference, it seems the better choice in the average situation. As for Ruby 1.9, sorry, I haven't looked into 1.9 yet, but I don't imagine they would change it all that much (don't take my word for it though, it seems you have heard of some changes, so I am probably wrong there). "} {"user":"33","questionId":588,"creationDate":"2008-08-03T07:50:37Z","answerId":633,"type":"answer","body":"I have not used PHP to do this but have experience in using C# to achieve the same thing. The Outlook API is a way of automating Outlook rather than connecting to Exchange directly. I have previously taken this approach in a C# application and it does work although can be buggy. If you wish to connect directly to the Exchange server you will need to research extended MAPI. In the past I used this wrapper MAPIEx: Extended MAPI Wrapper. It is a C# project but I believe you can use some .NET code on a PHP5 Windows server. Alternatively it has a C++ core DLL that you may be a able to use. I have found it to be very good and there are some good example applications. Update: Sorry for the delay no current way to keep track of posts yet. I do agree adding more layer on to your application and relying on 3rd party code can be scary (and rightfully so.) Today I read another interesting post tagged up as MAPI that is on a different subject. The key thing here though is that it has linked to this important MS article. I have been unaware of the issues until now on using managed code to interface to MAPI although the C++ code in the component should be unaffected by this error as it is unmanaged. This blog entry also suggests other ways to connect to MAPI/Exchange server. In this case due to these new facts http://us3.php.net/imap may be the answer as suggested by the other user. "} {"user":"188","questionId":337,"creationDate":"2008-08-03T08:34:57Z","answerId":635,"type":"answer","body":"I write a SOAP server that receives XML requests, and creates XML responses. (Unfortunately, it's not my project, so it's closed source, but that's another problem). It turned out for me that creating (SOAP) XML documents is fairly simple, if you have a data structure that \"fits\" the schema. I keep the envelope, since the response envelope is (almost) the same as the request envelope. Then, since my data structure is a (possibly nested) dictionary, I create a string that turns this dictionary into value items. This is a task that recursion makes simple, and I end up with the right structure. This is all done in python code, and is currently fast enough for production use. You can also (relatively) easily build lists as well, although depending upon your client, you may hit problems unless you give length hints. For me, this was much simpler, since a dictionary is a much easier way of working than some custom class. For the books, generating XML is much easier than parsing! "} {"user":"191","tags":["sql","database"],"questionId":644,"creationDate":"2008-08-03T09:55:26Z","title":"Swap unique indexed column values in database","acceptedAnswerId":665,"type":"question","body":"I have a database table and one of the fields (not the primary key) is having a unique index on it. Now I want to swap values under this column for two rows. How could this be done? Two hacks I know are: Delete both rows and re-insert them Update rows with some other value and swap and then update to actual value. But I don't want to go for these as they do not seem to be the appropriate solution to the problem. Could anyone help me out? "} {"user":"143","tags":["c#","visual-studio","versioning"],"questionId":650,"creationDate":"2008-08-03T11:12:52Z","title":"Automatically update version number","acceptedAnswerId":655,"type":"question","body":"I would like the version property of my application to be incremented for each build but I'm not sure on how to enable this functionality in Visual Studio (2005/2008). I have tried to specify the AssemblyVersion as 1.0.* but it doesn't get me exactly what I want. I'm also using a settings file and in earlier attempts when the assembly version changed my settings got reset to the default since the application looked for the settings file in another directory. I would like to be able to display a version number in the form of 1.1.38 so when a user finds a problem I can log the version they are using as well as tell them to upgrade if they have an old release. A short explanation of how the versioning works would also be appreciated. When does the build and revision number get incremented? "} {"user":"192","tags":["asp.net","iis","authentication","active-directory"],"questionId":651,"creationDate":"2008-08-03T11:21:54Z","title":"Checklist for IIS 6/ASP.NET Windows Authentication?","acceptedAnswerId":725,"type":"question","body":"I've been having trouble getting my ASP.NET application to automatically log users into the Intranet site I'm building. No matter the googling or the experimentation I applied, there is always a login box displayed by IE7. I've got Windows authentication mode set in the Web.config, disabled anonymous access and configured the correct default domain in IIS, but it's still asking the user to log in and, more annoyingly, the user is required to provide the domain too (DOMAIN\\auser), which is causing problems with non-technical visitors. Thank Zeus for password remembering functionality. I'm not the network administrator so it's possible that something about Active Directory is set up incorrectly, or it could just be me missing something very simple. Please note that I don't want to impersonate the user, I just need to know that the IPrincipal.Name property matches that of a valid record in my user database, hence authenticating the user to my application. To this end, it would be very useful to have a checklist of all configuration requirements for AD, ASP.NET and IIS to work together in this manner as a reference for debugging and hopefully reducing some user friction. "} {"user":"91","questionId":650,"creationDate":"2008-08-03T11:41:38Z","answerId":655,"type":"answer","body":"With the \"Built in\" stuff, you can't, as using 1.0.* or 1.0.0.* will replace the revision and build numbers with a coded date/timestamp, which is usually also a good way. For more info, see the Assembly Linker Documentation in the /v tag. As for automatically incrementing numbers, use the AssemblyInfo Task: AssemblyInfo Task This can be configured to automatically increment the build number. There are 2 Gotchas: Each of the 4 numbers in the Version string is limited to 65535. This is a Windows Limitation and unlikely to get fixed. Why are build numbers limited to 65535? Using with with Subversion requires a small change: Using MSBuild to generate assembly version info at build time (including SubVersion fix) Retrieving the Version number is then quite easy: Version v = Assembly.GetExecutingAssembly().GetName().Version; string About = string.Format(CultureInfo.InvariantCulture, @\"YourApp Version {0}.{1}.{2} (r{3})\", v.Major, v.Minor, v.Build, v.Revision); And, to clarify: In .net or at least in C#, the build is actually the THIRD number, not the fourth one as some people (for example Delphi Developers who are used to Major.Minor.Release.Build) might expect. In .net, it's Major.Minor.Build.Revision. "} {"user":"115","tags":["php","encryption","passwords"],"questionId":657,"creationDate":"2008-08-03T11:50:33Z","title":"Encrypting Passwords","acceptedAnswerId":669,"type":"question","body":"What is the fastest, yet secure way to encrypt passwords in (PHP preferred), and for which ever method you choose is it portable? In other words if I later migrate my website to a different server will my passwords continue to work? The method I am using now as I was told is dependent on the exact versions of the libraries installed on the server. "} {"user":"197","questionId":535,"creationDate":"2008-08-03T12:09:18Z","answerId":660,"type":"answer","body":"Second the Buildbot - Trac integration. You can find more information about the integration on the Buildbot website. At my previous job, we wrote and used the plugin they mention (tracbb). What the plugin does is rewriting all of the Buildbot urls so you can use Buildbot from within Trac. (http://example.com/tracbb). The really nice thing about Buildbot is that the configuration is written in Python. You can integrate your own Python code directly to the configuration. It's also very easy to write your own BuildSteps to execute specific tasks. We used BuildSteps to get the source from SVN, pull the dependencies, publish test results to WebDAV, etcetera. I wrote an X10 interface so we could send signals with build results. When the build failed, we switched on a red lava lamp. When the build succeeded, a green lava lamp switched on. Good times :-) "} {"user":"197","questionId":644,"creationDate":"2008-08-03T12:26:35Z","answerId":665,"type":"answer","body":"I think you should go for solution 2. There is no 'swap' function in any SQL variant I know of. If you need to do this regularly, I suggest solution 1, depending on how other parts of the software are using this data. You can have locking issues if you're not careful. But in short: there is no other solution than the ones you provided. "} {"user":"197","questionId":264,"creationDate":"2008-08-03T12:34:36Z","answerId":667,"type":"answer","body":"It depends on what kind of application you are building. Create a representative test scenario, and start hammering away. Then you will know the definitive answer. Besides your use case, it also depends on CPU, memory, front-side bus, operating system, cache settings, etcetera. Seriously, just test your own scenario. If you need some numbers (that actually may mean nothing in your scenario): Oracle Berkeley DB: Performance Metrics and Benchmarks Performance Metrics & Benchmarks: Berkeley DB "} {"user":"117","questionId":657,"creationDate":"2008-08-03T12:48:36Z","answerId":669,"type":"answer","body":"If you are choosing an encryption method for your login system then speed is not your friend, Jeff had a to-and-frow with Thomas Ptacek about passwords and the conclusion was that you should use the slowest, most secure encryption method you can afford to. From Thomas Ptacek's blog: Speed is exactly what you don’t want in a password hash function. Modern password schemes are attacked with incremental password crackers. Incremental crackers don’t precalculate all possible cracked passwords. They consider each password hash individually, and they feed their dictionary through the password hash function the same way your PHP login page would. Rainbow table crackers like Ophcrack use space to attack passwords; incremental crackers like John the Ripper, Crack, and LC5 work with time: statistics and compute. The password attack game is scored in time taken to crack password X. With rainbow tables, that time depends on how big your table needs to be and how fast you can search it. With incremental crackers, the time depends on how fast you can make the password hash function run. The better you can optimize your password hash function, the faster your password hash function gets, the weaker your scheme is. MD5 and SHA1, even conventional block ciphers like DES, are designed to be fast. MD5, SHA1, and DES are weak password hashes. On modern CPUs, raw crypto building blocks like DES and MD5 can be bitsliced, vectorized, and parallelized to make password searches lightning fast. Game-over FPGA implementations cost only hundreds of dollars. "} {"user":"199","questionId":227,"creationDate":"2008-08-03T13:01:24Z","answerId":676,"type":"answer","body":"Perhaps this is a little academic and off topic but hX tags are probably not the best choice for a tag cloud for reasons of document structure and all that sort of thing. Maybe spans or an ol with appropriate class attributes (plus some CSS)? "} {"user":"51","questionId":48,"creationDate":"2008-08-03T13:12:21Z","answerId":679,"type":"answer","body":"I would use Javascript to submit the form. The function would be triggered by the OnKeyPress event of the form element, and would detect whether the Enter key was selected. If this is the case, it will submit the form. Here are two pages that give techniques on how to do this: 1, 2. Based on these, here is an example of usage (based on here): "} {"user":"200","questionId":328,"creationDate":"2008-08-03T13:14:48Z","answerId":681,"type":"answer","body":"The main problem with PHP sessions and security (besides session hijacking) comes with what environment you are in. By default PHP stores the session data in a file in the OS's temp directory. Without any special thought or planning this is a world readable directory so all of your session information is public to anyone with access to the server. As for maintaining sessions over multiple servers. At that point it would be better to switch PHP to user handled sessions where it calls your provided functions to CRUD (create, read, update, delete) the session data. At that point you could store the session information in a database or memcache like solution so that all application servers have access to the data. Storing your own sessions may also be advantageous if you are on a shared server because it will let you store it in the database which you often times have more control over then the filesystem. "} {"user":"199","tags":["python","arrays","iteration"],"questionId":683,"creationDate":"2008-08-03T13:19:16Z","title":"Using 'in' to match an attribute of Python objects in an array","acceptedAnswerId":57833,"type":"question","body":"I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, foo in iter_attr(array of python objects, attribute name) I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers "} {"user":"51","questionId":644,"creationDate":"2008-08-03T13:22:25Z","answerId":684,"type":"answer","body":"I also think that #2 is the best bet, though I would be sure to wrap it in a transaction in case something goes wrong mid-update. An alternative (since you asked) to updating the Unique Index values with different values would be to update all of the other values in the rows to that of the other row. Doing this means that you could leave the Unique Index values alone, and in the end, you end up with the data that you want. Be careful though, in case some other table references this table in a Foreign Key relationship, that all of the relationships in the DB remain intact. "} {"user":"34","questionId":657,"creationDate":"2008-08-03T13:48:25Z","answerId":691,"type":"answer","body":"I'm with Peter. Developer don't seem to understand passwords. We all pick (and I'm guilty of this too) MD5 or SHA1 because they are fast. Thinking about it ('cuz someone recently pointed it out to me) that doesn't make any sense. We should be picking a hashing algorithm that's stupid slow. I mean, on the scale of things, a busy site will hash passwords what? every 1/2 minute? Who cares if it take 0.8 seconds vs 0.03 seconds server wise? But that extra slowness is huge to prevent all types of common brute-forcish attacks. From my reading, bcrypt is specifically designed for secure password hashing. It's based on blowfish, and there are many implementation. For PHP, check out PHPPass http://www.openwall.com/phpass/ For anyone doing .NET, check out BCrypt.NET http://derekslager.com/blog/posts/2007/10/bcrypt-dotnet-strong-password-hashing-for-dotnet-and-mono.ashx "} {"user":"209","questionId":371,"creationDate":"2008-08-03T13:57:01Z","answerId":693,"type":"answer","body":"I've found that using the recipients real first and last name in the body is a sure fire way of getting through a spam filter. "} {"user":"206","questionId":36,"creationDate":"2008-08-03T13:59:24Z","answerId":695,"type":"answer","body":"How often do you need to check for changes and how large (in terms of row size) are the tables in the database? If you use the CHECKSUM_AGG(BINARY_CHECKSUM(*)) method suggested by John, it will scan every row of the specified table. The NOLOCK hint helps, but on a large database, you are still hitting every row. You will also need to store the checksum for every row so that you tell one has changed. Have you considered going at this from a different angle? If you do not want to modify the schema to add triggers, (which makes a sense, it's not your database), have you considered working with the application vendor that does make the database? They could implement an API that provides a mechanism for notifying accessory apps that data has changed. It could be as simple as writing to a notification table that lists what table and which row were modified. That could be implemented through triggers or application code. From your side, ti wouldn't matter, your only concern would be scanning the notification table on a periodic basis. The performance hit on the database would be far less than scanning every row for changes. The hard part would be convincing the application vendor to implement this feature. Since this can be handles entirely through SQL via triggers, you could do the bulk of the work for them by writing and testing the triggers and then bringing the code to the application vendor. By having the vendor support the triggers, it prevent the situation where your adding a trigger inadvertently replaces a trigger supplied by the vendor. "} {"user":"204","tags":["php","database","odbc","db2","ibm-midrange"],"questionId":696,"creationDate":"2008-08-03T14:03:28Z","title":"Connect PHP to IBM i (AS/400)","acceptedAnswerId":704,"type":"question","body":"I've got an upcoming project wherein I will need to connect our website (PHP5/Apache 1.3/OpenBSD 4.1) to our back-end system running on a iSeries with OS400 V5R3 so that I can access some tables stored there. I've done some checking around but am running into some roadblocks. From what I've seen the DB2 extensions and DB2 software from IBM only run under Linux. I've tried compiling the extensions with all the software from IBM and even tried their precompiled ibm_db2 extension with no luck. IBM only supports Linux so I turned on the Linux emulation in the kernel but that didn't seem to help anything. If anyone has run across getting everything to run natively under OpenBSD that would be great, but what I think I may have to do is setting up a second server running CentOS with DB2 installed (most likely via ZendCore for IBM since it seems to do all this for me) and the driver so that I can set up a small transaction server that I can post against and get a JSON representation of the DB2 data that I need. Does the second option seem overkill or does anyone else have any better ideas? "} {"user":"30","questionId":164,"creationDate":"2008-08-03T14:27:20Z","answerId":699,"type":"answer","body":"The following works for me in Firefox and Internet Explorer: "} {"user":"111","questionId":683,"creationDate":"2008-08-03T14:30:50Z","answerId":701,"type":"answer","body":"No, you were not dreaming. Python has a pretty excellent list comprehension system that lets you manipulate lists pretty elegantly, and depending on exactly what you want to accomplish, this can be done a couple of ways. In essence, what you're doing is saying \"For item in list if criteria.matches\", and from that you can just iterate through the results or dump the results into a new list. I'm going to crib an example from Dive Into Python here, because it's pretty elegant and they're smarter than I am. Here they're getting a list of files in a directory, then filtering the list for all files that match a regular expression criteria. files = os.listdir(path) test = re.compile(\"test\\.py$\", re.IGNORECASE) files = [f for f in files if test.search(f)] You could do this without regular expressions, for your example, for anything where your expression at the end returns true for a match. There are other options like using the filter() function, but if I were going to choose, I'd go with this. Eric Sipple "} {"user":"200","questionId":696,"creationDate":"2008-08-03T14:39:09Z","answerId":704,"type":"answer","body":"Have you looked at connecting to the server using unixODBC? If I remember correctly it has support for IBM DB2 and compiles on OpenBSD. Check out http://www.php.net/odbc for more information regarding the PHP side. If you can't get that to work, the option to setup a web service on a Linux server may be all you can do. "} {"user":"91","tags":[".net","database","embedded-database"],"questionId":705,"creationDate":"2008-08-03T14:41:43Z","title":"Embedded Database for .net that can run off a network","acceptedAnswerId":707,"type":"question","body":"I was (and still am) looking for an embedded database to be used in a .net (c#) application. The caveat: The Application (or at least the database) is stored on a Network drive, but only used by 1 user at a time. Now, my first idea was SQL Server Compact edition. That is really nicely integreated, but it can not run off a network. Firebird seems to have the same issue, but the .net Integration seems to be not really first-class and is largely undocumented. Blackfish SQL looks interesting, but there is no trial of the .net Version. Pricing is also OK. Any other suggestions of something that works well with .net and runs off a network without the need of actually installing a server software? "} {"user":"46","questionId":705,"creationDate":"2008-08-03T14:48:52Z","answerId":707,"type":"answer","body":"SQLite came to my mind while reading your question, and I'm quite sure that it's possible to access it from a network drive if you keep yourself to the constraint of 1 user at a time. SQLite on .NET - Get up and running in 3 minutes "} {"user":"111","tags":["c#",".net","visual-studio","unit-testing"],"questionId":709,"creationDate":"2008-08-03T14:53:53Z","title":".NET Testing Framework Advice","acceptedAnswerId":713,"type":"question","body":"I'm looking to introduce a unit testing framework into the mix at my job. We're using Visual Studio 2005 (though we may be moving to 2008 within the next 6 months) and work primarily in C#. If the framework has some kind of IDE integration that would be best, but I'm open to frameworks that don't have integration but are still relatively simple to get set up. I'm going to get resistance to it one way or another, so if I can make sure what I'm pushing isn't a pain in the neck, that would help my case. The obvious choice from the research I've done so far points to nUnit, but I'd like to get the impressions of someone who's actually used it before recommending it to my team. Has anyone out there used nUnit? If so, are there any pitfalls or limitations of which I should be aware? Are there other good options out there? If so, if you've used both nUnit at that, I'd greatly appreciate an idea of the strengths and weaknesses of them. "} {"user":"51","questionId":705,"creationDate":"2008-08-03T14:57:18Z","answerId":710,"type":"answer","body":"Check out VistaDB. They have a very good product, the server version (3.4) is in Beta and is very close to release. "} {"user":"91","questionId":709,"creationDate":"2008-08-03T14:57:44Z","answerId":712,"type":"answer","body":"Scott Hanselman had a good Podcast about this, entitled: \"The Past, Present and Future of .NET Unit Testing Frameworks\" : Hanselminutes #112 "} {"user":"34","questionId":709,"creationDate":"2008-08-03T14:59:20Z","answerId":713,"type":"answer","body":"I think NUnit is your best bet. With TestDriven.NET, you get great integration within VS.NET. (Resharper also has a unit test runner if you're using it). NUnit it simple to use and follows an established paradigm. You'll also find plenty of projects/tutorials/guides using it which always helps. Your other main choice is probably MBUnit, which is more and more position itself as the BDD framework of choice (in conjunction with Gallio http://www.gallio.org). "} {"user":"Nelson Marmol","tags":[".net","sql-server-2005","oledb","legacy","visual-foxpro"],"questionId":717,"creationDate":"2008-08-03T15:07:10Z","title":"Why doesn't VFP .NET OLEdb provider work in 64 bit Windows?","acceptedAnswerId":799,"type":"question","body":"I wrote a windows service using VB that read some legacy data from Visual Foxpro Databases to be inserted in SQL 2005. The problem is this use to run fine in Windows server 2003 32-Bits, but the client recently moved to Windows 2003 64-Bits and now the service won't work. I'm getting a message the the VFP .NET OLEdb provider is not found. I researched and everything seems to point out that there is no solution. Any Help, please... "} {"user":"27","questionId":709,"creationDate":"2008-08-03T15:07:20Z","answerId":718,"type":"answer","body":"Visual Studio 2008 has a built in test project type that works in a similar way to NUnit, but obviously has much tighter integration with Visual Studio (can run on every build and shows the results in a similar way to the conversion results page when upgrading solution files), but it is obviously not as mature as NUnit as it's pretty new and I'm not sure about how it handles mocking. But it would be worth looking into when your team moves to VS2008 "} {"user":"216","questionId":626,"creationDate":"2008-08-03T15:21:52Z","answerId":723,"type":"answer","body":"Another important but subtle difference between procs created with lambda and procs created with Proc.new is how they handle the return statement: In a lambda-created proc, the return statement returns only from the proc itself In a Proc.new-created proc, the return statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc! Here's lambda-created proc's return in action. It behaves in a way that you probably expect: def whowouldwin mylambda = lambda {return \"Freddy\"} mylambda.call # mylambda gets called and returns \"Freddy\", and execution # continues on the next line return \"Jason\" end whowouldwin #=> \"Jason\" Now here's a Proc.new-created proc's return doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise: def whowouldwin2 myproc = Proc.new {return \"Freddy\"} myproc.call # myproc gets called and returns \"Freddy\", # but also returns control from whowhouldwin2! # The line below *never* gets executed. return \"Jason\" end whowouldwin2 #=> \"Freddy\" Thanks to this surprising behavior (as well as less typing), I tend to favor using lambda over Proc.new when making procs. "} {"user":"205","questionId":651,"creationDate":"2008-08-03T15:24:38Z","answerId":725,"type":"answer","body":"It sounds like you've covered all the server-side bases--maybe it's a client issue? I assume your users have integrated authentication enabled in IE7? (Tools -> Internet Options -> Advanced -> Security). This is enabled by default. Also, is your site correctly recognized by IE7 as being in the Local Intranet zone? The IE7 default is to allow automatic logon only in that zone, so users would be prompted if IE thinks your site is on the internet. I believe using a hostname with a dot in it causes IE to place the site into the Internet zone. "} {"user":"user2189331","questionId":705,"creationDate":"2008-08-03T15:34:17Z","answerId":730,"type":"answer","body":"Why not use SQL Server 2005 Express edition? It really depends on what you mean by \"embedded\" - but you can redistribute SQLServer2005E with your applications and the user never has to know it's there. Embedding SQL Server Express in Applications Embedding SQL Server Express into Custom Applications "} {"user":"145","questionId":683,"creationDate":"2008-08-03T15:47:22Z","answerId":735,"type":"answer","body":"I think: #!/bin/python bar in dict(Foo) Is what you are thinking of. When trying to see if a certain key exists within a dictionary in python (python's version of a hash table) there are two ways to check. First is the has_key() method attached to the dictionary and second is the example given above. It will return a boolean value. That should answer your question. And now a little off topic to tie this in to the list comprehension answer previously given (for a bit more clarity). List Comprehensions construct a list from a basic for loop with modifiers. As an example (to clarify slightly), a way to use the in dict language construct in a list comprehension: Say you have a two dimensional dictionary foo and you only want the second dimension dictionaries which contain the key bar. A relatively straightforward way to do so would be to use a list comprehension with a conditional as follows: #!/bin/python baz = dict([(key, value) for key, value in foo if bar in value]) Note the if bar in value at the end of the statement**, this is a modifying clause which tells the list comprehension to only keep those key-value pairs which meet the conditional.** In this case baz is a new dictionary which contains only the dictionaries from foo which contain bar (Hopefully I didn't miss anything in that code example... you may have to take a look at the list comprehension documentation found in docs.python.org tutorials and at secnetix.de, both sites are good references if you have questions in the future.). "} {"user":"173","questionId":705,"creationDate":"2008-08-03T15:48:43Z","answerId":737,"type":"answer","body":"It sounds like ADO/Access is perfect for your needs. It's baked into the MS stack, well seasoned, and multi-user. You can programatically create a DB like so: Dim catalog as New ADOX.Catalog Catalog.Create(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\server\\path\\to\\db.mdb\") You can then use standard ADO.NET methods to interact with the database. "} {"user":"189","tags":["python","django","views","oop"],"questionId":742,"creationDate":"2008-08-03T15:55:28Z","title":"Class views in Django","acceptedAnswerId":33957,"type":"question","body":"Django view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc... One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? "} {"user":"154","questionId":683,"creationDate":"2008-08-03T15:59:19Z","answerId":745,"type":"answer","body":"Are you looking to get a list of objects that have a certain attribute? If so, a list comprehension is the right way to do this. result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')] "} {"user":"192","tags":["string","language-agnostic","format","title-case"],"questionId":746,"creationDate":"2008-08-03T16:03:48Z","title":"Format string to title case","type":"question","body":"How do I format a string to title case? "} {"user":"192","questionId":746,"creationDate":"2008-08-03T16:05:57Z","answerId":747,"type":"answer","body":"Here is a simple static method to do this in C#: public static string ToTitleCaseInvariant(string targetString) { return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString); } "} {"user":"58","questionId":746,"creationDate":"2008-08-03T16:12:43Z","answerId":749,"type":"answer","body":"In what language? In PHP it is: ucwords() example: $HelloWorld = ucwords('hello world'); "} {"user":"199","questionId":683,"creationDate":"2008-08-03T16:13:29Z","answerId":750,"type":"answer","body":"What I was thinking of can be achieved using list comprehensions, but I thought that there was a function that did this in a slightly neater way. i.e. 'bar' is a list of objects, all of which have the attribute 'id' The mythical functional way: foo = 12 foo in iter_attr(bar, 'id') The list comprehension way: foo = 12 foo in [obj.id for obj in bar] In retrospect the list comprehension way is pretty neat anyway. "} {"user":"219","questionId":746,"creationDate":"2008-08-03T16:25:07Z","answerId":751,"type":"answer","body":"Without using a ready-made function, a super-simple low-level algorithm to convert a string to title case: convert first character to uppercase. for each character in string, if the previous character is whitespace, convert character to uppercase. This asssumes the \"convert character to uppercase\" will do that correctly regardless of whether or not the character is case-sensitive (e.g., '+'). "} {"user":"192","tags":["c#",".net","performance","reflection"],"questionId":752,"creationDate":"2008-08-03T16:29:03Z","title":"Get a new object instance from a Type","acceptedAnswerId":755,"type":"question","body":"One may not always know the Type of an object at compile-time, but may need to create an instance of the Type. How do you get a new object instance from a Type? "} {"user":"192","questionId":752,"creationDate":"2008-08-03T16:31:22Z","answerId":753,"type":"answer","body":"One implementation of this problem is to attempt to call the parameter-less constructor of the Type: public static object GetNewObject(Type t) { try { return t.GetConstructor(new Type[] { }).Invoke(new object[] { }); } catch { return null; } } Here is the same approach, contained in a generic method: public static T GetNewObject() { try { return (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { }); } catch { return default(T); } } "} {"user":"142","questionId":746,"creationDate":"2008-08-03T16:33:51Z","answerId":754,"type":"answer","body":"If the language you are using has a supported method/function then just use that (as in the C# ToTitleCase method) If it does not, then you will want to do something like the following: Read in the string Take the first word Capitalize the first letter of that word 1 Go forward and find the next word Go to 3 if not at the end of the string, otherwise exit 1 To capitalize it in, say, C - use the ascii codes to find the integer value of the char and subtract 32 from it. There would need to be much more error checking in the code (ensuring valid letters etc.), and the \"Capitalize\" function will need to impose some sort of \"title-case scheme\" on the letters to check for words that do not need to be capatilised ('and', 'but' etc. Here is a good scheme) "} {"user":"34","questionId":752,"creationDate":"2008-08-03T16:35:34Z","answerId":755,"type":"answer","body":"The Activator class within the root System namespace is pretty powerful. There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at: http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx Here are some simple examples: ObjectType instance = (ObjectType)Activator.CreateInstance(objectType); ObjectType instance = (ObjectType)Activator.CreateInstance(\"MyAssembly\",\"MyNamespace.ObjectType\"); "} {"user":"user2189331","questionId":609,"creationDate":"2008-08-03T16:54:12Z","answerId":759,"type":"answer","body":"No, there are many applications built with VS2005 that have to support Windows XP, 2000, NT, the whole stack. The issue is that (by default) VS2005 wants to use libraries/exports not present on NT. See this thread for some background. Then start limiting your dependencies via preprocessor macros, and avoiding APIs which aren't supported on NT. "} {"user":"214","tags":[".net","internationalization","date","globalization"],"questionId":761,"creationDate":"2008-08-03T17:30:20Z","title":"Localising date format descriptors","acceptedAnswerId":762,"type":"question","body":"What is the best way to localise a date format descriptor? As anyone from a culture which does not use the mm/dd/yyyy format knows, it is annoying to have to enter dates in this format. The .NET framework provides some very good localisation support, so it's trivial to parse dates according to the users culture, but you often want to also display a helpful hint as to the format required (especially to distinguish between yy and yyyy which is interchangeable in most cultures). What is the best way to do this in a way that make sense to most users (e.g. dd/M/yyy is confusing because of the change in case and the switching between one and two letters). "} {"user":"214","questionId":761,"creationDate":"2008-08-03T17:31:31Z","answerId":762,"type":"answer","body":"Here is my current method. Any suggestions? Regex singleMToDoubleRegex = new Regex(\"(? http://woarl.com/db.py Oddly enough, this would produce an error import MySQLdb import cgi import cgitb; cgitb.enable() I looked at some of the other files I had up there and it seems that library was one of the ones I had already tried. "} {"user":"232","tags":["asp-classic","sftp"],"questionId":805,"creationDate":"2008-08-03T20:11:26Z","title":"ASP, need to use SFTP","acceptedAnswerId":894,"type":"question","body":"This is ASP classic, not .Net. We have to get a way to SFTP into a server to upload and download a couple of files, kicked off by a user. What have other people used to do SFTP in ASP classic? Not necessarily opposed to purchasing a control. "} {"user":"233","tags":["windows","visual-studio","registry","installation"],"questionId":810,"creationDate":"2008-08-03T20:35:01Z","title":"Visual Studio Setup Project - Per User Registry Settings","acceptedAnswerId":820,"type":"question","body":"I'm trying to maintain a Setup Project in Visual Studio 2003 (yes, it's a legacy application). The problem we have at the moment is that we need to write registry entries to HKCU for every user on the computer. They need to be in the HKCU rather than HKLM because they are the default user settings, and they do change per user. My feeling is that This isn't possible This isn't something the installer should be doing, but something the application should be doing (after all what happens when a user profile is created after the install?). With that in mind, I still want to change as little as possible in the application, so my question is, is it possible to add registry entries for every user in a Visual Studio 2003 setup project? And, at the moment the project lists five registry root keys (HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS, and User/Machine Hive). I don't really know anything about the Users root key, and haven't seen User/Machine Hive. Can anyone enlighten me on what they are? Perhaps they could solve my problem above. "} {"user":"234","questionId":13,"creationDate":"2008-08-03T20:40:33Z","answerId":817,"type":"answer","body":"The magic all seems to be in visitortime.getTimezoneOffset() That's cool, I didn't know about that. Does it work in IE, etc? From there you should be able to use JS to ajax, set cookies, whatever. I'd probably go the cookie route myself. You'll need to allow the user to change it though. We tried to use geolocation (via maxmind) to do this a while ago, and it was wrong reasonably often - enough to make it not worth doing, so we just let the user set it in their profile, and show a notice to users who haven't set theirs yet. "} {"user":"233","questionId":810,"creationDate":"2008-08-03T20:45:27Z","answerId":818,"type":"answer","body":"I'm partway to my solution with this entry on MSDN (don't know how I couldn't find it before). User/Machine Hive Subkeys and values entered under this hive will be installed under the HKEY_CURRENT_USER hive when a user chooses \"Just Me\" or the HKEY_USERS hive or when a user chooses \"Everyone\" during installation. Registry Editor "} {"user":"91","questionId":810,"creationDate":"2008-08-03T20:48:47Z","answerId":820,"type":"answer","body":"First: Yes, this is something that belongs in the Application for the exact reson you specified: What happens after new user profiles are created? Sure, if you're using a domain it's possible to have some stuff put in the registry on creation, but this is not really a use case. The Application should check if there are seetings and use the default settings if not. That being said, it IS possible to change other users Keys through the HKEY_USERS Hive. I have no experience with the Visual Studio 2003 Setup Project, so here is a bit of (totally unrelated) VBScript code that might just give you an idea where to look: const HKEY_USERS = &H80000003 strComputer = \".\" Set objReg=GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\default:StdRegProv\") strKeyPath = \"\" objReg.EnumKey HKEY_USERS, strKeyPath, arrSubKeys strKeyPath = \"\\Software\\Microsoft\\Windows\\CurrentVersion\\WinTrust\\Trust Providers\\Software Publishing\" For Each subkey In arrSubKeys objReg.SetDWORDValue HKEY_USERS, subkey & strKeyPath, \"State\", 146944 Next (Code Courtesy of Jeroen Ritmeijer) "} {"user":"101","tags":["algorithm","language-agnostic"],"questionId":826,"creationDate":"2008-08-03T21:08:54Z","title":"Efficiently get sorted sums of a sorted list","acceptedAnswerId":97294,"type":"question","body":"You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the ascending list of sums of every two numbers in that list. Duplicates in the resulting list are irrelevant, you can remove them or avoid them if you like. To be clear, I'm interested in the algorithm. Feel free to post code in any language and paradigm that you like. "} {"user":"234","questionId":810,"creationDate":"2008-08-03T21:17:33Z","answerId":829,"type":"answer","body":"I'm guessing that because you want to set it for all users, that you're on some kind of shared computer, which is probably running under a domain? HERE BE DRAGONS Let's say Joe and Jane regularly log onto the computer, then they will each have 'registries'. You'll then install your app, and the installer will employ giant hacks and disgusting things to set items under HKCU for them. THEN, bob will come along and log on (he, and 500 other people have accounts in the domain and so can do this). He's never used this computer before, so he has no registry. The first time he logs in, windows creates him one, but he won't have your setting. Your app then falls over or behaves incorrectly, and bob complains loudly about those crappy products from raynixon incorporated. The correct answer is to just have some default settings in your app, which can write them to the registry if it doesn't find them. It's general good practice that your app should never depend on the registry, and should create things as needed, for any registry entry, not just HKCU, anyway "} {"user":"224","tags":["c#","linq","left-join"],"questionId":832,"creationDate":"2008-08-03T21:22:52Z","title":"How do I most elegantly express left join with aggregate SQL as LINQ query","acceptedAnswerId":837,"type":"question","body":"SQL: SELECT u.id, u.name, isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault FROM universe u LEFT JOIN history h ON u.id=h.id AND h.dateCol /noconsolelogger /p:OutputPath=$(CCNetArtifactDirectory)\\test But that does not work. In fact, it kills the service with this error: ThoughtWorks.CruiseControl.Core.Config.Preprocessor.EvaluationException: Reference to unknown symbol CCNetArtifactDirectory Documentation is rather sparse, and google und mainly offers modifying the .sln Project file, which is what I want to avoid in order to be able to manually build this project later - I would really prefer /p:OutputPath. "} {"user":"204","questionId":696,"creationDate":"2008-08-03T21:31:14Z","answerId":836,"type":"answer","body":"Looks like a web service is going to be the answer for me. On a production box I'd rather not have to go through compiling and maintaining my own special installation of PHP since ODBC support needs to be compiled in, according to the PHP documentation. "} {"user":"224","questionId":832,"creationDate":"2008-08-03T21:31:17Z","answerId":837,"type":"answer","body":"A solution, albeit one that defers handling of the null value to the code, could be: DateTime yesterday = DateTime.Now.Date.AddDays(-1); var collection= from u in db.Universe select new { u.id, u.name, MaxDate =(DateTime?) ( from h in db.History where u.Id == h.Id && h.dateCol < yesterday select h.dateCol ).Max() }; This does not produce exactly the same SQL, but does provide the same logical result. Translating \"complex\" SQL queries to LINQ is not always straightforward. "} {"user":"60","questionId":833,"creationDate":"2008-08-03T21:31:40Z","answerId":838,"type":"answer","body":"If you expect infrequent collisions, Optimistic Concurrency is probably your best bet. Scott Mitchell wrote a comprehensive tutorial on implementing that pattern: Implementing Optimistic Concurrency "} {"user":"101","questionId":826,"creationDate":"2008-08-03T21:36:25Z","answerId":840,"type":"answer","body":"The best I could come up with is to produce a matrix of sums of each pair, and then merge the rows together, a-la merge sort. I feel like I'm missing some simple insight that will reveal a much more efficient solution. My algorithm, in Haskell: matrixOfSums list = [[a+b | b <- list, b >= a] | a <- list] sortedSums = foldl merge [] matrixOfSums --A normal merge, save that we remove duplicates merge xs [] = xs merge [] ys = ys merge (x:xs) (y:ys) = case compare x y of LT -> x:(merge xs (y:ys)) EQ -> x:(merge xs (dropWhile (==x) ys)) GT -> y:(merge (x:xs) ys) I found a minor improvement, one that's more amenable to lazy stream-based coding. Instead of merging the columns pair-wise, merge all of them at once. The advantage being that you start getting elements of the list immediately. -- wide-merge does a standard merge (ala merge-sort) across an arbitrary number of lists -- wideNubMerge does this while eliminating duplicates wideNubMerge :: Ord a => [[a]] -> [a] wideNubMerge ls = wideNubMerge1 $ filter (/= []) ls wideNubMerge1 [] = [] wideNubMerge1 ls = mini:(wideNubMerge rest) where mini = minimum $ map head ls rest = map (dropWhile (== mini)) ls betterSortedSums = wideNubMerge matrixOfSums However, if you know you're going to use all of the sums, and there's no advantage to getting some of them earlier, go with 'foldl merge []', as it's faster. "} {"user":"238","tags":["javascript","html","css","fonts"],"questionId":845,"creationDate":"2008-08-03T21:42:37Z","title":"Detecting which font was used in a web page","acceptedAnswerId":849,"type":"question","body":"Suppose I have the following CSS rule in my page: body { font-family: Calibri, Trebuchet MS, Helvetica, sans-serif; } How can I detect which one of the defined fonts was used in the user's browser? Edit for people wondering why I want to do this: The font I'm detecting contains glyph's that are not available in other fonts and when the user does not have the font I want to display a link asking the user to download that font so they can use my web application with the correct font. Currently I am displaying the download font link for all users, I want to only display this for people who do not have the correct font installed. "} {"user":"93","questionId":845,"creationDate":"2008-08-03T21:51:44Z","answerId":849,"type":"answer","body":"I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what they expected for the desired font as opposed to the derived font, it's present. Here's where it came from: Javascript/CSS Font Detector (ajaxian.com; 12 Mar 2007) "} {"user":"93","tags":["visual-studio","xslt","documentation","sandcastle","xml-comments"],"questionId":855,"creationDate":"2008-08-03T22:03:37Z","title":".Net XML comment into API Documentation","acceptedAnswerId":858,"type":"question","body":"Is there an easy way to produce MSDN-style documentation from the Visual Studio XML output? I'm not patient enough to set up a good xslt for it because I know I'm not the first person to cross this bridge. Also, I tried setting up sandcastle recently, but it really made my eyes cross. Either I was missing something important in the process or it is just way too involved. I know somebody out there has a really nice dead-simple solution. I'm reiterating here because I think my formatting made that paragraph non-inviting to read: I gave sandcastle a try but had a really hard time getting it set up. What I really have in mind is something much simpler. That is, unless I just don't understand the sandcastle process. It seemed like an awful lot of extra baggage to me just to produce something nice for the testers to work with. "} {"user":"34","questionId":855,"creationDate":"2008-08-03T22:12:52Z","answerId":858,"type":"answer","body":"You're looking for Sandcastle Project Page: Sandcastle Releases Blog: Sandcastle Blog NDoc Code Documentation Generator for .NET used to be the tool of choice, but support has all but stopped. "} {"user":"91","questionId":855,"creationDate":"2008-08-03T22:14:55Z","answerId":859,"type":"answer","body":"Have a look at Sandcastle, which does exactly that. It's also one of the more simpler solutions out there, and it's more or less the tool of choice, so in the long run, maybe we could help you to set up Sandcastle if you specify what issues you encountered during setup? "} {"user":"233","questionId":810,"creationDate":"2008-08-03T22:34:06Z","answerId":870,"type":"answer","body":"Despite what the MSDN article says about User/Machine Hive, it doesn't write to HKEY_USERS. Rather it writes to HKCU if you select Just Me and HKLM if you select everyone. So my solution is going to be to use the User/Machine Hive, and then in the application it checks if the registry entries are in HKCU and if not, copies them from HKLM. I know this probably isn't the most ideal way of doing it, but it has the least amount of changes. "} {"user":"203","tags":["svn","git"],"questionId":871,"creationDate":"2008-08-03T22:38:29Z","title":"Why is Git better than Subversion?","acceptedAnswerId":875,"type":"question","body":"I've been using Subversion for a few years and after using SourceSafe, I just love Subversion. Combined with TortoiseSVN, I can't really imagine how it could be any better. Yet there's a growing number of developers claiming that Subversion has problems and that we should be moving to the new breed of distributed version control systems, such as Git. How does Git improve upon Subversion? "} {"user":"150","questionId":871,"creationDate":"2008-08-03T22:44:26Z","answerId":873,"type":"answer","body":"Google Tech Talk: Linus Torvalds on git http://www.youtube.com/watch?v=4XpnKHJAok8 The Git Wiki's comparison page http://git.or.cz/gitwiki/GitSvnComparsion "} {"user":"91","questionId":871,"creationDate":"2008-08-03T22:45:44Z","answerId":875,"type":"answer","body":"Git is not better than Subversion. But is also not worse. It's different. The key difference is that it is decentralized. Imagine you are a developer on the road, you develop on your laptop and you want to have source control so that you can go back 3 hours. With Subversion, you have a Problem: The SVN Repository may be in a location you can't reach (in your company, and you don't have internet at the moment), you cannot commit. If you want to make a copy of your code, you have to literally copy/paste it. With Git, you do not have this problem. Your local copy is a repository, and you can commit to it and get all benefits of source control. When you regain connectivity to the main repository, you can commit against it. This looks good at first, but just keep in mind the added complexity to this approach. Git seems to be the \"new, shiny, cool\" thing. It's by no means bad (there is a reason Linus wrote it for the Linux Kernel development after all), but I feel that many people jump on the \"Distributed Source Control\" train just because it's new and is written by Linus Torvalds, without actually knowing why/if it's better. Subversion has Problems, but so does Git, Mercurial, CVS, TFS or whatever. Edit: So this answer is now a year old and still generates many upvotes, so I thought I'll add some more explanations. In the last year since writing this, Git has gained a lot of momentum and support, particularly since sites like GitHub really took off. I'm using both Git and Subversion nowadays and I'd like to share some personal insight. First of all, Git can be really confusing at first when working decentralized. What is a remote? and How to properly set up the initial repository? are two questions that come up at the beginning, especially compared to SVN's simple \"svnadmin create\", Git's \"git init\" can take the parameters --bare and --shared which seems to be the \"proper\" way to set up a centralized repository. There are reasons for this, but it adds complexity. The documentation of the \"checkout\" command is very confusing to people changing over - the \"proper\" way seems to be \"git clone\", while \"git checkout\" seems to switch branches. Git REALLY shines when you are decentralized. I have a server at home and a Laptop on the road, and SVN simply doesn't work well here. With SVN, I can't have local source control if I'm not connected to the repository (Yes, I know about SVK or about ways to copy the repo). With Git, that's the default mode anyway. It's an extra command though (git commit commits locally, whereas git push origin master pushes the master branch to the remote named \"origin\"). As said above: Git adds complexity. Two modes of creating repositories, checkout vs. clone, commit vs. push... You have to know which commands work locally and which work with \"the server\" (I'm assuming most people still like a central \"master-repository\"). Also, the tooling is still insufficient, at least on Windows. Yes, there is a Visual Studio AddIn, but I still use git bash with msysgit. SVN has the advantage that it's MUCH simpler to learn: There is your repository, all changes to towards it, if you know how to create, commit and checkout and you're ready to go and can pickup stuff like branching, update etc. later on. Git has the advantage that it's MUCH better suited if some developers are not always connected to the master repository. Also, it's much faster than SVN. And from what I hear, branching and merging support is a lot better (which is to be expected, as these are the core reasons it was written). This also explains why it gains so much buzz on the Internet, as Git is perfectly suited for Open Source projects: Just Fork it, commit your changes to your own Fork, and then ask the original project maintainer to pull your changes. With Git, this just works. Really, try it on Github, it's magic. What I also see are Git-SVN Bridges: The central repository is a Subversion repo, but developers locally work with Git and the bridge then pushes their changes to SVN. But even with this lengthy addition, I still stand by my core message: Git is not better or worse, it's just different. If you have the need for \"Offline Source Control\" and the willingness to spend some extra time learning it, it's fantastic. But if you have a strictly centralized Source Control and/or are struggling to introduce Source Control in the first place because your co-workers are not interested, then the simplicity and excellent tooling (at least on Windows) of SVN shine. "} {"user":"34","questionId":871,"creationDate":"2008-08-03T22:47:42Z","answerId":876,"type":"answer","body":"Well, it's distributed. Benchmarks indicate that it's considerably faster (given its distributed nature, operations like diffs and logs are all local so of course it's blazingly faster in this case), and working folders are smaller (which still blows my mind). When you're working on subversion, or any other client/server revision control system, you essentially create working copies on your machine by checking-out revisions. This represents a snapshot in time of what the repository looks like. You update your working copy via updates, and you update the repository via commits. With a distributed version control, you don't have a snapshot, but rather the entire codebase. Wanna do a diff with a 3 month old version? No problem, the 3 month old version is still on your computer. This doesn't only mean things are way faster, but if you're disconnected from your central server, you can still do many of the operations you're used to. In other words, you don't just have a snapshot of a given revision, but the entire codebase. You'd think that Git would take up a bunch of space on your harddrive, but from a couple benchmarks I've seen, it actually takes less. Don't ask me how. I mean, it was built by Linus, he knows a thing or two about filesystems I guess. "} {"user":"206","questionId":717,"creationDate":"2008-08-03T22:48:47Z","answerId":877,"type":"answer","body":"You'll need to compile with the target CPU set to x86 to force your code to use the 32 bit version of the VFP OLE Db provider. Microsoft has stated that there are no plans on releasing a 64-bit edition of the Visual FoxPro OLE Db provider. For what's worth, Microsoft has also stated that VFP 9 is the final version of Visual FoxPro and support will end in 2015. If you need the OLE DB provider for VFP 9, you can get it here. "} {"user":"58","tags":["php","variables","pass-by-reference","pass-by-value"],"questionId":879,"creationDate":"2008-08-03T22:51:41Z","title":"Are PHP Variables passed by value or by reference?","acceptedAnswerId":885,"type":"question","body":"Are PHP variables passed by value or by reference? "} {"user":"34","questionId":879,"creationDate":"2008-08-03T22:52:11Z","answerId":880,"type":"answer","body":"Depends on the version, 4 is by value, 5 is by reference. "} {"user":"58","questionId":879,"creationDate":"2008-08-03T22:52:17Z","answerId":881,"type":"answer","body":"PHP variables are assigned by value, passed to functions by value, and when containing/representing objects are passed by reference. You can force variables to pass by reference using an & Assigned by value/reference example: $var1 = \"test\"; $var2 = $var1; $var2 = \"new test\"; $var3 = &$var2; $var3 = \"final test\"; print (\"var1: $var1, var2: $var2, var3: $var3); would output \"var1: test, var2: final test, var3: final test\". Passed by value/reference exampe: $var1 = \"foo\"; $var2 = \"bar\"; changeThem($var1, $var2); print \"var1: $var1, var2: $var2\"; function changeThem($var1, &$var2){ $var1 = \"FOO\"; $var2 = \"BAR\"; } would output: \"var1: foo, var2 BAR\". Object variables passed by reference exampe: class Foo{ public $var1; function __construct(){ $this->var1 = \"foo\"; } public function printFoo(){ print $this->var1; } } $foo = new Foo(); changeFoo($foo); $foo->printFoo(); function changeFoo($foo){ $foo->var1 = \"FOO\"; } Would output: \"FOO\" (that last example could be better probably...) "} {"user":"159","questionId":826,"creationDate":"2008-08-03T23:06:15Z","answerId":884,"type":"answer","body":"Rather than coding this out, I figure I'll pseudo-code it in steps and explain my logic, so that better programmers can poke holes in my logic if necessary. On the first step we start out with a list of numbers length n. For each number we need to create a list of length n-1 becuase we aren't adding a number to itself. By the end we have a list of about n sorted lists that was generated in O(n^2) time. step 1 (startinglist) for each number num1 in startinglist for each number num2 in startinglist add num1 plus num2 into templist add templist to sumlist return sumlist In step 2 because the lists were sorted by design (add a number to each element in a sorted list and the list will still be sorted) we can simply do a mergesort by merging each list together rather than mergesorting the whole lot. In the end this should take O(n^2) time. step 2 (sumlist) create an empty list mergedlist for each list templist in sumlist set mergelist equal to: merge(mergedlist,templist) return mergedlist The merge method would be then the normal merge step with a check to make sure that there are no duplicate sums. I won't write this out because anyone can look up mergesort. So there's my solution. The entire algorithm is O(n^2) time. Feel free to point out any mistakes or improvements. "} {"user":"91","questionId":879,"creationDate":"2008-08-03T23:06:56Z","answerId":885,"type":"answer","body":"It's by value according to the PHP Documentation. By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition. "} {"user":"153","questionId":871,"creationDate":"2008-08-03T23:08:23Z","answerId":886,"type":"answer","body":"Git and DVCS in general is great for developers doing a lot of coding independently of each other because everyone has their own branch. If you need a change from someone else, though, she has to commit to her local repo and then she must push that changeset to you or you must pull it from her. My own reasoning also makes me think DVCS makes things harder for QA and release management if you do things like centralized releases. Someone has to be responsible for doing that push/pull from everyone else's repository, resolving any conflicts that would have been resolved at initial commit time before, then doing the build, and then having all the other developers re-sync their repos. All of this can be addressed with human processes, of course; DVCS just broke something that was fixed by centralized version control in order to provide some new conveniences. "} {"user":"131","tags":["php","eclipse","debugging","phpstorm","xdebug"],"questionId":888,"creationDate":"2008-08-03T23:18:21Z","title":"How do you debug PHP scripts?","acceptedAnswerId":890,"type":"question","body":"How do you debug PHP scripts? I am aware of basic debugging such as using the Error Reporting. The breakpoint debugging in PHPEclipse is also quite useful. What is the best (in terms of fast and easy) way to debug in phpStorm or any other IDE? "} {"user":"91","questionId":888,"creationDate":"2008-08-03T23:20:48Z","answerId":889,"type":"answer","body":"I've used the Zend Studio (5.5), together with Zend Platform. That gives proper debugging, breakpoints/stepping over the code etc., although at a price. "} {"user":"200","questionId":888,"creationDate":"2008-08-03T23:28:39Z","answerId":890,"type":"answer","body":"Try Eclipse PDT to setup an Eclipse environment that has debugging features like you mentioned. The ability to step into the code is a much better way to debug then the old method of var_dump and print at various points to see where your flow goes wrong. When all else fails though and all I have is SSH and vim I still var_dump()/die() to find where the code goes south. "} {"user":"234","questionId":888,"creationDate":"2008-08-03T23:32:13Z","answerId":891,"type":"answer","body":"print_r( debug_backtrace() ); or something like that :-) "} {"user":"234","questionId":871,"creationDate":"2008-08-03T23:38:05Z","answerId":893,"type":"answer","body":"It's all about the ease of use/steps required to do something. If I'm developing a single project on my PC/laptop, git is better, because it is far easier to set up and use. You don't need a server, and you don't need to keep typing repository URL's in when you do merges. If it were just 2 people, I'd say git is also easier, because you can just push and pull from eachother. Once you get beyond that though, I'd go for subversion, because at that point you need to set up a 'dedicated' server or location. You can do this just as well with git as with SVN, but the benefits of git get outweighed by the need to do additional steps to synch with a central server. In SVN you just commit. In git you have to git commit, then git push. The additional step gets annoying simply because you end up doing it so much. SVN also has the benefit of better GUI tools, however the git ecosystem seems to be catching up quickly, so I wouldn't worry about this in the long term. "} {"user":"200","questionId":805,"creationDate":"2008-08-03T23:52:47Z","answerId":894,"type":"answer","body":"If you have the ability to use WScript.Shell then you can just execute pscp.exe from the Putty package. Obviously this is less then ideal but it will get the job done and let you use SCP/SFTP in classic ASP. "} {"user":"243","questionId":194,"creationDate":"2008-08-03T23:56:54Z","answerId":895,"type":"answer","body":"I am by no means authoritative, but I believe the only supported path is from 6.5 to 7. Certainly that would be the most sane route, then I believe you can migrate from 7 directly to 2005 pretty painlessly. As for scripting out all the objects - I would advise against it as you will inevitably miss something (unless your database is truly trivial). "} {"user":"34","questionId":879,"creationDate":"2008-08-03T23:57:46Z","answerId":896,"type":"answer","body":"http://www.php.net/manual/en/migration5.oop.php In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier). "} {"user":"137","questionId":879,"creationDate":"2008-08-04T00:05:05Z","answerId":897,"type":"answer","body":"Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There's quite an interesting article from Linux Journal from 2006 which mentions this and other OO differences between 4 and 5. http://www.linuxjournal.com/article/9170 "} {"user":"200","tags":["language-agnostic","unicode","localization","internationalization"],"questionId":898,"creationDate":"2008-08-04T00:08:51Z","title":"Internationalization in your projects","type":"question","body":"How have you implemented Internationalization (i18n) in actual projects you've worked on? I took an interest in making software cross-cultural after I read the famous post by Joel, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). However, I have yet to able to take advantage of this in a real project, besides making sure I used Unicode strings where possible. But making all your strings Unicode and ensuring you understand what encoding everything you work with is in is just the tip of the i18n iceberg. Everything I have worked on to date has been for use by a controlled set of US English speaking people, or i18n just wasn't something we had time to work on before pushing the project live. So I am looking for any tips or war stories people have about making software more localized in real world projects. "} {"user":"34","tags":["html","css","text"],"questionId":904,"creationDate":"2008-08-04T00:17:34Z","title":"How to word-break on a dash?","acceptedAnswerId":911,"type":"question","body":"Given a relatively simple CSS: div { width: 150px; }
How do I make it so that the string stays constrained to the width of 150, and simply wraps to a newline on the hyphen? "} {"user":"204","tags":["sql-server","sql-server-2005","windows-server-2003"],"questionId":905,"creationDate":"2008-08-04T00:17:55Z","title":"Client collation and SQL Server 2005","acceptedAnswerId":942,"type":"question","body":"We're upgrading an existing program from Win2k/SQL Server 2k to Windows 2003 and SQL Server 2005 as well as purchasing a new program that also uses 2k3/2k5. The vendor says that for us to host both databases we need to get the Enterprise version because the softwares clients use different collation for the connections and only Enterprise supports this. I cannot find anything on MS's site to support this and, honestly, don't want to pay the extra for Enterprise if the Standard edition works. Am I missing some not talked about feature of SQL Server or is this, as I suspect, a vendor trying to upsell me? "} {"user":"122","questionId":898,"creationDate":"2008-08-04T00:23:00Z","answerId":906,"type":"answer","body":"I worked on a project for my previous employer that used .NET, and there was a built in .resx format we used. We basically had a file that had all translations in the .resx file, and then multiple files with different translations. The consequence of this is that you have to be very diligent about ensuring that all strings visible in the application are stored in the .resx, and anytime one is changed you have to update all languages you support. If you get lazy and don't notify the people in charge of translations, or you embed strings without going through your localization system, it will be a nightmare to try and fix it later. Similarly, if localization is an afterthought, it will be very difficult to put in place. Bottom line, if you don't have all visible strings stored externally in a standard place, it will be very difficult to find all that need to be localized. One other note, very strictly avoid concatenating visible strings directly, such as String message = \"The \" + item + \" is on sale!\"; Instead, you must use something like String message = String.Format(\"The {0} is on sale!\", item); The reason for this is that different languages often order the words differently, and concatenating strings directly will need a new build to fix, but if you used some kind of string replacement mechanism like above, you can modify your .resx file (or whatever localization files you use) for the specific language that needs to reorder the words. "} {"user":"243","questionId":194,"creationDate":"2008-08-04T00:23:55Z","answerId":908,"type":"answer","body":"If you can find a professional or some other super-enterprise version of Visual Studio 6.0 - it came with a copy of MSDE (Basically the predecessor to SQL Express). I believe MSDE 2000 is still available as a free download from Microsoft, but I don't know if you can migrate directly from 6.5 to 2000. I think in concept, you won't likely face any danger. Years of practice however tell me that you will always miss some object, permission, or other database item that won't manifest itself immediately. If you can script out the entire dump, the better. As you will be less likely to miss something - and if you do miss something, it can be easily added to the script and fixed. I would avoid any manual steps (other than hitting the enter key once) like the plague. "} {"user":"136","questionId":871,"creationDate":"2008-08-04T00:24:15Z","answerId":910,"type":"answer","body":"With Git, you can do practically anything offline, because everybody has their own repository. Making branches and merging between branches is really easy. Even if you don't have commit rights for a project, you can still have your own repository online, and publish \"push requests\" for your patches. Everybody who likes your patches can pull them into their project, including the official maintainers. It's trivial to fork a project, modify it, and still keep merging in the bugfixes from the HEAD branch. Git works for the Linux kernel developers. That means it is really fast (it has to be), and scales to thousands of contributors. Git also uses less space (up to 30 times less space for the Mozilla repository). Git is very flexible, very TIMTOWTDI (There is more than one way to do it). You can use whatever workflow you want, and Git will support it. Finally, there's GitHub, a great site for hosting your Git repositories. Drawbacks of Git: it's much harder to learn, because Git has more concepts and more commands. revisions don't have version numbers like in subversion many Git commands are cryptic, and error messages are very user-unfriendly it lacks a good GUI (such as the great TortoiseSVN) "} {"user":"55","questionId":904,"creationDate":"2008-08-04T00:25:11Z","answerId":911,"type":"answer","body":"Replace your hyphens with this: ­ It's called a \"soft\" hyphen. div { width: 150px; }
"} {"user":"200","questionId":904,"creationDate":"2008-08-04T00:25:28Z","answerId":912,"type":"answer","body":"As part of CSS3, it is not yet fully supported, but you can find information on word-wrapping here. Another option is the wbr tag, ­, and ​ none of which are fully supported either. "} {"user":"91","questionId":898,"creationDate":"2008-08-04T00:35:14Z","answerId":921,"type":"answer","body":"Some fun things: Having a PHP and MySQL Application that works well with German and French, but now needs to support Russian and Chinese. I think I move this over to .net, as PHP's Unicode support is - in my opinion - not really good. Sure, juggling around with utf8_de/encode or the mbstring-functions is fun. Almost as fun as having Freddy Krüger visit you at night... Realizing that some languages are a LOT more Verbose than others. German is a LOT more verbose than English usually, and seeing how the German Version destroys the User Interface because too little space was allocated was not fun. Some products gained some fame for their creative ways to work around that, with Oblivion's \"Schw.Tr.d.Le.En.W.\" being memorable :-) Playing around with date formats, woohoo! Yes, there ARE actually people in the world who use date formats where the day goes in the middle. Sooooo much fun trying to find out what 07/02/2008 is supposed to mean, just because some users might believe it could be July 2... But then again, you guys over the pond may believe the same about users who put the month in the middle :-P, especially because in English, July 2 sounds a lot better than 2nd of July, something that does not neccessarily apply to other languages (i.e. in German, you would never say Juli 2 but always Zweiter Juli). I use 2008-02-07 whenever possible. It's clear that it means February 7 and it sorts properly, but dd/mm vs. mm/dd can be a really tricky problem. Anoter fun thing, Number formats! 10.000,50 vs 10,000.50 vs. 10 000,50 vs. 10'000,50... This is my biggest nightmare right now, having to support a multi-cultural environent but not having any way to reliably know what number format the user will use. Formal or Informal. In some language, there are two ways to address people, a formal way and a more informal way. In English, you just say \"You\", but in German you have to decide between the formal \"Sie\" and the informal \"Du\", same for French Tu/Vous. It's usually a safe bet to choose the formal way, but this is easily overlooked. Calendars. In Europe, the first day of the Week is Monday, whereas in the US it's Sunday. Calendar Widgets are nice. Showing a Calendar with Sunday on the left and Saturday on the right to a European user is not so nice, it confuses them. "} {"user":"245","tags":["c#","database","loops","connection"],"questionId":930,"creationDate":"2008-08-04T00:47:25Z","title":"How do I connect to a database and loop over a recordset in C#?","acceptedAnswerId":951,"type":"question","body":"What's the simplest way to connect and query a database for a set of records in C#? "} {"user":"116","questionId":88,"creationDate":"2008-08-04T00:51:52Z","answerId":931,"type":"answer","body":"@Bernard: I have to admit, most of your example went straight over my head. It does compile, and seems to work, though. Is this safe for SMP systems or SpeedStep? That's a good question... I think the code's ok. From a practical standpoint, we use it in my company every day, and we run on a pretty wide array of boxes, everything from 2-8 cores. Of course, YMMV, etc, but it seems to be a reliable and low-overhead (because it doesn't make a context switch into system-space) method of timing. Generally how it works is: declare the block of code to be assembler (and volatile, so the optimizer will leave it alone). execute the CPUID instruction. In addition to getting some CPU information (which we don't do anything with) it synchronizes the CPU's execution buffer so that the timings aren't affected by out-of-order execution. execute the rdtsc (read timestamp) execution. This fetches the number of machine cycles executed since the processor was reset. This is a 64-bit value, so with current CPU speeds it will wrap around every 194 years or so. Interestingly, in the original Pentium reference, they note it wraps around every 5800 years or so. the last couple of lines store the values from the registers into the variables hi and lo, and put that into the 64-bit return value. Specific notes: out-of-order execution can cause incorrect results, so we execute the \"cpuid\" instruction which in addition to giving you some information about the cpu also synchronizes any out-of-order instruction execution. Most OS's synchronize the counters on the CPUs when they start, so the answer is good to within a couple of nano-seconds. The hibernating comment is probably true, but in practice you probably don't care about timings across hibernation boundaries. regarding speedstep: Newer Intel CPUs compensate for the speed changes and returns an adjusted count. I did a quick scan over some of the boxes on our network and found only one box that didn't have it: a Pentium 3 running some old database server. (these are linux boxes, so I checked with: grep constant_tsc /proc/cpuinfo) I'm not sure about the AMD CPUs, we're primarily an Intel shop, although I know some of our low-level systems gurus did an AMD evaluation. Hope this satisfies your curiosity, it's an interesting and (IMHO) under-studied area of programming. You know when Jeff and Joel were talking about whether or not a programmer should know C? I was shouting at them, \"hey forget that high-level C stuff... assembler is what you should learn if you want to know what the computer is doing!\" "} {"user":"246","tags":["string","postgresql","escaping"],"questionId":935,"creationDate":"2008-08-04T01:00:24Z","title":"String literals and escape characters in postgresql","acceptedAnswerId":938,"type":"question","body":"Attempting to insert an escape character into a table results in a warning. For example: create table EscapeTest (text varchar(50)); insert into EscapeTest (text) values ('This is the first part \\n And this is the second'); Produces the warning: WARNING: nonstandard use of escape in a string literal (Using PSQL 8.2) Anyone know how to get around this? "} {"user":"246","questionId":935,"creationDate":"2008-08-04T01:07:03Z","answerId":938,"type":"answer","body":"Partially. The text is inserted, but the warning is still generated. I found a discussion that indicated the text needed to be preceded with 'E', as such: insert into EscapeTest (text) values (E'This is the first part \\n And this is the second'); This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked. As such: insert into EscapeTest (text) values (E'This is the first part \\\\n And this is the second'); "} {"user":"244","questionId":123,"creationDate":"2008-08-04T01:07:07Z","answerId":939,"type":"answer","body":"There is nothing I know of that can do this without you at least writing a little bit of code... You will need 2 separate library: A CSV Parser Framework An XML Serialization Framework The CSV parser I would recommend (unless you want to have a little bit of fun to write your own CSV Parser) is OpenCSV (A SourceForge Project for parsing CSV Data) The XML Serialization Framework should be something that can scale in case you want to transform large (or huge) CSV file to XML: My recommendation is the Sun Java Streaming XML Parser Framework (See here) which allows pull-parsing AND serialization. "} {"user":"243","questionId":930,"creationDate":"2008-08-04T01:07:14Z","answerId":940,"type":"answer","body":"Very roughly and from memory since I don't have code on this laptop: using (OleDBConnection conn = new OleDbConnection()) { conn.ConnectionString = \"Whatever connection string\"; using (OleDbCommand cmd = new OleDbCommand()) { cmd.Connection = conn; cmd.CommandText = \"Select * from CoolTable\"; using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { // do something like Console.WriteLine(dr[\"column name\"] as String); } } } } "} {"user":"206","questionId":905,"creationDate":"2008-08-04T01:13:06Z","answerId":942,"type":"answer","body":"All editions of SQL Server 2000/2005/2008 support having multiple databases, each using their own collation sequence. You don't need the Enterprise version. When you have a database that uses a collation sequence that is different from default collation for the database server, you will need to take some extra precautions if you use temporary tables and/or table variables. Temp tables/variables live in the tempdb database, which uses the collation seqyuence used by by the master databases. Just remember to use \"COLLATE database_default\" when defining character fields in the temp tables/variables. I blogged about that not too long ago, if you want some more details. "} {"user":"91","questionId":935,"creationDate":"2008-08-04T01:14:57Z","answerId":943,"type":"answer","body":"Cool. I also found the documentation regarding the E: http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS PostgreSQL also accepts \"escape\" string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g. E'foo'. (When continuing an escape string constant across lines, write E only before the first opening quote.) Within an escape string, a backslash character (\\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represents a special byte value. \\b is a backspace, \\f is a form feed, \\n is a newline, \\r is a carriage return, \\t is a tab. Also supported are \\digits, where digits represents an octal byte value, and \\xhexdigits, where hexdigits represents a hexadecimal byte value. (It is your responsibility that the byte sequences you create are valid characters in the server character set encoding.) Any other character following a backslash is taken literally. Thus, to include a backslash character, write two backslashes (\\\\). Also, a single quote can be included in an escape string by writing \\', in addition to the normal way of ''. "} {"user":"233","tags":["c#",".net","exception","exception-handling"],"questionId":944,"creationDate":"2008-08-04T01:15:38Z","title":"Unhandled Exception Handler in .NET 1.1","acceptedAnswerId":1016,"type":"question","body":"I'm maintaining a .NET 1.1 application, and one of the things I've been tasked with is making sure the user doesn't see any unfriendly error notifications. I've added handlers to Application.ThreadException and AppDomain.CurrentDomain.UnhandledException, which do get called. My problem is that the standard CLR error dialog is still displayed (before the exception handler is called). Jeff talks about this problem on his blog here and here. But there's no solution. So what is the standard way in .NET 1.1 to handle uncaught exceptions and display a friendly dialog box? Edit: Jeff's response was marked as the correct answer, because the link he provided has the most complete information on how to do what's required. "} {"user":"243","tags":["vb6"],"questionId":947,"creationDate":"2008-08-04T01:22:49Z","title":"How to use a mutex in Visual Basic","acceptedAnswerId":1028,"type":"question","body":"I have imported the kernel32 library so I have the createMutex function available but I am not quite sure of the various parameters and return values. This is classic Visual Basic, not Visual Basic.NET but I can probably work with either language in the form of an answer. "} {"user":"206","questionId":194,"creationDate":"2008-08-04T01:29:18Z","answerId":950,"type":"answer","body":"You can upgrade 6.5 to SQL Server 2000. You may have an easier time getting a hold of SQL Server or the 2000 version of the MSDE. Microsoft has a page on going from 6.5 to 2000. Once you have the database in 2000 format, SQL Server 2005 will have no trouble upgrading it to the 2005 format. If you don't have SQL Server 2000, you can download the MSDE 2000 version directly from Microsoft. "} {"user":"49","questionId":930,"creationDate":"2008-08-04T01:31:31Z","answerId":951,"type":"answer","body":"@Goyuix -- that's excellent for something written from memory. tested it here -- found the connection wasn't opened. Otherwise very nice. using System.Data.OleDb; ... using (OleDbConnection conn = new OleDbConnection()) { conn.ConnectionString = \"Provider=sqloledb;Data Source=yourServername\\\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;\"; using (OleDbCommand cmd = new OleDbCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandText = \"Select * from yourTable\"; using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Console.WriteLine(dr[\"columnName\"]); } } } } "} {"user":"101","questionId":164,"creationDate":"2008-08-04T02:14:59Z","answerId":971,"type":"answer","body":"Encoding flash video is actually very easy with ffmpeg. You can use one command to convert from just about any video format, ffmpeg is smart enough to figure the rest out, and it'll use every processor on your machine. Invoking it is easy: ffmpeg -i input.avi output.flv ffmpeg will guess at the bitrate you want, but if you'd like to specify one, you can use the -b option, so -b 500000 is 500kbps for example. There's a ton of options of course, but I generally get good results without much tinkering. This is a good place to start if you're looking for more options: video options. You don't need a special web server to show flash video. I've done just fine by simply pushing .flv files up to a standard web server, and linking to them with a good swf player, like flowplayer. WMVs are fine if you can be sure that all of your users will always use [a recent, up to date version of] Windows only, but even then, Flash is often a better fit for the web. The player is even extremely skinnable and can be controlled with javascript. "} {"user":"145","tags":["python","oop","methods","monkeypatching"],"questionId":972,"creationDate":"2008-08-04T02:17:51Z","title":"Adding a Method to an Existing Object Instance","acceptedAnswerId":2982,"type":"question","body":"I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python. I understand that it's not always good to do so. But, how might one do this? This answer looks good, I tried it but it appears that it ends up being not a true method. from SomeOtherProduct.SomeModule import SomeClass def speak(self): return \"ook ook eee eee eee!\" SomeClass.speak = speak That example defines the new patch function with an argument of self, but if you write actual code that way, the now patched class method asks for an argument named self (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call class.patch(obj) instead of just class.patch() if you want the same functionality as a true method. It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function (and as such is callable). Is there any way to attach an actual method to a class? "} {"user":"116","questionId":833,"creationDate":"2008-08-04T02:30:09Z","answerId":981,"type":"answer","body":"The database will do this for you. Look at \"select ... for update\", which is designed just for this kind of thing. It will give you a write lock on the selected rows, which you can then commit or roll back. "} {"user":"200","questionId":972,"creationDate":"2008-08-04T02:31:13Z","answerId":982,"type":"answer","body":"In Python monkey patching generally works by overwriting a class or functions signature with your own. Below is an example from the Zope Wiki: from SomeOtherProduct.SomeModule import SomeClass def speak(self): return \"ook ook eee eee eee!\" SomeClass.speak = speak That code will overwrite/create a method called speak on the class. In Jeff Atwood's recent post on monkey patching. He shows an example in C# 3.0 which is the current language I use for work. "} {"user":"122","questionId":972,"creationDate":"2008-08-04T02:36:40Z","answerId":984,"type":"answer","body":"I don't know Python syntax, but I know Ruby can do it, and it is rather trivial. Let's say you want to add a method to Array that prints the length to standard out: class Array def print_length puts length end end If you don't want to modify the whole class, you can just add the method to a single instance of the array, and no other arrays will have the method: array = [1, 2, 3] def array.print_length puts length end Just be aware of the issues involved in using this feature. Jeff Atwood actually wrote about it not too long ago. "} {"user":"1","questionId":944,"creationDate":"2008-08-04T02:45:07Z","answerId":986,"type":"answer","body":"is this a console app or a winforms app? If it's a .NET 1.1 console app this is, sadly, by design -- it's confirmed by a MSFT dev in the second blog post you referenced: BTW, on my 1.1 machine the example from MSDN does have the expected output; it's just that the second line doesn't show up until after you've attached a debugger (or not). In v2 we've flipped things around so that the UnhandledException event fires before the debugger attaches, which seems to be what most people expect. Sounds like .NET 2.0 does this better (thank goodness), but honestly, I never had time to go back and check. "} {"user":"233","questionId":944,"creationDate":"2008-08-04T02:54:15Z","answerId":990,"type":"answer","body":"It's a WinForms app. The exceptions that are caught by Application.ThreadException work fine, and I don't get the ugly .NET exception box (OK to terminate, cancel to debug? who came up with that??). I was getting some exceptions that weren't being caught by that and ended up going to the AppDomain.UnhandledException event that were causing problems. I think I've caught most of those exceptions and I am displaying them in our nice error box now. So I'll just have to hope there are not some other circumstances that would cause exceptions to not be caught by the Application.ThreadException handler. "} {"user":"85","tags":["linux","unix","vi"],"questionId":1005,"creationDate":"2008-08-04T03:34:02Z","title":"Getting root permissions on a file inside of vi?","acceptedAnswerId":37042,"type":"question","body":"Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type sudo vi filename Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it. "} {"user":"55","questionId":1005,"creationDate":"2008-08-04T03:39:31Z","answerId":1006,"type":"answer","body":"A quick Google seems to give this advice: Don't try to edit if it's read-only. You might be able to change the permissions on the file. (Whether or not it will let you save is up to experimentation.) If you still edited anyway, save to a temporary file and then move it. http://ubuntuforums.org/showthread.php?t=782136 "} {"user":"67","tags":["c#","asp.net"],"questionId":1010,"creationDate":"2008-08-04T03:59:42Z","title":"How to get the value of built, encoded ViewState?","acceptedAnswerId":1074,"type":"question","body":"I need to grab the base64-encoded representation of the ViewState. Obviously this would not be available until fairly late in the request lifecycle, which is OK. For example, if the output of the page includes: I need a way on the server side to get the value \"/wEPDwUJODU0Njc5MD...==\" To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being sent to the client, not the ViewState I'm getting back from them. "} {"user":"13","questionId":1005,"creationDate":"2008-08-04T04:04:52Z","answerId":1012,"type":"answer","body":"Ryan's advice is generally good, however, if following step 3, don't move the temporary file; it'll have the wrong ownership and permissions. Instead, sudoedit the correct file and read in the contents (using :r or the like) of the temporary file. If following step 2, use :w! to force the file to be written. "} {"user":"1","questionId":944,"creationDate":"2008-08-04T04:31:02Z","answerId":1016,"type":"answer","body":"Oh, in WinForms you definitely should be able to get it to work. The only thing you have to watch out for is things happening on different threads. I have an old CodeProject article here which should help: http://www.codeproject.com/KB/exception/ExceptionHandling.aspx "} {"user":"93","questionId":930,"creationDate":"2008-08-04T04:45:05Z","answerId":1022,"type":"answer","body":"That's definitely a good way to do it. But you if you happen to be using a database that supports LINQ to SQL, it can be a lot more fun. It can look something like this: MyDB db = new MyDB(\"Data Source=...\"); var q = from db.MyTable select c; foreach (var c in q) Console.WriteLine(c.MyField.ToString()); "} {"user":"231","questionId":835,"creationDate":"2008-08-04T04:45:12Z","answerId":1023,"type":"answer","body":"The CCNetArtifactDirectory is passed to the MSBuild by default, so you dont need to worry about it. MSBuild will place the build output in the \"bin location\" relevant to the working directory that you have specified. c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe C:\\data\\projects\\FooSolution\\ FooSolution.sln /noconsolelogger /p:Configuration=Debug So in the above example your build output will be put in C:\\data\\projects\\FooSolution[ProjectName]\\bin\\Debug. Should you want to output to a different location you may want to look at of the tag in CCNET. C:\\data\\projects\\FooSolution\\FooProject\\bin\\Debug C:\\published\\FooSolution\\ false This will allow you to publish your output to a different location. "} {"user":"234","tags":["ruby-on-rails","ruby","exception","plugins"],"questionId":1024,"creationDate":"2008-08-04T04:48:38Z","title":"How do I fix 'Unprocessed view path found' error with ExceptionNotifier plugin in rails 2.1?","acceptedAnswerId":171170,"type":"question","body":"After upgrading a rails 1.2 website to 2.1, the ExceptionNotifier plugin no longer works, complaining about this error: ActionView::TemplateFinder::InvalidViewPath: Unprocessed view path found: \"/path/to/appname/vendor/plugins/exception_notification/lib/../views\". Set your view paths with #append_view_path, #prepend_view_path, or #view_paths=. What causes it and how do I fix it? "} {"user":"77","questionId":947,"creationDate":"2008-08-04T04:48:40Z","answerId":1025,"type":"answer","body":"Well, based on the documentation it looks like: Security attributes (can pass null) Whether it's initially owned (can pass false) The name of it HTH "} {"user":"234","questionId":1024,"creationDate":"2008-08-04T04:50:44Z","answerId":1026,"type":"answer","body":"This was caused by a change in rails 2.1 which prevents rails from loading views from any arbitrary path for security reasons. There is now an updated version of the plugin on github, so the solution is to use that. The old solution here for posterity To work around it, edit init.rb under your vendor/plugins/exception_notification directory, and add the following code to the end ActionController::Base.class_eval do append_view_path File.dirname(__FILE__) + '/lib/../views' end This adds the ExceptionNotifier plugins' views folder to the list, so it is allowed to load them. "} {"user":"user2189331","questionId":947,"creationDate":"2008-08-04T04:58:40Z","answerId":1028,"type":"answer","body":"The VB code looks something like this: hMutex = CreateMutex(ByVal 0&, 1, ByVal 0&) The first parameter is a pointer to an SECURITY_ATTRIBUTES structure. If you don't know what it is, you don't need it. Pass NULL (0). The second parameter is TRUE (non-zero, or 1) if the calling thread should take ownership of the mutex. FALSE otherwise. The third parameter is the mutex name and may be NULL (0), as shown. If you need a named mutex, pass the name (anything unique) in. Not sure whether the VB wrapper marshals the length-prefixed VB string type (BSTR) over to a null-terminated Ascii/Unicode string if not, you'll need to do that and numerous examples are out there. Good luck! "} {"user":"87","tags":["ip","lookup","country"],"questionId":1033,"creationDate":"2008-08-04T05:15:35Z","title":"How to get the Country according to a certain IP?","acceptedAnswerId":1056,"type":"question","body":"Does anyone know of a simple way to retrieve the country for a given IP Address? Preferably in ISO_3166-1 format? "} {"user":"116","questionId":1033,"creationDate":"2008-08-04T05:21:59Z","answerId":1034,"type":"answer","body":"Here's a nice free service with a public API: http://www.hostip.info/use.html "} {"user":"231","tags":["c#","winforms","flash","adobe","macromedia"],"questionId":1037,"creationDate":"2008-08-04T05:35:52Z","title":"Displaying Flash content in a C# WinForms application","acceptedAnswerId":1039,"type":"question","body":"What is the best way to display Flash content in a C# WinForms application? I would like to create a user control (similar to the current PictureBox) that will be able to display images and flash content. It would be great to be able to load the flash content from a stream of sorts rather than a file on disk. "} {"user":"46","questionId":1037,"creationDate":"2008-08-04T05:44:45Z","answerId":1039,"type":"answer","body":"While I haven't used a flash object inside a windows form application myself, I do know that it's possible. In Visual studio on your toolbox, choose to add a new component. Then in the new window that appears choose the \"COM Components\" tab to get a list in which you can find the \"Shockwave Flash Object\" Once added to the toolbox, simply use the control as you would use any other \"standard\" control from visual studio. three simple commands are available to interact with the control: AxShockwaveFlash1.Stop() AxShockwaveFlash1.Movie = FilePath & \"\\FileName.swf\" AxShockwaveFlash1.Play() which, I think, are all self explanatory. It would be great to be able to load the flash content from a stream of sorts rather than a file on disk. I just saw you are also looking for a means to load the content from a stream, and because I'm not really sure that is possible with the shockwave flash object I will give you another option (two actually). the first is the one I would advise you to use only when necessary, as it uses the full blown \"webbrowser component\" (also available as an extra toolbox item), which is like trying to shoot a fly with a bazooka. of course it will work, as the control will act as a real browser window (actually the internet explorer browser), but its not really meant to be used in the way you need it. the second option is to use something I just discovered while looking for more information about playing flash content inside a windows form. F-IN-BOX is a commercial solution that will also play content from a given website URL. (The link provided will direct you to the .NET code you have to use). "} {"user":"254","tags":["c#","file-locking"],"questionId":1040,"creationDate":"2008-08-04T05:45:22Z","title":"How do I delete a file which is locked by another process in C#?","acceptedAnswerId":1044,"type":"question","body":"I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using File.Delete(). "} {"user":"user2189331","tags":["c++","regex"],"questionId":1041,"creationDate":"2008-08-04T05:50:00Z","title":"Easy-to-Use Regular Expression Support in C++?","acceptedAnswerId":17198991,"type":"question","body":"I'm looking for a robust, easy-to-use, regular expression evaluator for native C++, either platform-independent or Windows-specific. Requirements: Can't use Boost or ACE regex libraries (unfortunately) Can't use .NET Regex (or any managed code) The main requirement is that it should be standalone and open. "} {"user":"2","tags":["sql","sql-server","sql-server-2005","indexing","full-text-search"],"questionId":1042,"creationDate":"2008-08-04T05:51:56Z","title":"Why doesn't SQL Full Text Indexing return results for words containing #?","acceptedAnswerId":1061,"type":"question","body":"For instance, my query is like the following using SQL Server 2005: SELECT * FROM Table WHERE FREETEXT(SearchField, 'c#') I have a full text index defined to use the column SearchField which returns results when using: SELECT * FROM Table WHERE SearchField LIKE '%c#%' I believe # is a special letter, so how do I allow FREETEXT to work correctly for the query above? "} {"user":"55","questionId":1040,"creationDate":"2008-08-04T05:59:53Z","answerId":1043,"type":"answer","body":"You can use this program, Handle, to find which process has the lock on your file. It's a command-line tool, so I guess you use the output from that... I'm not sure about finding it programmatically. If deleting the file can wait, you could specify it for deletion when your computer next starts up: Start REGEDT32 (W2K) or REGEDIT (WXP) and navigate to: HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager W2K and WXP W2K:EditAdd Value...Data Type: REG_MULTI_SZValue Name: PendingFileRenameOperationsOK WXP:EditNewMulti-String Valueenter PendingFileRenameOperations In the Data area, enter \"\\??\\\" + filename to be deleted. LFNs may be entered without being embedded in quotes. To delete C:\\Long Directory Name\\Long File Name.exe, enter the following data: \\??\\C:\\Long Directory Name\\Long File Name.exe Then press OK. The \"destination file name\" is a null (zero) string. It is entered as follows: W2K:EditBinaryselect Data Format: Hexclick at the end of the hex stringenter 0000 (four zeros)OK WXP:Right-click the valuechoose \"Modify Binary Data\"click at the end of the hex stringenter 0000 (four zeros)OK Close REGEDT32/REGEDIT and reboot to delete the file. (Shamelessly stolen from some random forum, for posterity's sake.) "} {"user":"227","questionId":1040,"creationDate":"2008-08-04T06:01:52Z","answerId":1044,"type":"answer","body":"Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the MoveFileEx API function to mark the file for deletion upon next reboot. If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions. "} {"user":"227","questionId":1042,"creationDate":"2008-08-04T06:10:16Z","answerId":1047,"type":"answer","body":"Quoting a much-replicated help page about Indexing Service query language: To use specially treated characters such as &, |, ^, #, @, $, (, ), in a query, enclose your query in quotation marks (“). As far as I know, full text search in MSSQL is also done by the Indexing Service, so this might help. "} {"user":"234","questionId":1040,"creationDate":"2008-08-04T06:12:11Z","answerId":1049,"type":"answer","body":"If you want to do it programatically. I'm not sure... and I'd really recommend against it. If you're just troubleshooting stuff on your own machine, SysInternals Process Explorer can help you Run it, use the Find Handle command (I think it's either in the find or handle menu), and search for the name of your file. Once the handle(s) is found, you can forcibly close them. You can then delete the file and so on. Beware, doing this may cause the program which owns the handles to behave strangely, as you've just pulled the proverbial rug out from under it, but it works well when you are debugging your own errant code, or when visual studio / windows explorer is being crap and not releasing file handles even though you told them to close the file ages ago... sigh :-) "} {"user":"234","questionId":1040,"creationDate":"2008-08-04T06:14:42Z","answerId":1050,"type":"answer","body":"Oh, one big hack I employed years ago, is that Windows won't let you delete files, but it does let you move them. Pseudo-sort-of-code: mv %WINDIR%\\System32\\mfc42.dll %WINDIR\\System32\\mfc42.dll.old Install new mfc42.dll Tell user to save work and restart applications When the applications restarted (note we didn't need to reboot the machine), they loaded the new mfc42.dll, and all was well. That, coupled with PendingFileOperations to delete the old one the next time the whole system restarted, worked pretty well. "} {"user":"user2189331","questionId":1040,"creationDate":"2008-08-04T06:15:30Z","answerId":1051,"type":"answer","body":"The typical method is as follows. You've said you want to do this in C# so here goes... If you don't know which process has the file locked, you'll need to examine each process's handle list, and query each handle to determine if it identifies the locked file. Doing this in C# will likely require P/Invoke or an intermediary C++/CLI to call the native APIs you'll need. Once you've figured out which process(es) have the file locked, you'll need to safely inject a small native DLL into the process (you can also inject a managed DLL, but this is messier, as you then have to start or attach to the .NET runtime). That bootstrap DLL then closes the handle using CloseHandle etc. Essentially: the way to unlock a \"locked\" file is to inject a DLL into the offending process's address space and close it yourself. You can do this using native or managed code. No matter what, you're going to need a small amount of native code or at least P/Invoke into the same. Helpful links: http://www.codeproject.com/KB/threads/winspy.aspx http://damianblog.com/2008/07/02/net-code-injection/ Good luck! "} {"user":"13","tags":["math","language-agnostic","floating-point"],"questionId":1053,"creationDate":"2008-08-04T06:21:38Z","title":"A little diversion into floating point (im)precision, part 1","acceptedAnswerId":394225,"type":"question","body":"Most mathematicians agree that: eπi + 1 = 0 However, most floating point implementations disagree. How well can we settle this dispute? I'm keen to hear about different languages and implementations, and various methods to make the result as close to zero as possible. Be creative! "} {"user":"13","questionId":1053,"creationDate":"2008-08-04T06:22:18Z","answerId":1054,"type":"answer","body":"Here's a short list of implementations and languages I've tried. It's sorted by closeness to zero: Scheme: (+ 1 (make-polar 1 (atan 0 -1))) ⇒ 0.0+1.2246063538223773e-16i (Chez Scheme, MIT Scheme) ⇒ 0.0+1.22460635382238e-16i (Guile) ⇒ 0.0+1.22464679914735e-16i (Chicken with numbers egg) ⇒ 0.0+1.2246467991473532e-16i (MzScheme, SISC, Gauche, Gambit) ⇒ 0.0+1.2246467991473533e-16i (SCM) Common Lisp: (1+ (exp (complex 0 pi))) ⇒ #C(0.0L0 -5.0165576136843360246L-20) (CLISP) ⇒ #C(0.0d0 1.2246063538223773d-16) (CMUCL) ⇒ #C(0.0d0 1.2246467991473532d-16) (SBCL) Perl: use Math::Complex; Math::Complex->emake(1, pi) + 1 ⇒ 1.22464679914735e-16i Python: from cmath import exp, pi; exp(complex(0, pi)) + 1 ⇒ 1.2246467991473532e-16j (CPython) Ruby: require 'complex'; Complex::polar(1, Math::PI) + 1 ⇒ Complex(0.0, 1.22464679914735e-16) (MRI) ⇒ Complex(0.0, 1.2246467991473532e-16) (JRuby) R: complex(argument = pi) + 1 ⇒ 0+1.224606353822377e-16i "} {"user":"234","questionId":1041,"creationDate":"2008-08-04T06:23:51Z","answerId":1055,"type":"answer","body":"try libpcre If you're stuck on windows they have a windows port which should work. I know e-texteditor uses it, so at least that's proof it works :-) "} {"user":"234","questionId":1033,"creationDate":"2008-08-04T06:26:22Z","answerId":1056,"type":"answer","body":"A lot of people (including my company) seem to use MaxMind GeoIP. They have a free version GeoLite which is not as accurate as the paid version, but if you're just after something simple, it may be good enough. "} {"user":"55","questionId":1053,"creationDate":"2008-08-04T06:29:03Z","answerId":1057,"type":"answer","body":"Is it possible to settle this dispute? My first thought is to look to a symbolic language, like Maple. I don't think that counts as floating point though. In fact, how does one represent i (or j for the engineers) in a conventional programming language? Perhaps a better example is sin(π) = 0? (Or have I missed the point again?) "} {"user":"3","questionId":1042,"creationDate":"2008-08-04T06:39:40Z","answerId":1061,"type":"answer","body":"The # char is indexed as punctuation and therefore ignored, so it looks like we'll remove the letter C from our word indexing ignore lists. Tested it locally after doing that and rebuilding the indexes and I get results! Looking at using a different word breaker language on the indexed column, so that those special characters aren't ignored. EDIT: I also found this information: c# is indexed as c (if c is not in your noise word list, see more on noise word lists later), but C# is indexed as C# (in SQL 2005 and SQL 2000 running on Win2003 regardless if C or c is in your noise word list). It is not only C# that is stored as C#, but any capital letter followed by #. Conversely, c++ ( and any other lower-cased letter followed by a ++) is indexed as c (regardless of whether c is in your noise word list). "} {"user":"116","questionId":1041,"creationDate":"2008-08-04T06:41:29Z","answerId":1062,"type":"answer","body":"The GNU C Library supports regular expressions. It's open, and the RE code seems to be easily extractable. "} {"user":"user2189331","tags":["language-agnostic","opengl","3d","directx"],"questionId":1064,"creationDate":"2008-08-04T06:51:20Z","title":"Displaying 100 Floating Cubes Using DirectX OR OpenGL","acceptedAnswerId":1096,"type":"question","body":"I'd like to display ~100 floating cubes using DirectX or OpenGL. I'm looking for either some sample source code, or a description of the technique. I know this kind of thing is easy for you accomplished '3D' gurus out there but I have enough trouble getting even one cube to display correctly. I've combed the net for a good series of tutorials and although they talk about how to do 3D primitives, what I can't find is information on how to do large numbers of 3D primitives - cubes, spheres, pyramids, and so forth. "} {"user":"116","questionId":1005,"creationDate":"2008-08-04T06:52:32Z","answerId":1065,"type":"answer","body":"In general, you can't change the effective user id of the vi process, but you can do this: :w !sudo tee myfile "} {"user":"231","questionId":1037,"creationDate":"2008-08-04T07:12:57Z","answerId":1066,"type":"answer","body":"Sven, you reached the same conclusion as I did: I found the Shockwave Flash Object, all be it from a slightly different route, but was stumped on how to load the files from somewhere other than file on disk/URL. The F-IN-BOX, although just a wrapper of the Shockwave Flash Object seems to provide much more functionality, which may just help me! Shooting flys with bazookas may be fun, but an embeded web brower is not the path that I am looking for. :) There was a link on Adobe's site that talked about \"Embedding and Communicating with the Macromedia Flash Player in C# Windows Applications\" but they seem to have removed it :( "} {"user":"257","tags":["c++","windows","multithreading","debugging","memory"],"questionId":1069,"creationDate":"2008-08-04T07:30:01Z","title":"Heap corruption under Win32; how to locate?","acceptedAnswerId":1073,"type":"question","body":"I'm working on a multithreaded C++ application that is corrupting the heap. The usual tools to locate this corruption seem to be inapplicable. Old builds (18 months old) of the source code exhibit the same behaviour as the most recent release, so this has been around for a long time and just wasn't noticed; on the downside, source deltas can't be used to identify when the bug was introduced - there are a lot of code changes in the repository. The prompt for crashing behaviuor is to generate throughput in this system - socket transfer of data which is munged into an internal representation. I have a set of test data that will periodically cause the app to exception (various places, various causes - including heap alloc failing, thus: heap corruption). The behaviour seems related to CPU power or memory bandwidth; the more of each the machine has, the easier it is to crash. Disabling a hyper-threading core or a dual-core core reduces the rate of (but does not eliminate) corruption. This suggests a timing related issue. Now here's the rub: When it's run under a lightweight debug environment (say Visual Studio 98 / AKA MSVC6) the heap corruption is reasonably easy to reproduce - ten or fifteen minutes pass before something fails horrendously and exceptions, like an alloc; when running under a sophisticated debug environment (Rational Purify, VS2008/MSVC9 or even Microsoft Application Verifier) the system becomes memory-speed bound and doesn't crash (Memory-bound: CPU is not getting above 50%, disk light is not on, the program's going as fast it can, box consuming 1.3G of 2G of RAM). So, I've got a choice between being able to reproduce the problem (but not identify the cause) or being able to idenify the cause or a problem I can't reproduce. My current best guesses as to where to next is: Get an insanely grunty box (to replace the current dev box: 2Gb RAM in an E6550 Core2 Duo); this will make it possible to repro the crash causing mis-behaviour when running under a powerful debug environment; or Rewrite operators new and delete to use VirtualAlloc and VirtualProtect to mark memory as read-only as soon as it's done with. Run under MSVC6 and have the OS catch the bad-guy who's writing to freed memory. Yes, this is a sign of desperation: who the hell rewrites new and delete?! I wonder if this is going to make it as slow as under Purify et al. And, no: Shipping with Purify instrumentation built in is not an option. A colleague just walked past and asked \"Stack Overflow? Are we getting stack overflows now?!?\" And now, the question: How do I locate the heap corruptor? Update: balancing new[] and delete[] seems to have gotten a long way towards solving the problem. Instead of 15mins, the app now goes about two hours before crashing. Not there yet. Any further suggestions? The heap corruption persists. Update: a release build under Visual Studio 2008 seems dramatically better; current suspicion rests on the STL implementation that ships with VS98. Reproduce the problem. Dr Watson will produce a dump that might be helpful in further analysis. I'll take a note of that, but I'm concerned that Dr Watson will only be tripped up after the fact, not when the heap is getting stomped on. Another try might be using WinDebug as a debugging tool which is quite powerful being at the same time also lightweight. Got that going at the moment, again: not much help until something goes wrong. I want to catch the vandal in the act. Maybe these tools will allow you at least to narrow the problem to certain component. I don't hold much hope, but desperate times call for... And are you sure that all the components of the project have correct runtime library settings (C/C++ tab, Code Generation category in VS 6.0 project settings)? No I'm not, and I'll spend a couple of hours tomorrow going through the workspace (58 projects in it) and checking they're all compiling and linking with the appropriate flags. Update: This took 30 seconds. Select all projects in the Settings dialog, unselect until you find the project(s) that don't have the right settings (they all had the right settings). "} {"user":"236","tags":["unix","size"],"questionId":1070,"creationDate":"2008-08-04T07:34:44Z","title":"Process size on UNIX","acceptedAnswerId":1773,"type":"question","body":"What is the correct way to get the process size on Solaris, HP-UX and AIX? Should we use top or ps -o vsz or something else? "} {"user":"257","questionId":264,"creationDate":"2008-08-04T07:45:38Z","answerId":1071,"type":"answer","body":"What I did when working against a database of unknown performance was to measure turnaround time on my queries. I kept upping the thread count until turn-around time dropped, and dropping the thread count until turn-around time improved (well, it was processes in my environment, but whatever). There were moving averages and all sorts of metrics involved, but the take-away lesson was: just adapt to how things are working at the moment. You never know when the DBAs will improve performance or hardware will be upgraded, or perhaps another process will come along to load down the system while you're running. So adapt. Oh, and another thing: avoid process switches if you can - batch things up. Oh, I should make this clear: this all happened at run time, not during development. "} {"user":"122","questionId":1069,"creationDate":"2008-08-04T07:48:51Z","answerId":1072,"type":"answer","body":"You tried old builds, but is there a reason you can't keep going further back in the repository history and seeing exactly when the bug was introduced? Otherwise, I would suggest adding simple logging of some kind to help track down the problem, though I am at a loss of what specifically you might want to log. If you can find out what exactly CAN cause this problem, via google and documentation of the exceptions you are getting, maybe that will give further insight on what to look for in the code. "} {"user":"user2189331","questionId":1069,"creationDate":"2008-08-04T07:51:02Z","answerId":1073,"type":"answer","body":"My first choice would be a dedicated heap tool such as pageheap.exe. Rewriting new and delete might be useful, but that doesn't catch the allocs committed by lower-level code. If this is what you want, better to Detour the low-level alloc APIs using Microsoft Detours. Also sanity checks such as: verify your run-time libraries match (release vs. debug, multi-threaded vs. single-threaded, dll vs. static lib), look for bad deletes (eg, delete where delete [] should have been used), make sure you're not mixing and matching your allocs. Also try selectively turning off threads and see when/if the problem goes away. What does the call stack etc look like at the time of the first exception? "} {"user":"1","questionId":1010,"creationDate":"2008-08-04T08:04:41Z","answerId":1074,"type":"answer","body":"Rex, I suspect a good place to start looking is solutions that compress the ViewState -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be. Scott Hanselman on ViewState Compression (2005) ViewState Compression with System.IO.Compression (2007) "} {"user":"214","questionId":761,"creationDate":"2008-08-04T08:14:56Z","answerId":1077,"type":"answer","body":"The trouble with international standards is that pretty much noone uses them. I try where I can, but I am forced to use dd/mm/yyyy almost everywhere in real life, which means I am so used to it it's always a conscious process to use ISO-8601. For the majority of people who don't even try to use ISO-8601 it's even worse. If you can internationalize where you can, I think it's a great advantage. "} {"user":"116","questionId":1070,"creationDate":"2008-08-04T08:21:07Z","answerId":1082,"type":"answer","body":"Yes, you are right to lock at the VSZ. ps u will give you the VSZ and RSS, which are the virtual memory size and resident set size. The RSS is how much physical memory has been allocated to the process, and the VSZ is the virtual memory size of the process. If you have several copies of a program running, a lot of the memory in the VSZ will be shared between those processes. "} {"user":"260","tags":["artificial-intelligence","email-spam","bayesian"],"questionId":1083,"creationDate":"2008-08-04T08:21:42Z","title":"Bayesian filtering for spam","acceptedAnswerId":42406,"type":"question","body":"I was wondering if there is any good and clean oo implementation of Bayesian filtering for spam and text classification? This is just for learning purposes. "} {"user":"2090742","questionId":1069,"creationDate":"2008-08-04T08:26:55Z","answerId":1086,"type":"answer","body":"My first action would be as follows: Build the binaries in \"Release\" version but creating debug info file (you will find this possibility in project settings). Use Dr Watson as a defualt debugger (DrWtsn32 -I) on a machine on which you want to reproduce the problem. Repdroduce the problem. Dr Watson will produce a dump that might be helpful in further analysis. Another try might be using WinDebug as a debugging tool which is quite powerful being at the same time also lightweight. Maybe these tools will allow you at least to narrow the problem to certain component. And are you sure that all the components of the project have correct runtime library settings (C/C++ tab, Code Generation category in VS 6.0 project settings)? "} {"user":"86","questionId":1083,"creationDate":"2008-08-04T08:54:16Z","answerId":1090,"type":"answer","body":"Maybe https://ci-bayes.dev.java.net/ or http://www.cs.cmu.edu/~javabayes/Home/node2.html? I never played with it either. "} {"user":"61","questionId":1064,"creationDate":"2008-08-04T09:04:01Z","answerId":1092,"type":"answer","body":"Just use glTranslatef (or the DirectX equivalent) to draw a cube using the same code, but moving the relative point where you draw it. Maybe there's a better way to do it though, I'm fairly new to OpenGL. Be sure to set your viewpoint so you can see them all. "} {"user":"51","questionId":1010,"creationDate":"2008-08-04T09:04:17Z","answerId":1093,"type":"answer","body":"See this blog post where the author describes a method for overriding the default behavior for generating the ViewState and instead shows how to save it on the server Session object. In ASP.NET 2.0, ViewState is saved by a descendant of PageStatePersister class. This class is an abstract class for saving and loading ViewsState and there are two implemented descendants of this class in .Net Framework, named HiddenFieldPageStatePersister and SessionPageStatePersister. By default HiddenFieldPageStatePersister is used to save/load ViewState information, but we can easily get the SessionPageStatePersister to work and save ViewState in Session object. Although I did not test his code, it seems to show exactly what you want: a way to gain access to ViewState code while still on the server, before postback. "} {"user":"51","questionId":1083,"creationDate":"2008-08-04T09:08:32Z","answerId":1095,"type":"answer","body":"Here is an implementation of Bayesian filtering in C#: A Naive Bayesian Spam Filter for C# (hosted on CodeProject). "} {"user":"41","questionId":1064,"creationDate":"2008-08-04T09:12:37Z","answerId":1096,"type":"answer","body":"You say you have enough trouble getting one cube to display... so I am not sure if you have got one to display or not. Basically... put your code for writing a cube in one function, then just call that function 100 times. void DrawCube() { //code to draw the cube } void DisplayCubes() { for(int i = 0; i < 10; ++i) { for(int j = 0; j < 10; ++j) { glPushMatrix(); //alter these values depending on the size of your cubes. //This call makes sure that your cubes aren't drawn overtop of each other glTranslatef(i*5.0, j*5.0, 0); DrawCube(); glPopMatrix(); } } } That is the basic outline for how you could go about doing this. If you want something more efficient take a look into Display Lists sometime once you have the basics figured out :) "} {"user":"236","tags":["c++","exception","try-catch"],"questionId":1104,"creationDate":"2008-08-04T10:01:37Z","title":"Ensuring that Exceptions are always сaught","acceptedAnswerId":1109,"type":"question","body":"Exceptions in C++ don't need to be caught (no compile time errors) by the calling function. So it's up to developer's judgment whether to catch еруь using try/catch (unlike in Java). Is there a way one can ensure that the exceptions thrown are always caught using try/catch by the calling function? "} {"user":"264","tags":["sql","database","performance","indexing","database-indexes"],"questionId":1108,"creationDate":"2008-08-04T10:07:12Z","title":"How does database indexing work?","acceptedAnswerId":1130,"type":"question","body":"Given that indexing is so important as your data set increases in size, can someone explain how does indexing works at a database agnostic level? For information on queries to index a field, check out How do I index a database column. "} {"user":"13","questionId":1104,"creationDate":"2008-08-04T10:10:15Z","answerId":1109,"type":"answer","body":"No. See A Pragmatic Look at Exception Specifications for reasons why not. The only way you can \"help\" this is to document the exceptions your function can throw, say as a comment in the header file declaring it. This is not enforced by the compiler or anything. Use code reviews for that purpose. "} {"user":"227","questionId":944,"creationDate":"2008-08-04T10:20:01Z","answerId":1114,"type":"answer","body":"AppDomain.UnhandledException is an event, not a global exception handler. This means, by the time it is raised, your application is already on its way down the drain, and there is nothing you can do about it, except for doing cleanup and error logging. What happened behind the scenes is this: The framework detected the exception, walked up the call stack to the very top, found no handlers that would recover from the error, so was unable to determine if it was safe to continue execution. So, it started the shutdown sequence, and fired up this event as a courtesy to you so you can pay your respects to your already-doomed process. This happens when an exception is left unhandled in the main thread. There is no single-point solution to this kind of error. You need to put a real exception handler (a catch block) upstream of all places where this error occurs and forward it to (for example) a global handler method/class that will determine if it is safe to simply report and continue, based on exception type and/or content. Edit: It is possible to disable (=hack) the error-reporting mechanism built into Windows so the mandatory \"crash and burn\" dialog does not get displayed when your app goes down. However, this becomes effective for all the applications in the system, not just your own. "} {"user":"91","questionId":855,"creationDate":"2008-08-04T10:27:05Z","answerId":1120,"type":"answer","body":"I've just set up Sandcastle again. Try installing it (the May 2008 release) and search for SandcastleGui.exe or something similar (it's in the examples folder or so). Click Add Assembly and add your Assembly or Assemblies, add any .xml Documentation files (the ones generated by the compiler if you enabled that option) and then Build. It will take some time, but the result will be worth the effort. It will actually look up stuff from MSDN, so your resulting documentation will also have the Class Inheritance all the way down to System.Object with links to MSDN and stuff. Sandcastle seems a bit complicated at first, especially when you want to use it in an automated build, but I am absolutely sure it will be worth the effort. Also have a look at Sandcastle Help File Builder, this is a somewhat more advanced GUI for it. "} {"user":"39","questionId":855,"creationDate":"2008-08-04T10:31:33Z","answerId":1123,"type":"answer","body":"Follow this simple 5 step article and you are pretty much done. As a bonus you can use H2Viewer to view Html Help 2.x files. "} {"user":"264","questionId":1108,"creationDate":"2008-08-04T10:41:04Z","answerId":1130,"type":"answer","body":"Why is it needed? When data is stored on disk based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously. Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires N/2 block accesses (on average), where N is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire table space must be searched at N block accesses. Whereas with a sorted field, a Binary Search may be used, this has log2 N block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial. What is indexing? Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it. The downside to indexing is that these indexes require additional space on the disk, since the indexes are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed. How does it work? Firstly, let’s outline a sample database table schema; Field name Data type Size on disk id (Primary key) Unsigned INT 4 bytes firstName Char(50) 50 bytes lastName Char(50) 50 bytes emailAddress Char(100) 100 bytes Note: char was used in place of varchar to allow for an accurate size on disk value. This sample database contains five million rows, and is unindexed. The performance of several queries will now be analyzed. These are a query using the id (a sorted key field) and one using the firstName (a non-key unsorted field). Example 1 - sorted vs unsorted fields Given our sample database of r = 5,000,000 records of a fixed size giving a record length of R = 204 bytes and they are stored in a table using the MyISAM engine which is using the default block size B = 1,024 bytes. The blocking factor of the table would be bfr = (B/R) = 1024/204 = 5 records per disk block. The total number of blocks required to hold the table is N = (r/bfr) = 5000000/5 = 1,000,000 blocks. A linear search on the id field would require an average of N/2 = 500,000 block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of log2 1000000 = 19.93 = 20 block accesses. Instantly we can see this is a drastic improvement. Now the firstName field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact N = 1,000,000 block accesses. It is this situation that indexing aims to correct. Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the firstName field is outlined below; Field name Data type Size on disk firstName Char(50) 50 bytes (record pointer) Special 4 bytes Note: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table. Example 2 - indexing Given our sample database of r = 5,000,000 records with an index record length of R = 54 bytes and using the default block size B = 1,024 bytes. The blocking factor of the index would be bfr = (B/R) = 1024/54 = 18 records per disk block. The total number of blocks required to hold the index is N = (r/bfr) = 5000000/18 = 277,778 blocks. Now a search using the firstName field can utilise the index to increase performance. This allows for a binary search of the index with an average of log2 277778 = 18.08 = 19 block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to 19 + 1 = 20 block accesses, a far cry from the 1,000,000 block accesses required to find a firstName match in the non-indexed table. When should it be used? Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indexes can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index. Since indexes are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space. "} {"user":"91","tags":["windows","language-agnostic","chm","winhelp"],"questionId":1131,"creationDate":"2008-08-04T10:43:05Z","title":"Windows Help files - what are the options?","acceptedAnswerId":1135,"type":"question","body":"Back in the old days, Help was not trivial but possible: generate some funky .rtf file with special tags, run it through a compiler, and you got a WinHelp file (.hlp) that actually works really well. Then, Microsoft decided that WinHelp was not hip and cool anymore and switched to CHM, up to the point they actually axed WinHelp from Vista. Now, CHM maybe nice, but everyone that tried to open a .chm file on the Network will know the nice \"Navigation to the webpage was canceled\" screen that is caused by security restrictions. While there are ways to make CHM work off the network, this is hardly a good choice, because when a user presses the Help Button he wants help and not have to make some funky settings. Bottom Line: I find CHM absolutely unusable. But with WinHelp not being an option anymore either, I wonder what the alternatives are, especially when it comes to integrate with my Application (i.e. for WinHelp and CHM there are functions that allow you to directly jump to a topic)? PDF has the disadvantage of requiring the Adobe Reader (or one of the more lightweight ones that not many people use). I could live with that seeing as this is kind of standard nowadays, but can you tell it reliably to jump to a given page/anchor? HTML files seem to be the best choice, you then just have to deal with different browsers (CSS and stuff). Edit: I am looking to create my own Help Files. As I am a fan of the \"No Setup, Just Extract and Run\" Philosophy, i had that problem many times in the past because many of my users will run it off the network, which causes exactly this problem. So i am looking for a more robust and future-proof way to provide help to my users without having to code a different help system for each application i make. CHM is a really nice format, but that Security Stuff makes it unusable, as a Help system is supposed to provide help to the user, not to generate even more problems. "} {"user":"227","questionId":1131,"creationDate":"2008-08-04T10:51:39Z","answerId":1135,"type":"answer","body":"HTML would be the next best choice, ONLY IF you would serve them from a public web server. If you tried to bundle it with your app, all the files (and images (and stylesheets (and ...) ) ) would make CHM look like a gift from gods. That said, when actually bundled in the installation package, (instead of being served over the network), I found the CHM files to work nicely. OTOH, another pitfall about CHM files: Even if you try to open a CHM file on a local disk, you may bump into the security block if you initially downloaded it from somewhere, because the file could be marked as \"came from external source\" when it was obtained. "} {"user":"40","questionId":1131,"creationDate":"2008-08-04T10:52:26Z","answerId":1136,"type":"answer","body":"Is the question how to generate your own help files, or what is the best help file format? Personally, I find CHM to be excellent. One of the first things I do when setting up a machine is to download the PHP Manual in CHM format (http://www.php.net/download-docs.php) and add a hotkey to it in Crimson Editor. So when I press F1 it loads the CHM and performs a search for the word my cursor is on (great for quick function reference). "} {"user":"267","questionId":1131,"creationDate":"2008-08-04T11:02:12Z","answerId":1141,"type":"answer","body":"Our software is both distributed locally to the clients and served from a network share. We opted for generating both a CHM file and a set of HTML files for serving from the network. Users starting the program locally use the CHM file, and users getting their program served from a network share has to use the HTML files. We use Help and Manual and can thus easily produce both types of output from the same source project. The HTML files also contain searching capabilities and doesn't require a web server, so though it isn't an optimal solution, works fine. So far all the single-file types for Windows seems broken in one way or another: WinHelp - obsoleted HtmlHelp (CHM) - obsoleted on Vista, doesn't work from network share, other than that works really nice Microsoft Help 2 (HXS) - this seems to work right up until the point when it doesn't, corrupted indexes or similar, this is used by Visual Studio 2005 and above, as an example "} {"user":"268","questionId":1083,"creationDate":"2008-08-04T11:03:51Z","answerId":1142,"type":"answer","body":"In French, but you should be able to find the download link :) PHP Naive Bayesian Filter "} {"user":"188","tags":["c","malloc"],"questionId":1145,"creationDate":"2008-08-04T11:06:00Z","title":"Why am I getting a double free error with realloc()?","acceptedAnswerId":1154,"type":"question","body":"I've tried to write a string replace function in C, which works on a char *, which has been allocated using malloc(). It's a little different in that it will find and replace strings, rather than characters in the starting string. It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated. If I try to use realloc(), I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using realloc(). Perhaps a little code will help: void strrep(char *input, char *search, char *replace) { int searchLen = strlen(search); int replaceLen = strlen(replace); int delta = replaceLen - searchLen; char *find = input; while (find = strstr(find, search)) { if (delta > 0) { realloc(input, strlen(input) + delta); find = strstr(input, search); } memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input)); memmove(find, replace, replaceLen); } } The program works, until I try to realloc() in an instance where the replaced string will be longer than the initial string. (It still kind of works, it just spits out errors as well as the result). If it helps, the calling code looks like: #include #include #include void strrep(char *input, char *search, char *replace); int main(void) { char *input = malloc(81); while ((fgets(input, 81, stdin)) != NULL) { strrep(input, \"Noel\", \"Christmas\"); } } "} {"user":"46","questionId":13,"creationDate":"2008-08-04T11:11:14Z","answerId":1148,"type":"answer","body":" Anyone know of any services that will match IP to geographic location Well, lucky for you that answer can be found on our very own stackoverflow website: How to get the Country according to a certain IP? spoiler: http://www.hostip.info/use.html "} {"user":"200","questionId":1145,"creationDate":"2008-08-04T11:14:48Z","answerId":1149,"type":"answer","body":"Just a shot in the dark because I haven't tried it yet but when you realloc it returns the pointer much like malloc. Because realloc can move the pointer if needed you are most likely operating on an invalid pointer if you don't do the following: input = realloc(input, strlen(input) + delta); "} {"user":"267","questionId":1145,"creationDate":"2008-08-04T11:17:32Z","answerId":1153,"type":"answer","body":"Note, try to edit your code to get rid of the html escape codes. Well, though it has been a while since I used C/C++, realloc that grows only reuses the memory pointer value if there is room in memory after your original block. For instance, consider this: (xxxxxxxxxx..........) If your pointer points to the first x, and . means free memory location, and you grow the memory size pointed to by your variable by 5 bytes, it'll succeed. This is of course a simplified example as blocks are rounded up to a certain size for alignment, but anyway. However, if you subsequently try to grow it by another 10 bytes, and there is only 5 available, it will need to move the block in memory and update your pointer. However, in your example you are passing the function a pointer to the character, not a pointer to your variable, and thus while the strrep function internally might be able to adjust the variable in use, it is a local variable to the strrep function and your calling code will be left with the original pointer variable value. This pointer value, however, has been freed. In your case, input is the culprit. However, I would make another suggestion. In your case it looks like the input variable is indeed input, and if it is, it shouldn't be modified, at all. I would thus try to find another way to do what you want to do, without changing input, as side-effects like this can be hard to track down. "} {"user":"268","questionId":1145,"creationDate":"2008-08-04T11:19:54Z","answerId":1154,"type":"answer","body":"As a general rule, you should never do a free or realloc on a user provided buffer. You don't know where the user allocated the space (in your module, in another DLL) so you cannot use any of the allocation functions on a user buffer. Provided that you now cannot do any reallocation within your function, you should change its behavior a little, like doing only one replacement, so the user will be able to compute the resulting string max length and provide you with a buffer long enough for this one replacement to occur. Then you could create another function to do the multiple replacements, but you will have to allocate the whole space for the resulting string and copy the user input string. Then you must provide a way to delete the string you allocated. Resulting in: void strrep(char *input, char *search, char *replace); char* strrepm(char *input, char *search, char *replace); void strrepmfree(char *input); "} {"user":"2090742","questionId":1145,"creationDate":"2008-08-04T11:20:58Z","answerId":1155,"type":"answer","body":"My quick hints. Instead of: void strrep(char *input, char *search, char *replace) try: void strrep(char *&input, char *search, char *replace) and than in the body: input = realloc(input, strlen(input) + delta); Generally read about passing function arguments as values/reference and realloc() description :). "} {"user":"264","tags":["sql","database","indexing"],"questionId":1156,"creationDate":"2008-08-04T11:21:26Z","title":"How do I index a database column","acceptedAnswerId":1157,"type":"question","body":"Hopefully, I can get answers for each database server. For an outline of how indexing works check out: How does database indexing work? "} {"user":"200","questionId":1156,"creationDate":"2008-08-04T11:25:14Z","answerId":1157,"type":"answer","body":"The following is SQL92 standard so should be supported by the majority of RDMBS that use SQL: CREATE INDEX [index name] ON [table name] ( [column name] ) "} {"user":"120","tags":["svn","msbuild","cruisecontrol.net"],"questionId":1160,"creationDate":"2008-08-04T11:37:24Z","title":"Use SVN Revision to label build in CCNET","acceptedAnswerId":975299,"type":"question","body":"I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code. I would like to use the latest revision number to generate AssemblyInfo.cs while compiling. How can I retrieve the latest revision from subversion and use the value in CCNET? Edit: I'm not using NAnt - only MSBuild. "} {"user":"263","questionId":1145,"creationDate":"2008-08-04T11:39:47Z","answerId":1163,"type":"answer","body":"This seems to work; char *strrep(char *string, const char *search, const char *replace) { char *p = strstr(string, search); if (p) { int occurrence = p - string; int stringlength = strlen(string); int searchlength = strlen(search); int replacelength = strlen(replace); if (replacelength > searchlength) { string = (char *) realloc(string, strlen(string) + replacelength - searchlength + 1); } if (replacelength != searchlength) { memmove(string + occurrence + replacelength, string + occurrence + searchlength, stringlength - occurrence - searchlength + 1); } strncpy(string + occurrence, replace, replacelength); } return string; } Sigh, is there anyway to post code without it sucking? "} {"user":"91","questionId":1160,"creationDate":"2008-08-04T11:41:37Z","answerId":1164,"type":"answer","body":"I am currently \"manually\" doing it through a prebuild-exec Task, using my cmdnetsvnrev tool, but if someone knows a better ccnet-integrated way of doing it, i'd be happy to hear :-) "} {"user":"120","questionId":1160,"creationDate":"2008-08-04T11:51:59Z","answerId":1168,"type":"answer","body":"I found this project on google code. This is CCNET plugin to generate the label in CCNET. The DLL is tested with CCNET 1.3 but it works with CCNET 1.4 for me. I'm successfully using this plugin to label my build. Now onto passing it to MSBuild... "} {"user":"275","questionId":1160,"creationDate":"2008-08-04T11:56:42Z","answerId":1169,"type":"answer","body":"You have basically two options. Either you write a simple script that will start and parse output from svn.exe info --revision HEAD to obtain revision number (then generating AssemblyInfo.cs is pretty much straight forward) or just use plugin for CCNET. Here it is: SVN Revision Labeller is a plugin for CruiseControl.NET that allows you to generate CruiseControl labels for your builds, based upon the revision number of your Subversion working copy. This can be customised with a prefix and/or major/minor version numbers. http://code.google.com/p/svnrevisionlabeller/ I prefer the first option because it's only roughly 20 lines of code: using System; using System.Diagnostics; namespace SvnRevisionNumberParserSample { class Program { static void Main() { Process p = Process.Start(new ProcessStartInfo() { FileName = @\"C:\\Program Files\\SlikSvn\\bin\\svn.exe\", // path to your svn.exe UseShellExecute = false, RedirectStandardOutput = true, Arguments = \"info --revision HEAD\", WorkingDirectory = @\"C:\\MyProject\" // path to your svn working copy }); // command \"svn.exe info --revision HEAD\" will produce a few lines of output p.WaitForExit(); // our line starts with \"Revision: \" while (!p.StandardOutput.EndOfStream) { string line = p.StandardOutput.ReadLine(); if (line.StartsWith(\"Revision: \")) { string revision = line.Substring(\"Revision: \".Length); Console.WriteLine(revision); // show revision number on screen break; } } Console.Read(); } } } "} {"user":"280","tags":["python","performance","data-structures","graph-theory"],"questionId":1171,"creationDate":"2008-08-04T12:00:57Z","title":"What is the most efficient graph data structure in Python?","acceptedAnswerId":28705,"type":"question","body":"I need to be able to manipulate a large (10^7 nodes) graph in python. The data corresponding to each node/edge is minimal, say, a small number of strings. What is the most efficient, in terms of memory and speed, way of doing this? A dict of dicts is more flexible and simpler to implement, but I intuitively expect a list of lists to be faster. The list option would also require that I keep the data separate from the structure, while dicts would allow for something of the sort: graph[I][J][\"Property\"]=\"value\" What would you suggest? Yes, I should have been a bit clearer on what I mean by efficiency. In this particular case I mean it in terms of random access retrieval. Loading the data in to memory isn't a huge problem. That's done once and for all. The time consuming part is visiting the nodes so I can extract the information and measure the metrics I'm interested in. I hadn't considered making each node a class (properties are the same for all nodes) but it seems like that would add an extra layer of overhead? I was hoping someone would have some direct experience with a similar case that they could share. After all, graphs are one of the most common abstractions in CS. "} {"user":"266","questionId":1160,"creationDate":"2008-08-04T12:03:03Z","answerId":1172,"type":"answer","body":"If you prefer doing it on the MSBuild side over the CCNet config, looks like the MSBuild Community Tasks extension's SvnVersion task might do the trick. "} {"user":"267","questionId":1171,"creationDate":"2008-08-04T12:09:55Z","answerId":1174,"type":"answer","body":"A dictionary may also contain overhead, depending on the actual implementation. A hashtable usually contain some prime number of available nodes to begin with, even though you might only use a couple of the nodes. Judging by your example, \"Property\", would you be better of with a class approach for the final level and real properties? Or is the names of the properties changing a lot from node to node? I'd say that what \"efficient\" means depends on a lot of things, like: speed of updates (insert, update, delete) speed of random access retrieval speed of sequential retrieval memory used I think that you'll find that a data structure that is speedy will generally consume more memory than one that is slow. This isn't always the case, but most data structures seems to follow this. A dictionary might be easy to use, and give you relatively uniformly fast access, it will most likely use more memory than, as you suggest, lists. Lists, however, generally tend to contain more overhead when you insert data into it, unless they preallocate X nodes, in which they will again use more memory. My suggestion, in general, would be to just use the method that seems the most natural to you, and then do a \"stress test\" of the system, adding a substantial amount of data to it and see if it becomes a problem. You might also consider adding a layer of abstraction to your system, so that you don't have to change the programming interface if you later on need to change the internal data structure. "} {"user":"206","questionId":1131,"creationDate":"2008-08-04T12:11:47Z","answerId":1175,"type":"answer","body":"If you are doing \"just extract and run\", you are going to run in security issues. This is especially true if you are users are running Vista (or later). is there a reason why you wanted to avoid packaging your applications inside an installer? Using an installer would alleviate the \"external source\" problem. You would be able to use .chm files without any problems. We use InstallAware to create our install packages. It's not cheap, but is very good. If cost is your concern, WIX is open source and pretty robust. WIX does have a learning curve, but it's easy to work with. "} {"user":"25","tags":["ruby","open-source"],"questionId":1176,"creationDate":"2008-08-04T12:11:55Z","title":"Open Source Ruby Projects","acceptedAnswerId":1186,"type":"question","body":"I have just recently started to study Ruby, and in lieu of Jeff's advice over the weekend... Stop theorizing. Write lots of software. Learn from your mistakes. ...I was interested in honing my skills while helping out the Open Source Community the process so I thought I'd ask if anyone have any suggestions for cool/interesting Open Source Projects written in Ruby that you know of or are involved in. "} {"user":"281","tags":["web-applications","dns","subdomain","account"],"questionId":1180,"creationDate":"2008-08-04T12:22:07Z","title":"How to make subdomain user accounts in a webapp","acceptedAnswerId":1232,"type":"question","body":"I am looking to allow users to control of subdomain of an app I am toying with, much like Basecamp where it is customusername.seework.com. What is required on the DNS end to allow these to be created dynamically and be available instantly. And how do you recommend dealing with this in the logic of the site? Htaccess rule to lookup the subdomain in the DB? "} {"user":"Mark Papadakis","questionId":1041,"creationDate":"2008-08-04T12:23:35Z","answerId":1183,"type":"answer","body":"The GNU C library regular expressions facility (regcomp(), regexec() and friends) is broken. Use libetre instead; the function signatures match the ones provided by glibc. http://laurikari.net/tre/ "} {"user":"60","questionId":1180,"creationDate":"2008-08-04T12:28:03Z","answerId":1185,"type":"answer","body":"The trick to that is to use URL rewriting so that name.domain.com transparently maps to something like domain.com/users/name on your server. Once you start down that path, it's fairly trivial to implement. "} {"user":"34","questionId":1176,"creationDate":"2008-08-04T12:28:24Z","answerId":1186,"type":"answer","body":"Well, you didn't specify Rails, so I'm going to throw Shoes out there. First, building shoes apps is probably the best way to learn Ruby (Rails is great, but I find mastering Ruby far more fun/useful). Secondly, while I certainly don't think building crossplatform UI components is trivial, shoes is relatively new, and relatively small. There are no doubt countless additions that could be made. "} {"user":"275","questionId":1180,"creationDate":"2008-08-04T12:32:24Z","answerId":1187,"type":"answer","body":"Don't worry about DNS and URL rewriting Your DNS record will be static, something like: *.YOURDOMAIN.COM A Ask your DNS provider to do it for you (if it's not done already) or do it by yourself if you have control over your DNS records. This will automatically point all your subdomains (current and future ones) into the same HTTP server. Once it's done, you will only need to parse HOST header on every single http request to detect what hostname was used to access your server-side scripts on your http server. Assuming you're using ASP.NET, this is kind of silly example I came up with but works and demonstrates simplicity of this approach: <%@ Language=\"C#\" %> <% string subDomain = Request.Url.Host.Split('.')[0].ToUpper(); if (subDomain == \"CLIENTXXX\") Response.Write(\"Hello CLIENTXXX, your secret number is 33\"); else if (subDomain == \"CLIENTYYY\") Response.Write(\"Hello CLIENTYYY, your secret number is 44\"); else Response.Write(subDomain+\" doesn't exist\"); %> "} {"user":"258","tags":["c#",".net","safari","viewstate"],"questionId":1189,"creationDate":"2008-08-04T12:38:21Z","title":"ViewState invalid only in Safari","acceptedAnswerId":1190,"type":"question","body":"One of the sites I maintain relies heavily on use of ViewState (it isn't my code). However, on certain pages where the ViewState is extra-bloated, Safari throws a \"Validation of viewstate MAC failed\" error. This appears to only happen in Safari. Firefox, IE and Opera all load successfully in the same scenario. "} {"user":"258","questionId":1189,"creationDate":"2008-08-04T12:40:49Z","answerId":1190,"type":"answer","body":"I've been doing a little research into this and whilst I'm not entirely sure its the cause I believe it is because Safari is not returning the full result set (hence cropping it). I have been in dicussion with another developer and found the following post on Channel 9 as well which recommends making use of the SQL State service to store the viewstate avoiding the postback issue and also page size. http://channel9.msdn.com/forums/TechOff/250549-ASPNET-ViewState-flawed-architecture/?CommentID=270477#263702 Does this seem like the best solution? "} {"user":"188","questionId":1171,"creationDate":"2008-08-04T12:41:15Z","answerId":1191,"type":"answer","body":"Making a class-based structure would probably have more overhead than the dict-based structure, since in python classes actually use dicts when they are implemented. "} {"user":"192","questionId":1189,"creationDate":"2008-08-04T13:00:32Z","answerId":1202,"type":"answer","body":"My first port of call would be to go through the elements on the page and see which controls: Will still work when I switch ViewState off Can be moved out of the page and into an AJAX call to be loaded when required Failing that, and here's the disclaimer - I've never used this solution on a web-facing site - but in the past where I've wanted to eliminate massive ViewStates in limited-audience applications I have stored the ViewState in the Session. It has worked for me because the hit to memory isn't significant for the number of users, but if you're running a fairly popular site I wouldn't recommend this approach. However, if the Session solution works for Safari you could always detect the user agent and fudge appropriately. "} {"user":"120","questionId":1160,"creationDate":"2008-08-04T13:22:31Z","answerId":1216,"type":"answer","body":" Customizing csproj files to autogenerate AssemblyInfo.cs http://www.codeproject.com/KB/dotnet/Customizing_csproj_files.aspx Every time we create a new C# project, Visual Studio puts there the AssemblyInfo.cs file for us. The file defines the assembly meta-data like its version, configuration, or producer. Found the above technique to auto-gen AssemblyInfo.cs using MSBuild. Will post sample shortly. "} {"user":"257","questionId":336,"creationDate":"2008-08-04T13:35:41Z","answerId":1226,"type":"answer","body":"C and C++ compilers will generate a warning when you compare signed and unsigned types; in your example code, you couldn't make your loop variable unsigned and have the compiler generate code without warnings (assuming said warnings were turned on). Naturally, you're compiling with warnings turned all the way up, right? And, have you considered compiling with \"treat warnings as errors\" to take it that one step further? The downside with using signed numbers is that there's a temptation to overload them so that, for example, the values 0->n are the menu selection, and -1 means nothing's selected - rather than creating a class that has two variables, one to indicate if something is selected and another to store what that selection is. Before you know it, you're testing for negative one all over the place and the compiler is complaining about how you're wanting to compare the menu selection against the number of menu selections you have - but that's dangerous because they're different types. So don't do that. "} {"user":"Jin","tags":["hyperlink","powerpoint"],"questionId":1229,"creationDate":"2008-08-04T13:38:18Z","title":"How do I hyperlink to a specific slide of a .ppt file?","type":"question","body":"I want to link to a specific slide in an online PowerPoint file, (e.g. http://www.example.com/hello.ppt) but what I want is that when people click on my link, it goes straight to the nth slide. Is this possible? "} {"user":"48","questionId":1180,"creationDate":"2008-08-04T13:39:39Z","answerId":1232,"type":"answer","body":"The way we do this is to have a 'catch all' for our domain name registered in DNS so that anything.ourdomain.com will point to our server. With Apache you can set up a similar catch-all for your vhosts. The ServerName must be a single static name but the ServerAlias directive can contain a pattern. Servername www.ourdomain.com ServerAlias *.ourdomain.com Now all of the domains will trigger the vhost for our project. The final part is to decode the domain name actually used so that you can work out the username in your code, something like (PHP): list( $username ) = explode( \".\", $_SERVER[ \"HTTP_HOST\" ] ); or a RewriteRule as already suggested that silently maps user.ourdomain.com/foo/bar to www.ourdomain.com/foo/bar?user=user or whatever you prefer. "} {"user":"173","questionId":1160,"creationDate":"2008-08-04T13:43:54Z","answerId":1235,"type":"answer","body":"I have written a NAnt build file that handles parsing SVN information and creating properties. I then use those property values for a variety of build tasks, including setting the label on the build. I use this target combined with the SVN Revision Labeller mentioned by lubos hasko with great results. "} {"user":"149","questionId":1189,"creationDate":"2008-08-04T13:44:49Z","answerId":1236,"type":"answer","body":"While I second the Channel 9 solution, also be aware that in some hosted environments Safari is not considered an up-level browser. You may need to add it to your application's browscap in order to make use of some ASP.Net features. That was the root cause of some headaches we had for a client's site that used the ASP Menu control. "} {"user":"230","tags":["regex","parsing"],"questionId":1237,"creationDate":"2008-08-04T13:47:10Z","title":"Regex: To pull out a sub-string between two tags in a string","acceptedAnswerId":1243,"type":"question","body":"I have a file in the following format: Data Data Data [Start] Data i want [End] Data I'd like to grab the Data i want from between the [Start] and [End] tags using a RegEx. Can anyone show me how this might be done? "} {"user":"206","questionId":1131,"creationDate":"2008-08-04T13:48:02Z","answerId":1238,"type":"answer","body":"If you don't want to use an installer and you don't want the user to perform any extra steps to allow CHM files over the network, why not fall back to WinHelp? Vista does not include WinHlp32.exe out of the box, but it is freely available as a download for both Vista and Server 2008. "} {"user":"34","questionId":1237,"creationDate":"2008-08-04T13:52:06Z","answerId":1240,"type":"answer","body":"[start](.*?)[end] which'll put the text in the middle within a capture "} {"user":"194","tags":["c#","c++","sockets"],"questionId":1241,"creationDate":"2008-08-04T13:52:25Z","title":"Asynchronous multi-direction server-client communication over the same open socket?","acceptedAnswerId":1275,"type":"question","body":"I have a client-server app where the client is on a Windows Mobile 6 device, written in C++ and the server is on full Windows and written in C#. Originally, I only needed it to send messages from the client to the server, with the server only ever sending back an acknowledgment that it received the message. Now, I would like to update it so that the server can actually send a message to the client to request data. As I currently have it set up so the client is only in receive mode after it sends data to the server, this doesn't allow for the server to send a request at any time. I would have to wait for client data. My first thought would be to create another thread on the client with a separate open socket, listening for server requests...just like the server already has in respect the the client. Is there a way, within the same thread and using the same socket, to all the server to send requests at any time? Can you use something to the affect of WaitForMultipleObjects() and pass it a receive buffer and an event that tells it there is data to be sent? "} {"user":"39","questionId":1229,"creationDate":"2008-08-04T13:54:01Z","answerId":1242,"type":"answer","body":"Link to http://www.whatever.com/hello.ppt#4 for slide 4 to be opened initially. Take a look at this site: http://www.tinyempire.com/shortnotes/files/specific_slide_in_ppt.htm "} {"user":"264","questionId":1237,"creationDate":"2008-08-04T13:55:05Z","answerId":1243,"type":"answer","body":"[start]\\s*(((?![start]|[end]).)+)\\s*[end] This should hopefully drop the [start] and [end] markers as well. "} {"user":"268","questionId":11,"creationDate":"2008-08-04T13:57:26Z","answerId":1248,"type":"answer","body":"Jeff, your code is nice but could be clearer with constants (as suggested in Code Complete). const int SECOND = 1; const int MINUTE = 60 * SECOND; const int HOUR = 60 * MINUTE; const int DAY = 24 * HOUR; const int MONTH = 30 * DAY; var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks); double delta = Math.Abs(ts.TotalSeconds); if (delta < 1 * MINUTE) return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\"; if (delta < 2 * MINUTE) return \"a minute ago\"; if (delta < 45 * MINUTE) return ts.Minutes + \" minutes ago\"; if (delta < 90 * MINUTE) return \"an hour ago\"; if (delta < 24 * HOUR) return ts.Hours + \" hours ago\"; if (delta < 48 * HOUR) return \"yesterday\"; if (delta < 30 * DAY) return ts.Days + \" days ago\"; if (delta < 12 * MONTH) { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1 ? \"one month ago\" : months + \" months ago\"; } else { int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1 ? \"one year ago\" : years + \" years ago\"; } "} {"user":"30","questionId":1237,"creationDate":"2008-08-04T14:00:04Z","answerId":1252,"type":"answer","body":"With Perl you can surround the data you want with ()'s and pull it out later, perhaps other languages have a similar feature. if ($s_output =~ /(data data data data START(data data data)END (data data)/) { $dataAllOfIt = $1; # 1 full string $dataInMiddle = $2; # 2 Middle Data $dataAtEnd = $3; # 3 End Data } "} {"user":"206","questionId":1033,"creationDate":"2008-08-04T14:02:14Z","answerId":1257,"type":"answer","body":"I don't know how accurate that hostip.info site is. I just visted that site, and it reported that my country is Canada. I'm in the US and the ISP that my office uses only operates from the US. It does allow you to correct it's guess, but if you are using this service to track web site vistors by country, you'll have no way of knowing if the data is correct. Of course, I'm just one data point. I downloaded the GeoLite Country database, which is just a .csv file, and my IP address was correctly identified as US. Another benefit of the MaxMind product line (paid or free) is that you have the data, you don't incur the performance hit of making a web service call to another system. "} {"user":"Jin","questionId":1229,"creationDate":"2008-08-04T14:06:02Z","answerId":1260,"type":"answer","body":"I found the answer. all you have to do is add #n after .ppt. For example, http://www.whatever.com/hello.ppt#4 will take you straight to the 4th slide. "} {"user":"292","tags":["svn","version-control","cvs"],"questionId":1261,"creationDate":"2008-08-04T14:06:48Z","title":"What are the advantages of using SVN over CVS?","acceptedAnswerId":1272,"type":"question","body":"My company is using CVS as our de-facto standard for source control. However, I've heard a lot of people say that SVN is better. I know SVN is newer, but other than that, I'm unfamiliar with its benefits. What I'm looking for is a good, succinct comparison of the two systems, noting any advantages or disadvantages of each in a Java/Eclipse development environment. "} {"user":"257","questionId":104,"creationDate":"2008-08-04T14:09:47Z","answerId":1263,"type":"answer","body":"All memory leaks are resolved by program termination. Leak enough memory and the Operating System may decide to resolve the problem on your behalf. "} {"user":"91","questionId":1261,"creationDate":"2008-08-04T14:09:54Z","answerId":1264,"type":"answer","body":"One of the many comparisons: http://wiki.scummvm.org/index.php/CVS_vs_SVN Now this is very specific to that project, but a lot of stuff apllies in general. Pro Subversion: Support for versioned renames/moves (impossible with CVS): Fingolfin, Ender Supports directories natively: It's possible to remove them, and they are versioned: Fingolfin, Ender File properties are versioned; no more \"executable bit\" hell: Fingolfin Overall revision number makes build versioning and regression testing much easier: Ender, Fingolfin Atomic commits: Fingolfin Intuitive (directory-based) branching and tagging: Fingolfin Easier hook scripts (pre/post commit, etc): SumthinWicked (I use it for Doxygen after commits) Prevents accidental committing of conflicted files: Salty-horse, Fingolfin Support for custom 'diff' command: Fingolfin Offline diffs, and they're instant: sev "} {"user":"267","questionId":564,"creationDate":"2008-08-04T14:11:03Z","answerId":1266,"type":"answer","body":"I'll just post here since some of the other posts are slightly inaccurate in relation to C#. Correct: int is an alias for System.Int32. Wrong: float is not an alias for System.Float, but for System.Single Basically, int is a reserved keyword in the C# programming language, and is an alias for the System.Int32 value type. float and Float is not the same however, as the right system type for ''float'' is System.Single. There are some types like this that has reserved keywords that doesn't seem to match the type names directly. In C# there is no difference between ''int'' and ''System.Int32'', or any of the other pairs or keywords/system types, except for when defining enums. With enums you can specify the storage size to use and in this case you can only use the reserved keyword, and not the system runtime type name. Wether the value in the int will be stored on the stack, in memory, or as a referenced heap object depends on the context and how you use it. This declaration in a method: int i; defines a variable i of type System.Int32, living in a register or on the stack, depending on optimizations. The same declaration in a type (struct or class) defines a member field. The same declaration in a method argument list defines a parameter, with the same storage options as for a local variable. (note that this paragraph is not valid if you start pulling iterator methods into the mix, these are different beasts altogether) To get a heap object, you can use boxing: object o = i; this will create a boxed copy of the contents of i on the heap. In IL you can access methods on the heap object directly, but in C# you need to cast it back to an int, which will create another copy. Thus, the object on the heap cannot easily be changed in C# without creating a new boxed copy of a new int value. (Ugh, this paragraph doesn't read all that easily.) "} {"user":"48","questionId":1261,"creationDate":"2008-08-04T14:14:14Z","answerId":1269,"type":"answer","body":"The Subversion book has an appendix that details important differences from CVS, which may help you make your decision. The two approaches are more or less the same idea but SVN was specifically designed to fix long standing flaws in CVS so, in theory at least, SVN will always be the better choice. "} {"user":"268","questionId":1261,"creationDate":"2008-08-04T14:17:59Z","answerId":1272,"type":"answer","body":"CVS only tracks modification on a file-by-file basis, while SVN tracks a whole commit as a new revision, which means that it is easier to follow the history of your project. Add the fact that all modern source control software use the concept of revision so it is far easier to migrate from SVN than it is from CVS. There is also the atomic commit problem. While I only encountered it once, it is possible that 2 people committing together in CVS can conflict each other, losing some data and putting your client in an inconsistent state. When detected early, these problems are not major because your data is still out there somewhere, but it can be a pain in a stressful environment. And finally, not many tools are developed around CVS anymore. While the new and shiny-new tools like Git or Mercurial definitely lack tools yet, SVN has a pretty large application base on any system. EDIT 2015: Seriously, this answer is 7 years old now. Forget SVN, go use Git like everyone else! "} {"user":"46","questionId":1241,"creationDate":"2008-08-04T14:30:12Z","answerId":1275,"type":"answer","body":"When I needed to write an application with a client-server model where the clients could leave and enter whenever they want, (I assume that's also the case for your application as you use mobile devices) I made sure that the clients send an online message to the server, indicating they were connected and ready to do whatever they needed doing. at that time the server could send messages back to the client trough the same open connection. Also, but I don't know if that is applicable for you, I had some sort of heartbeat the clients sent to the server, letting it know it was still online. That way the server knows when a client was forcibly disconnected from the network and it could mark that client back as offline. "} {"user":"30","tags":["mysql","database","database-performance"],"questionId":1276,"creationDate":"2008-08-04T14:31:11Z","title":"How big can a MySQL database get before performance starts to degrade","acceptedAnswerId":1338,"type":"question","body":"At what point does a MySQL database start to lose performance? Does physical database size matter? Do number of records matter? Is any performance degradation linear or exponential? I have what I believe to be a large database, with roughly 15M records which take up almost 2GB. Based on these numbers, is there any incentive for me to clean the data out, or am I safe to allow it to continue scaling for a few more years? "} {"user":"275","questionId":1261,"creationDate":"2008-08-04T14:35:12Z","answerId":1278,"type":"answer","body":"SVN has 3 main advantages over CVS it's faster supports versioning of binary files and adds transactional commit (all or nothing) "} {"user":"35","questionId":835,"creationDate":"2008-08-04T14:40:20Z","answerId":1281,"type":"answer","body":"You can use the artifact directory variable inside the MSBuild script itself. Here's an example of how I'm running FxCop right now from my CC.Net MSBuild script (this script is what CC.Net points to - there is also a \"Build\" target in the script that includes an MSBuild task against the SLN to do the actual compilation): "} {"user":"Schmidty","tags":["sql","xss","sql-injection"],"questionId":1284,"creationDate":"2008-08-04T14:40:58Z","title":"Catching SQL Injection and other Malicious Web Requests","type":"question","body":"I am looking for a tool that can detect malicious requests (such as obvious SQL injection gets or posts) and will immediately ban the IP address of the requester/add to a blacklist. I am aware that in an ideal world our code should be able to handle such requests and treat them accordingly, but there is a lot of value in such a tool even when the site is safe from these kinds of attacks, as it can lead to saving bandwidth, preventing bloat of analytics, etc. Ideally, I'm looking for a cross-platform (LAMP/.NET) solution that sits at a higher level than the technology stack; perhaps at the web-server or hardware level. I'm not sure if this exists, though. Either way, I'd like to hear the community's feedback so that I can see what my options might be with regard to implementation and approach. "} {"user":"268","questionId":88,"creationDate":"2008-08-04T14:44:56Z","answerId":1290,"type":"answer","body":"Wine is actually using gettimeofday() to implement QueryPerformanceCounter() and it is known to make many Windows games work on Linux and Mac. Starts http://source.winehq.org/source/dlls/kernel32/cpu.c#L312 leads to http://source.winehq.org/source/dlls/ntdll/time.c#L448 "} {"user":"192","tags":[".net","collections","queue"],"questionId":1292,"creationDate":"2008-08-04T14:47:10Z","title":"Limit size of Queue in .NET?","acceptedAnswerId":1305,"type":"question","body":"I have a Queue object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class? "} {"user":"25","questionId":1292,"creationDate":"2008-08-04T14:52:40Z","answerId":1297,"type":"answer","body":"Why wouldn't you just use an array with a size of 2? A Queue is supposed to be able to dynamically grow and shrink. Or create a wrapper class around an instance of Queue instance and each time one enqueues a object, check the size of the queue. If larger than 2, dequeue the first item. "} {"user":"91","tags":[".net",".net-3.5","msbuild","nant"],"questionId":1300,"creationDate":"2008-08-04T14:55:04Z","title":"Is nAnt still supported and suitable for .net 3.5/VS2008?","acceptedAnswerId":1673,"type":"question","body":"I am using MSBuild to build my stuff. I want to use CruiseControl.net as by Build Server. Now, CCNET refers nAnt a lot, but it looks as if ccnet can do most of the stuff nant could do through the project configuration and msbuild. Also, nAnt seems a bit unsupported, with a Beta release that is almost a year old now. In short: I am actually quite happy with MSBuild (especially since it's the \"official\" compiler front end) and a bit uncomfortable with nAnt, but I do not want to judge prematurely. What would be reasons to use nAnt over MSBuild? Especially with ccnet, which seems to overlap a bit with nant in terms of features (and adding the automated build related stuff) "} {"user":"267","questionId":1292,"creationDate":"2008-08-04T14:56:49Z","answerId":1303,"type":"answer","body":"You should create your own class, a ringbuffer would probably fit your needs. The data structures in .NET that allows you to specify capacity, except for array, uses this to build the internal data structure used to hold the internal data. For instance, for a list, capacity is used to size an internal array. When you start adding elements to the list, it'll start filling this array from index 0 and up, and when it reaches your capacity, it increases the capacity to a new higher capacity, and continues filling it up. "} {"user":"121","tags":["c#",".net","io","filelock"],"questionId":1304,"creationDate":"2008-08-04T14:56:57Z","title":"How to check for file lock?","acceptedAnswerId":1309,"type":"question","body":"Is there any way to check whether a file is locked without using a try/catch block? Right now, the only way I know of is to just open the file and catch any System.IO.IOException. "} {"user":"192","questionId":1292,"creationDate":"2008-08-04T14:57:28Z","answerId":1305,"type":"answer","body":"I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along. public class LimitedQueue : Queue { public int Limit { get; set; } public LimitedQueue(int limit) : base(limit) { Limit = limit; } public new void Enqueue(T item) { while (Count >= Limit) { Dequeue(); } base.Enqueue(item); } } "} {"user":"302","tags":["ruby","unix","curses"],"questionId":1306,"creationDate":"2008-08-04T14:57:59Z","title":"How do I use (n)curses in Ruby?","acceptedAnswerId":1318,"type":"question","body":"I'd like to create a progress bar to indicate the status of an a batch job in Ruby. I've read some tutorials / libraries on using (n)curses, none of which were particularly helpful in explaining how to create an \"animated\" progress bar in the terminal or using curses with Ruby. I'm already aware of using a separate thread to monitor the progress of a given job, I'm just not sure how to proceed with drawing a progress bar. Update ProgressBar class was incredibly straight-forward, perfectly solved my problem. "} {"user":"267","questionId":1304,"creationDate":"2008-08-04T14:59:24Z","answerId":1309,"type":"answer","body":"No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan). Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice. If your code would look like this: if not locked then open and update file Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions. "} {"user":"306","tags":["c","audio","rockbox"],"questionId":1311,"creationDate":"2008-08-04T15:02:41Z","title":"Rockbox audio format","type":"question","body":"How do you specify a callback for rb->pcm_play_data()? "} {"user":"91","questionId":898,"creationDate":"2008-08-04T15:04:47Z","answerId":1312,"type":"answer","body":"I was just listening to a Podcast from Scott Hanselman this morning, where he talks about internationalization, especially the really tricky things, like Turkish (with it's four i's) and Thai. Also, Jeff Atwood had a post: "} {"user":"2089740","tags":["language-agnostic","colors"],"questionId":1313,"creationDate":"2008-08-04T15:08:13Z","title":"Followup: Finding an accurate \"distance\" between colors","acceptedAnswerId":74033,"type":"question","body":"Original Question I am looking for a function that attempts to quantify how \"distant\" (or distinct) two colors are. This question is really in two parts: What color space best represents human vision? What distance metric in that space best represents human vision (euclidean?) "} {"user":"312","tags":["msbuild","build-process","cruisecontrol.net"],"questionId":1314,"creationDate":"2008-08-04T15:09:07Z","title":"Using MSTest with CruiseControl.NET","acceptedAnswerId":1319,"type":"question","body":"We have been using CruiseControl for quite a while with NUnit and NAnt. For a recent project we decided to use the testing framework that comes with Visual Studio, which so far has been adequate. I'm attempting to get the solution running in CruiseControl. I've finally got the build itself to work; however, I have been unable to get any tests to show up in the CruiseControl interface despite adding custom build tasks and components designed to do just that. Does anyone have a definitive link out there to instructions on getting this set up? "} {"user":"48","questionId":1284,"creationDate":"2008-08-04T15:11:16Z","answerId":1317,"type":"answer","body":"The problem with a generic tool is that it is very difficult to come up with a set of rules that will only match against a genuine attack. SQL keywords are all English words and don't forget that the string DROP TABLE users; is perfectly valid in a form field that, for example, contains an answer to a programming question. The only sensible option is to sanitise the input before ever passing it to your database but pass it on nonetheless. Otherwise lots of perfectly normal, non-malicious users are going to get banned from your site. "} {"user":"216","questionId":1306,"creationDate":"2008-08-04T15:11:19Z","answerId":1318,"type":"answer","body":"You might be able to get some implementation ideas from the Ruby/ProgressBar library, which generates text progress bars. I stumbled across it a couple of months back but haven't made any use of it. "} {"user":"91","questionId":1314,"creationDate":"2008-08-04T15:12:13Z","answerId":1319,"type":"answer","body":"Not sure if that helps (i found the ccnet Documentation somewhat unhelpful at times): Using CruiseControl.NET with MSTest "} {"user":"312","questionId":1300,"creationDate":"2008-08-04T15:12:37Z","answerId":1320,"type":"answer","body":"In my opinion it is more a question of personal preference. nAnt is a great framework and MSBuild is almost as capable. With the ability to easily develop custom tasks (in both frameworks) you can accomplish almost anything that you need to do. I cannot answer the \"still supported\" portion of your questions, but I would say if you are already comfortable with nAnt then it's probably viable. If you (or someone in your group) is familiar with MSBuild then that is a fine way to go as well. "} {"user":"268","questionId":1313,"creationDate":"2008-08-04T15:14:39Z","answerId":1321,"type":"answer","body":"May look like spam but no, this link is really interesting for color spaces :) http://www.compuphase.com/cmetric.htm "} {"user":"267","questionId":1313,"creationDate":"2008-08-04T15:14:40Z","answerId":1322,"type":"answer","body":"The easiest distance would of course be to just consider the colors as 3d vectors originating from the same origin, and taking the distance between their end points. If you need to consider such factors that green is more prominent in judging intensity, you can weigh the values. ImageMagic provides the following scales: red: 0.3 green: 0.6 blue: 0.1 Of course, values like this would only be meaningful in relation to other values for other colors, not as something that would be meaningful to humans, so all you could use the values for would be similiarity ordering. "} {"user":"2089740","tags":["algorithm","language-agnostic","colors"],"questionId":1323,"creationDate":"2008-08-04T15:14:47Z","title":"Followup: \"Sorting\" colors by distinctiveness","type":"question","body":"Original Question If you are given N maximally distant colors (and some associated distance metric), can you come up with a way to sort those colors into some order such that the first M are also reasonably close to being a maximally distinct set? In other words, given a bunch of distinct colors, come up with an ordering so I can use as many colors as I need starting at the beginning and be reasonably assured that they are all distinct and that nearby colors are also very distinct (e.g., bluish red isn't next to reddish blue). Randomizing is OK but certainly not optimal. Clarification: Given some large and visually distinct set of colors (say 256, or 1024), I want to sort them such that when I use the first, say, 16 of them that I get a relatively visually distinct subset of colors. This is equivalent, roughly, to saying I want to sort this list of 1024 so that the closer individual colors are visually, the farther apart they are on the list. "} {"user":"39","questionId":1313,"creationDate":"2008-08-04T15:16:11Z","answerId":1325,"type":"answer","body":"HSL and HSV are better for human color perception. According to Wikipedia: It is sometimes preferable in working with art materials, digitized images, or other media, to use the HSV or HSL color model over alternative models such as RGB or CMYK, because of differences in the ways the models emulate how humans perceive color. RGB and CMYK are additive and subtractive models, respectively, modelling the way that primary color lights or pigments (respectively) combine to form new colors when mixed. "} {"user":"121","questionId":1284,"creationDate":"2008-08-04T15:20:17Z","answerId":1328,"type":"answer","body":"One method that might work for some cases would be to take the sql string that would run if you naively used the form data and pass it to some code that counts the number of statements that would actually be executed. If it is greater than the number expected, then there is a decent chance that an injection was attempted, especially for fields that are unlikely to include control characters such as username. Something like a normal text box would be a bit harder since this method would be a lot more likely to return false positives, but this would be a start, at least. "} {"user":"83","tags":["windows","file","filesystems","utilities"],"questionId":1329,"creationDate":"2008-08-04T15:20:42Z","title":"What is a better file copy alternative than the Windows default?","acceptedAnswerId":1339,"type":"question","body":"I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows. I don't want it to hang on a \"Are you sure?\", \"Are you really sure?\", \"Even zip files?\", \"Surely not read-only files too!\" loop as soon as I step away. I don't want it to work for hours and then stop unexpectedly: \"Someone once opened this file and so I won't copy it!\" and then cancel the whole copy or just quit with no indication of what was done and what work remains. What file management programs do you have experience with? Which do you recommend? This question is related to my other question: How can I use an old PATA hard disk drive on my newer SATA-only computer? "} {"user":"39","questionId":1329,"creationDate":"2008-08-04T15:21:49Z","answerId":1331,"type":"answer","body":"Use Robocopy (Robust File Copy). NOTE: In Windows Vista and Server 2008 when you type: xcopy /? you get: NOTE: Xcopy is now deprecated, please use Robocopy. So start getting used to robocopy :) "} {"user":"313","questionId":289,"creationDate":"2008-08-04T15:22:03Z","answerId":1332,"type":"answer","body":"Why not use LINQ: Dictionary myDict = new Dictionary(); myDict.Add(\"one\", 1); myDict.Add(\"four\", 4); myDict.Add(\"two\", 2); myDict.Add(\"three\", 3); var sortedDict = from entry in myDict orderby entry.Value ascending select entry; This would also allow for great flexibility in that you can select the top 10, 20 10% etc. Or if you are using your word frequency index for type-ahead, you could also include StartsWith clause as well. "} {"user":"91","questionId":1284,"creationDate":"2008-08-04T15:22:04Z","answerId":1333,"type":"answer","body":"One little thing to keep in mind: In some countries (i.e. most of Europe), people do not have static IP Addresses, so blacklisting should not be forever. "} {"user":"267","questionId":1329,"creationDate":"2008-08-04T15:23:08Z","answerId":1334,"type":"answer","body":"You can try TeraCopy or RoboCopy. "} {"user":"29","questionId":1329,"creationDate":"2008-08-04T15:24:03Z","answerId":1335,"type":"answer","body":"It sounds like a backup-style tool may be what you're looking for. I've been using SyncBack (one of the versions is free). You could also try out MS SyncToy which tries to make moving, copying, syncing, etc. easy. If you really do copy just random files at random times, you could try Total Copy which has the added benefit of working well over a network (pause, resume, etc.). "} {"user":"121","questionId":1284,"creationDate":"2008-08-04T15:26:05Z","answerId":1336,"type":"answer","body":"Now that I think about it, a Bayesian filter similar to the ones used to block spam might work decently too. If you got together a set of normal text for each field and a set of sql injections, you might be able to train it to flag injection attacks. "} {"user":"194","questionId":1329,"creationDate":"2008-08-04T15:26:39Z","answerId":1337,"type":"answer","body":"You really need to use a file Sync tool, like SyncBackSE, MS SyncToy, or even something like WinMerge will do the trick. I prefer SyncBack as it allows you to set up very explicit rules for just about every possible case and conflict, at least more so than the other two. With any of these you won't have to keep clicking all the pop-ups and you can verify, without a doubt, that the destination is exactly the same as the source. "} {"user":"17","questionId":1276,"creationDate":"2008-08-04T15:26:55Z","answerId":1338,"type":"answer","body":"The physical database size doesn't matter. The number of records don't matter. In my experience the biggest problem that you are going to run in to is not size, but the number of queries you can handle at a time. Most likely you are going to have to move to a master/slave configuration so that the read queries can run against the slaves and the write queries run against the master. However if you are not ready for this yet, you can always tweak your indexes for the queries you are running to speed up the response times. Also there is a lot of tweaking you can do to the network stack and kernel in Linux that will help. I have had mine get up to 10GB, with only a moderate number of connections and it handled the requests just fine. I would focus first on your indexes, then have a server admin look at your OS, and if all that doesn't help it might be time to implement a master/slave configuration. "} {"user":"91","questionId":1329,"creationDate":"2008-08-04T15:28:23Z","answerId":1339,"type":"answer","body":"How about good old Command-Line Xcopy? With S: being the source and T: the target: xcopy /K /R /E /I /S /C /H /G /X /Y s:\\*.* t:\\ /K Copies attributes. Normal Xcopy will reset read-only attributes. /R Overwrites read-only files. /E Copies directories and subdirectories, including empty ones. /I If destination does not exist and copying more than one file, assumes that destination must be a directory. /S Copies directories and subdirectories except empty ones. /C Continues copying even if errors occur. /H Copies hidden and system files also. /Y Suppresses prompting to confirm you want to overwrite an existing destination file. /G Allows the copying of encrypted files to destination that does not support encryption. /X Copies file audit settings (implies /O). (Edit: Added /G and /X which are new since a few years) "} {"user":"267","questionId":1323,"creationDate":"2008-08-04T15:29:49Z","answerId":1340,"type":"answer","body":"Do you mean that from a set of N colors, you need to pick M colors, where M < N, such that M is the best representation of the N colors in the M space? As a better example, reduce a true-color (24 bit color space) to a 8-bit mapped color space (GIF?). There are quantization algorithms for this, like the Adaptive Spatial Subdivision algorithm used by ImageMagic. These algorithms usually don't just pick existing colors from the source space but creates new colors in the target space that most closely resemble the source colors. As a simplified example, if you have 3 colors in the original image where two are red (with different intensity or bluish tints etc.) and the third is blue, and need to reduce to two colors, the target image could have a red color that is some kind of average of the original two red + the blue color from the original image. If you need something else then I didn't understand your question :) "} {"user":"268","questionId":1329,"creationDate":"2008-08-04T15:31:04Z","answerId":1341,"type":"answer","body":"You can try SuperCopier, it replaces the standard Windows copy mechanism while loaded. It can retry failed files at the end, resume a canceled copy (even a copy canceled by Windows), accepts \"All\" for every answers. You can even answer the annoying questions (file already exists, error copying file) before they occur. "} {"user":"17","questionId":1323,"creationDate":"2008-08-04T15:31:15Z","answerId":1342,"type":"answer","body":"You can split them in to RGB HEX format so that you can compare the R with R's of a different color, same with the G and B. Same format as HTML XX XX XX RR GG BB 00 00 00 = black ff ff ff = white ff 00 00 = red 00 ff 00 = green 00 00 ff = blue So the only thing you would need to decide is how close you want the colors and what is an acceptable difference for the segments to be considered different. "} {"user":"17","questionId":1300,"creationDate":"2008-08-04T15:37:31Z","answerId":1347,"type":"answer","body":"Honestly it depends on what fits in to your environment better. If you are using a lot of Non-Microsoft tools, nunit, ccnet, ncover. You will probably find better support with nant. Alternatively if you are using MSTest, TFSBuild, you will probably find MSBuild a better environment. I would learn both and use which every fits more smoothly with your environment. "} {"user":"199","questionId":1313,"creationDate":"2008-08-04T15:37:43Z","answerId":1348,"type":"answer","body":"Well, as a first point of call, I'd say of the common metrics HSV (Hue, Saturation and Value) or HSL are better representative of how humans perceive colour than say RGB or CYMK. See HSL, HSV on Wikipedia. I suppose naively I would plot the points in the HSL space for the two colours and calculate the magnitude of the difference vector. However this would mean that bright yellow and bright green would be considered just as different as green to dark green. But then many consider red and pink two different colours. Moreover, difference vectors in the same direction in this parameter space are not equal. For instance, the human eye picks up green much better than other colours. A shift in hue from green by the same amount as a shift from red may seem greater. Also a shift in saturation from a small amount to zero is the difference between grey and pink, elsewhere the shift would be the difference between two shades of red. From a programmers point of view, you would need to plot the difference vectors but modified by a proportionality matrix that would adjust the lengths accordingly in various regions of the HSL space - this would be fairly arbitrary and would be based on various colour theory ideas but be tweaked fairly arbitrarily depending on what you wanted to apply this to. Even better, you could see if anyone has already done such a thing online... "} {"user":"267","questionId":1323,"creationDate":"2008-08-04T15:38:09Z","answerId":1351,"type":"answer","body":"This also sounds to me like some kind of resistance graph where you try to map out the path of least resistance. If you inverse the requirements, path of maximum resistance, it could perhaps be used to produce a set that from the start produces maximum difference as you go, and towards the end starts to go back to values closer to the others. For instance, here's one way to perhaps do what you want. Calculate the distance (ref your other post) from each color to all other colors Sum the distances for each color, this gives you an indication for how far away this color is from all other colors in total Order the list by distance, going down This would, it seems, produce a list that starts with the color that is farthest away from all other colors, and then go down, colors towards the end of the list would be closer to other colors in general. Edit: Reading your reply to my first post, about the spatial subdivision, would not exactly fit the above description, since colors close to other colors would fall to the bottom of the list, but let's say you have a cluster of colors somewhere, at least one of the colors from that cluster would be located near the start of the list, and it would be the one that generally was farthest away from all other colors in total. If that makes sense. "} {"user":"91","questionId":1329,"creationDate":"2008-08-04T15:41:39Z","answerId":1353,"type":"answer","body":"Xcopy keeps the Date Modified, only the Date Created and Date Accessed will change. (tested on XP Pro, try it on a small folder to check if you're using Vista as I did not test it under Vista) Edit: You MAY want to redirect the Output though: xcopy /K /R ....... s:\\*.* t:\\ >c:\\xcopy.log 2>&1 That way, if files fail to copy you can check the log (i.e. System Volume Information will generate an error, but that folder does not matter anyway for what you're trying to do) "} {"user":"314","questionId":1284,"creationDate":"2008-08-04T15:43:50Z","answerId":1356,"type":"answer","body":"Your almost looking at it the wrong way, no 3party tool that is not aware of your application methods/naming/data/domain is going to going to be able to perfectly protect you. Something like SQL injection prevention is something that has to be in the code, and best written by the people that wrote the SQL, because they are the ones that will know what should/shouldnt be in those fields (unless your project has very good docs) Your right, this all has been done before. You dont quite have to reinvent the wheel, but you do have to carve a new one because of a differences in everyone's axle diameters. This is not a drop-in and run problem, you really do have to be familiar with what exactly SQL injection is before you can prevent it. It is a sneaky problem, so it takes equally sneaky protections. These 2 links taught me far more then the basics on the subject to get started, and helped me better phrase my future lookups on specific questions that weren't answered. SQL injection SQL Injection Attacks by Example And while this one isnt quite a 100% finder, it will \"show you the light\" on existing problem in your existing code, but like with webstandards, dont stop coding once you pass this test. Exploit-Me "} {"user":"35","questionId":1314,"creationDate":"2008-08-04T15:46:42Z","answerId":1359,"type":"answer","body":"The CC.Net interface is generated via an XSL transform on your XML files put together as specified in the ccnet.config file for your projects. The XSL is already written for things like FxCop - check your server's CC xsl directory for examples - shouldn't be too hard to write your own to add in the info - just remember to add the XML output from your tests into the main log. "} {"user":"35","questionId":1300,"creationDate":"2008-08-04T15:52:42Z","answerId":1364,"type":"answer","body":"If you've already got a bunch of custom tasks you use with nAnt, stick with it - you don't gain much with MSBuild. That said, there doesn't seem to be anything that nAnt can do that MSBuild can't at its core. Both can call external tools, both can run .Net-based custom tasks, and both have a bunch of community tasks out there. We're using MSBuild here for the same reason you are - it's the default build system for VS now, and we didn't have any nAnt-specific stuff to worry about. The MSBuildCommunityTasks are a good third-party task base to start with, and covers most of the custom stuff I ever did in nAnt, including VSS and Subversion support. "} {"user":"136","questionId":1306,"creationDate":"2008-08-04T16:03:22Z","answerId":1375,"type":"answer","body":"On windows, curses works out of the box, ncurses doesn't, and for a progress bar curses should be sufficient. So, use curses instead of ncurses. Also, both curses and ncurses are wafer-thin wrappers around the c library - that means you don't really need Ruby-specific tutorials. However, on the site for the PickAxe you can download all the code examples for the book. The file \"ex1423.rb\" contains a curses demo which plays Pong - that should give you plenty of material to get you going. "} {"user":"26","tags":["flex","air"],"questionId":1376,"creationDate":"2008-08-04T16:05:29Z","title":"Get the current logged in OS user in Adobe Air","type":"question","body":"I need the name of the current logged in user in my Air/Flex application. The application will only be deployed on Windows machines. I think I could attain this by regexing the User directory, but am open to other ways. "} {"user":"269","questionId":1306,"creationDate":"2008-08-04T16:18:32Z","answerId":1378,"type":"answer","body":"Personally I think curses is overkill in this case. While the curses lib is nice (and I frequently use it myself) it's a PITA to relearn every time I haven't needed it for 12 months which has to be the sign of a bad interface design. If for some reason you can't get on with the progress bar lib Joey suggested roll your own and release it under a pretty free licence for instant kudos :) "} {"user":"26","questionId":1376,"creationDate":"2008-08-04T16:19:45Z","answerId":1380,"type":"answer","body":"Here is a solution that works in XP / Vista, but is definitely expandable to OSX, linux, I'd still be interested in another way. public static function GetCurrentOSUser():String{ // XP & Vista only. var userDirectory:String = File.userDirectory.resolvePath(\"\").nativePath; var startIndex:Number = userDirectory.lastIndexOf(\"\\\\\") + 1 var stopIndex:Number = userDirectory.length; var user = userDirectory.substring(startIndex, stopIndex); return user; } "} {"user":"206","questionId":1329,"creationDate":"2008-08-04T16:25:14Z","answerId":1381,"type":"answer","body":"Use Robocopy, it has the ability to copy files in \"restartable mode\", plus it should respect the file attributes. And it comes with Vista and Server 2008, and you can download it for older OS's. Plus you can set it to retry on failed copies, to pick up files that are temporarily in use by another process. "} {"user":"314","tags":["unit-testing","glossary"],"questionId":1383,"creationDate":"2008-08-04T16:27:39Z","title":"What is unit testing?","acceptedAnswerId":1393,"type":"question","body":"I saw many questions asking 'how' to unit test in a specific language, but no question asking 'what', 'why', and 'when'. What is it? What does it do for me? Why should I use it? When should I use it (also when not)? What are some common pitfalls and misconceptions "} {"user":"230","tags":[".net","nhibernate","orm","subsonic"],"questionId":1384,"creationDate":"2008-08-04T16:29:23Z","title":"Subsonic Vs NHibernate","type":"question","body":"What is the concensus on when to use one of these tools adversed to the other? I find Subsonic very useful in terms of getting things done quickly, but on large projects it tends not to scale, and its ties your domain model to your database model. That is where Nhibernate comes in as it gives you lightweight POCOs that are unrelated to your database model, but the setup time is much longer. "} {"user":"Larsenal","tags":[".net","parallel-processing"],"questionId":1387,"creationDate":"2008-08-04T16:30:46Z","title":"What are the current best options for parallelizing a CPU-intensive .NET app?","type":"question","body":"This is an open-ended question. What approaches should I consider? "} {"user":"60","tags":["sql-server","windows-server-2008"],"questionId":1390,"creationDate":"2008-08-04T16:33:36Z","title":"Is Windows Server 2008 \"Server Core\" appropriate for a SQL Server instance?","acceptedAnswerId":1394,"type":"question","body":"I'm setting up a dedicated SQL Server 2005 box on Windows Server 2008 this week, and would like to pare it down to be as barebones as possible while still being fully functional. To that end, the \"Server Core\" option sounds appealing, but I'm not clear about whether or not I can run SQL Server on that SKU. Several services are addressed on the Microsoft website, but I don't see any indication about SQL Server. Does anyone know definitively? "} {"user":"266","questionId":1383,"creationDate":"2008-08-04T16:36:51Z","answerId":1393,"type":"answer","body":"Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are: Running the tests becomes automate-able and repeatable You can test at a much more granular level than point-and-click testing via a GUI Note that if your test code writes to a file, opens a database connection or does something over the network, it's more appropriately categorized as an integration test. Integration tests are a good thing, but should not be confused with unit tests. Unit test code should be short, sweet and quick to execute. Another way to look at unit testing is that you write the tests first. This is known as Test-Driven Development (TDD for short). TDD brings additional advantages: You don't write speculative \"I might need this in the future\" code -- just enough to make the tests pass The code you've written is always covered by tests By writing the test first, you're forced into thinking about how you want to call the code, which usually improves the design of the code in the long run. If you're not doing unit testing now, I recommend you get started on it. Get a good book, practically any xUnit-book will do because the concepts are very much transferable between them. Sometimes writing unit tests can be painful. When it gets that way, try to find someone to help you, and resist the temptation to \"just write the damn code\". Unit testing is a lot like washing the dishes. It's not always pleasant, but it keeps your metaphorical kitchen clean, and you really want it to be clean. :) Edit: One misconception comes to mind, although I'm not sure if it's so common. I've heard a project manager say that unit tests made the team write all the code twice. If it looks and feels that way, well, you're doing it wrong. Not only does writing the tests usually speed up development, but it also gives you a convenient \"now I'm done\" indicator that you wouldn't have otherwise. "} {"user":"91","questionId":1390,"creationDate":"2008-08-04T16:38:03Z","answerId":1394,"type":"answer","body":"Not sure how credible this source is, but: The Windows Server 2008 Core edition can: Run the file server role. Run the Hyper-V virtualization server role. Run the Directory Services role. Run the DHCP server role. Run the IIS Web server role. Run the DNS server role. Run Active Directory Lightweight Directory Services. Run the print server role. The Windows Server 2008 Core edition cannot: Run a SQL Server. Run an Exchange Server. Run Internet Explorer. Run Windows Explorer. Host a remote desktop session. Run MMC snap-in consoles locally. "} {"user":"40","questionId":1376,"creationDate":"2008-08-04T16:39:40Z","answerId":1397,"type":"answer","body":"Also I would try: File.userDirectory.name But I don't have Air installed so I can't really test this... "} {"user":"34","questionId":1383,"creationDate":"2008-08-04T16:41:17Z","answerId":1398,"type":"answer","body":"I don't disagree with Dan (although a better choice may just be not to answer)...but... Unit testing is the process of writing code to test the behavior and functionality of your system. Obviously tests improve the quality of your code, but that's just a superficial benefit of unit testing. The real benefits are to: Make it easier to change the technical implementation while making sure you don't change the behavior (refactoring). Properly unit tested code can be aggressively refactored/cleaned up with little chance of breaking anything without noticing it. Give developers confidence when adding behavior or making fixes. Document your code Indicate areas of your code that are tightly coupled. It's hard to unit test code that's tightly coupled Provide a means to use your API and look for difficulties early on Indicates methods and classes that aren't very cohesive You should unit test because its in your interest to deliver a maintainable and quality product to your client. I'd suggest you use it for any system, or part of a system, which models real-world behavior. In other words, it's particularly well suited for enterprise development. I would not use it for throw-away/utility programs. I would not use it for parts of a system that are problematic to test (UI is a common example, but that isn't always the case) The greatest pitfall is that developers test too large a unit, or they consider a method a unit. This is particularly true if you don't understand Inversion of Control - in which case your unit tests will always turn into end-to-end integration testing. Unit test should test individual behaviors - and most methods have many behaviors. The greatest misconception is that programmers shouldn't test. Only bad or lazy programmers believe that. Should the guy building your roof not test it? Should the doctor replacing a heart valve not test the new valve? Only a programmer can test that his code does what he intended it to do (QA can test edge cases - how code behaves when it's told to do things the programmer didn't intend, and the client can do acceptance test - does the code do what what the client paid for it to do) "} {"user":"200","questionId":1387,"creationDate":"2008-08-04T16:41:23Z","answerId":1399,"type":"answer","body":"There are some parallel extensions to .NET that are currently in testing and available at Microsoft's Parallel Computing Developer Center. They have a few interesting items that you would expect like Parallel foreach and a parallel version of LINQ called PLINQ. Some of the best information about the extensions is on Channel 9. "} {"user":"149","tags":["asp.net","javascript","validation"],"questionId":1401,"creationDate":"2008-08-04T16:44:25Z","title":"ASP.Net Custom Client-Side Validation","acceptedAnswerId":1418,"type":"question","body":"I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due. I've placed the validator code in the ascx file, and I have also tried using Page.ClientScript.RegisterClientScriptBlock() and in both cases the validation fires, but cannot find the JavaScript function. The output in Firefox's error console is \"feeAmountCheck is not defined\". Here is the function (this was taken directly from firefox->view source) Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page? "} {"user":"212","questionId":9,"creationDate":"2008-08-04T16:50:06Z","answerId":1404,"type":"answer","body":"An easy to understand and simple solution. // Save today's date. var today = DateTime.Today; // Calculate the age. var age = today.Year - birthdate.Year; // Go back to the year the person was born in case of a leap year if (birthdate > today.AddYears(-age)) age--; However, this assumes you are looking for the western idea of age and not using East Asian reckoning. "} {"user":"225","questionId":1401,"creationDate":"2008-08-04T16:51:03Z","answerId":1405,"type":"answer","body":"When you're using .Net 2.0 and Ajax - you should use: ScriptManager.RegisterClientScriptBlock It will work better in Ajax environments then the old Page.ClientScript version "} {"user":"58","tags":["php","apache","xampp","server-configuration"],"questionId":1408,"creationDate":"2008-08-04T16:54:49Z","title":"Make XAMPP/Apache serve file outside of htdocs","acceptedAnswerId":1421,"type":"question","body":"Is it possible to configure xampp to serve up a file outside of the htdocs directory? For instance, say I have a file located as follows: C:\\projects\\transitCalculator\\trunk\\TransitCalculator.php and my xampp files are normally served out from: C:\\xampp\\htdocs\\ (because that's the default configuration) Is there some way to make Apache recognize and serve up my TransitCalculator.php file without moving it under htdocs? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under htdocs. edit: edited to add Apache to the question title to make Q/A more \"searchable\" "} {"user":"26","tags":["asp.net","iis"],"questionId":1409,"creationDate":"2008-08-04T16:55:31Z","title":"Bandwith throttling in IIS 6 by IP Address","acceptedAnswerId":27335,"type":"question","body":"I am writing an application that downloads large files in the background. All clients are logged in locally, or through a VPN. When they are logged in locally, I do not want to throttle downloads. However, I would like to limit downloads to 10 KBps when the user is connected via VPN. I can differentiate between these users by IP Address range. Since this is an AIR Application, I figure I will throttle via server-side since I can do it from either the server itself (IIS 6) or the web service (asp.net / C#). Throttling through IIS 6 seems to work fine, but it seems like it has to be done across the entire web site. Is there anyway to do this via IP? Or will I have to rig this up in .NET? "} {"user":"269","questionId":1408,"creationDate":"2008-08-04T17:00:08Z","answerId":1413,"type":"answer","body":"You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form. Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot. EDIT: alias myapp c:\\myapp\\ I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term. "} {"user":"60","questionId":1408,"creationDate":"2008-08-04T17:00:27Z","answerId":1414,"type":"answer","body":"You can relocate it by editing the DocumentRoot setting in XAMPP\\apache\\conf\\httpd.conf. It should currently be: C:/xampp/htdocs Change it to: C:/projects/transitCalculator/trunk "} {"user":"70","questionId":588,"creationDate":"2008-08-04T17:00:40Z","answerId":1415,"type":"answer","body":"I would look into IMAP IMAP, POP3 and NNTP "} {"user":"287","tags":["php","apache","authentication","http-authentication"],"questionId":1417,"creationDate":"2008-08-04T17:02:31Z","title":"How can I get the authenticated user name under Apache using plain HTTP authentication and PHP?","acceptedAnswerId":1425,"type":"question","body":"First, let's get the security considerations out of the way. I'm using simple authentication under Apache for a one-off, internal use only, non-internet connected lan, php web app. How can get I the HTTP authenticated user name in PHP? "} {"user":"35","questionId":1401,"creationDate":"2008-08-04T17:02:56Z","answerId":1418,"type":"answer","body":"Try changing the argument names to sender and args. And, after you have it working, switch the call over to ScriptManager.RegisterClientScriptBlock, regardless of AJAX use. "} {"user":"26","questionId":246,"creationDate":"2008-08-04T17:05:37Z","answerId":1420,"type":"answer","body":"I'm sure you could write a small app that takes an XSD file and parses it into a SQL script. I've never seen code out there to do it though, but that's not saying it doesn't exist. "} {"user":"58","questionId":1408,"creationDate":"2008-08-04T17:05:48Z","answerId":1421,"type":"answer","body":"Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this: Virtual Hosts Open C:\\xampp\\apache\\conf\\extra\\httpd-vhosts.conf. Un-comment line 19 (NameVirtualHost *:80). Add your virtual host (~line 36): DocumentRoot C:\\Projects\\transitCalculator\\trunk ServerName transitcalculator.localhost Order allow,deny Allow from all Open your hosts file (C:\\Windows\\System32\\drivers\\etc\\hosts). Add transitcalculator.localhost #transitCalculator to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed). Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble). Restart Apache. Now you can access that directory by browsing to http://transitcalculator.localhost/. Make an Alias Starting ~line 200 of your http.conf file, copy everything between and (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory. Find the section (~line 300) and add Alias /transitCalculator \"C:/Projects/transitCalculator/trunk\" (or whatever is relevant to your desires) below the Alias comment block, inside the module tags. Change your document root Edit ~line 176 in C:\\xampp\\apache\\conf\\httpd.conf; change DocumentRoot \"C:/xampp/htdocs\" to #DocumentRoot \"C:/Projects\" (or whatever you want). Edit ~line 203 to match your new location (in this case C:/Projects). Notes: You have to use forward slashes \"/\" instead of back slashes \"\\\". Don't include the trailing \"/\" at the end. restart your server. "} {"user":"1384652","questionId":1417,"creationDate":"2008-08-04T17:08:26Z","answerId":1425,"type":"answer","body":"I think that you are after this $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; "} {"user":"45","questionId":1384,"creationDate":"2008-08-04T17:12:53Z","answerId":1428,"type":"answer","body":"I think you pretty much nailed it. Subsonic generates code, so your business objects will be reflective of your database structure. nHibernate uses mapping files which map your business objects to the database so your objects can be structured however you like. How large of a project is this? Will there be long term support needed? Is the cost effectiveness of Subsonic going to offset any potential scaling issues? "} {"user":"269","questionId":1176,"creationDate":"2008-08-04T17:16:26Z","answerId":1430,"type":"answer","body":"I think if you are attempting to learn a new language do something fun in that language. I learned python by writing lots of web spiders and little toys and for ruby I'd take exactly the same path. Instead of finding a project that needs input do a couple of little personal projects to get a feel for the language. You learn more by doing something then by reading lots of examples and other peoples code in those first few months. A language like Ruby is structured in such a way you can do something productive straight out of the box without much support so jump right in and do something fun rather than think you have to do something for somebody else right at the beginning of your experimentation with a new language. have fun with Ruby, it's on my short list of things to play with :) "} {"user":"60","questionId":427,"creationDate":"2008-08-04T17:28:46Z","answerId":1435,"type":"answer","body":"How about running IE with the HTML favorites file as a parameter? IExplore file://\\windows\\fav.htm "} {"user":"Larsenal","questionId":1387,"creationDate":"2008-08-04T17:32:13Z","answerId":1436,"type":"answer","body":"I think we could also include non-.NET-specific approaches to parallel processing if those are among the best options to consider. "} {"user":"55","questionId":1104,"creationDate":"2008-08-04T17:33:57Z","answerId":1437,"type":"answer","body":"Or you could start throwing critical exceptions. Surely, an access violation exception will catch your users' attention. "} {"user":"307","questionId":580,"creationDate":"2008-08-04T17:38:59Z","answerId":1446,"type":"answer","body":"Using SMO/DMO, it isn't too difficult to generate a script of your schema. Data is a little more fun, but still doable. In general, I take \"Script It\" approach, but you might want to consider something along these lines: Distinguish between Development and Staging, such that you can Develop with a subset of data ... this I would create a tool to simply pull down some production data, or generate fake data where security is concerned. For team development, each change to the database will have to be coordinated amongst your team members. Schema and data changes can be intermingled, but a single script should enable a given feature. Once all your features are ready, you bundle these up in a single SQL file and run that against a restore of production. Once your staging has cleared acceptance, you run the single SQL file again on the production machine. I have used the Red Gate tools and they are great tools, but if you can't afford it, building the tools and working this way isn't too far from the ideal. "} {"user":"200","questionId":1387,"creationDate":"2008-08-04T17:41:01Z","answerId":1447,"type":"answer","body":"@Larsenal If you want to branch outside of .NET there has been a lot of discussion about Intel's Threading Building Blocks which is a parallel library for C++. "} {"user":"106","tags":["sql","permissions"],"questionId":1451,"creationDate":"2008-08-04T17:46:28Z","title":"What is the best way to handle multiple permission types?","acceptedAnswerId":1477,"type":"question","body":"I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000. Scenario I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specific person access to an application. And pretend that we have a number of applications that keeps growing. In the past, I have chosen one of the following two ways that I know to do this. 1) Use a single permission table with special columns that are used for determining a how to apply the parameters. The special columns in this example are TypeID and TypeAuxID. The SQL would look something like this. SELECT COUNT(PermissionID) FROM application_permissions WHERE (TypeID = 1 AND TypeAuxID = @UserID) OR (TypeID = 2 AND TypeAuxID = @DepartmentID) AND ApplicationID = 1 2) Use a mapping table for each type of permission, then joining them all together. SELECT COUNT(perm.PermissionID) FROM application_permissions perm LEFT JOIN application_UserPermissions emp ON perm.ApplicationID = emp.ApplicationID LEFT JOIN application_DepartmentPermissions dept ON perm.ApplicationID = dept.ApplicationID WHERE q.SectionID=@SectionID AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR (emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1 ORDER BY q.QID ASC My Thoughts I hope that the examples make sense. I cobbled them together. The first example requires less work, but neither of them feel like the best answer. Is there a better way to handle this? "} {"user":"58","tags":["php","parameters","error-handling"],"questionId":1453,"creationDate":"2008-08-04T17:51:13Z","title":"Using object property as default for method property","acceptedAnswerId":1456,"type":"question","body":"I'm trying to do this (which produces an unexpected T_VARIABLE error): public function createShipment($startZip, $endZip, $weight = $this->getDefaultWeight()){} I don't want to put a magic number in there for weight, since the object I am using has a \"defaultWeight\" parameter that all new shipments get if you don't specify a weight. I can't put the defaultWeight in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following? public function createShipment($startZip, $endZip, weight = 0){ if($weight <= 0){ $weight = $this->getDefaultWeight(); } } "} {"user":"292","questionId":1104,"creationDate":"2008-08-04T17:51:33Z","answerId":1454,"type":"answer","body":"Outside the scope of your question so I debated not posting this but in Java there are actually 2 types of exceptions, checked and unchecked. The basic difference is that, much like in c[++], you dont have to catch an unchecked exception. For a good reference try this "} {"user":"40","questionId":1453,"creationDate":"2008-08-04T17:53:00Z","answerId":1456,"type":"answer","body":"This isn't much better: public function createShipment($startZip, $endZip, $weight=null){ $weight = !$weight ? $this->getDefaultWeight() : $weight; } // or... public function createShipment($startZip, $endZip, $weight=null){ if ( !$weight ) $weight = $this->getDefaultWeight(); } "} {"user":"331","tags":["ajax","url","rest","address-bar"],"questionId":1457,"creationDate":"2008-08-04T17:53:32Z","title":"Modify Address Bar URL in AJAX App to Match Current State","acceptedAnswerId":1468,"type":"question","body":"I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state. How are people handling maintaining RESTfulness in AJAX apps? "} {"user":"200","questionId":1451,"creationDate":"2008-08-04T17:56:26Z","answerId":1459,"type":"answer","body":"The way I typically go about coding permission systems is having 6 tables. Users - this is pretty straight forward it is your typical users table Groups - this would be synonymous to your departments Roles - this is a table with all permissions generally also including a human readable name and a description Users_have_Groups - this is a many-to-many table of what groups a user belongs to Users_have_Roles - another many-to-many table of what roles are assigned to an individual user Groups_have_Roles - the final many-to-many table of what roles each group has At the beginning of a users session you would run some logic that pulls out every role they have assigned, either directory or through a group. Then you code against those roles as your security permissions. Like I said this is what I typically do but your millage may vary. "} {"user":"304","questionId":898,"creationDate":"2008-08-04T17:58:02Z","answerId":1462,"type":"answer","body":"It has been a while, so this is not comprehensive. Character Sets Unicode is great, but you can't get away with ignoring other character sets. The default character set on Windows XP (English) is Cp1252. On the web, you don't know what a browser will send you (though hopefully your container will handle most of this). And don't be surprised when there are bugs in whatever implementation you are using. Character sets can have interesting interactions with filenames when they move to between machines. Translating Strings Translators are, generally speaking, not coders. If you send a source file to a translator, they will break it. Strings should be extracted to resource files (e.g. properties files in Java or resource DLLs in Visual C++). Translators should be given files that are difficult to break and tools that don't let them break them. Translators do not know where strings come from in a product. It is difficult to translate a string without context. If you do not provide guidance, the quality of the translation will suffer. While on the subject of context, you may see the same string \"foo\" crop up in multiple times and think it would be more efficient to have all instances in the UI point to the same resource. This is a bad idea. Words may be very context-sensitive in some languages. Translating strings costs money. If you release a new version of a product, it makes sense to recover the old versions. Have tools to recover strings from your old resource files. String concatenation and manual manipulation of strings should be minimized. Use the format functions where applicable. Translators need to be able to modify hotkeys. Ctrl+P is print in English; the Germans use Ctrl+D. If you have a translation process that requires someone to manually cut and paste strings at any time, you are asking for trouble. Dates, Times, Calendars, Currency, Number Formats, Time Zones These can all vary from country to country. A comma may be used to denote decimal places. Times may be in 24hour notation. Not everyone uses the Gregorian calendar. You need to be unambiguous, too. If you take care to display dates as MM/DD/YYYY for the USA and DD/MM/YYYY for the UK on your website, the dates are ambiguous unless the user knows you've done it. Especially Currency The Locale functions provided in the class libraries will give you the local currency symbol, but you can't just stick a pound (sterling) or euro symbol in front of a value that gives a price in dollars. User Interfaces Layout should be dynamic. Not only are strings likely to double in length on translation, the entire UI may need to be inverted (Hebrew; Arabic) so that the controls run from right to left. And that is before we get to Asia. Testing Prior To Translation Use static analysis of your code to locate problems. At a bare minimum, leverage the tools built into your IDE. (Eclipse users can go to Window > Preferences > Java > Compiler > Errors/Warnings and check for non-externalised strings.) Smoke test by simulating translation. It isn't difficult to parse a resource file and replace strings with a pseudo-translated version that doubles the length and inserts funky characters. You don't have to speak a language to use a foreign operating system. Modern systems should let you log in as a foreign user with translated strings and foreign locale. If you are familiar with your OS, you can figure out what does what without knowing a single word of the language. Keyboard maps and character set references are very useful. Virtualisation would be very useful here. Non-technical Issues Sometimes you have to be sensitive to cultural differences (offence or incomprehension may result). A mistake you often see is the use of flags as a visual cue choosing a website language or geography. Unless you want your software to declare sides in global politics, this is a bad idea. If you were French and offered the option for English with St. George's flag (the flag of England is a red cross on a white field), this might result in confusion for many English speakers - assume similar issues will arise with foreign languages and countries. Icons need to be vetted for cultural relevance. What does a thumbs-up or a green tick mean? Language should be relatively neutral - addressing users in a particular manner may be acceptable in one region, but considered rude in another. Resources C++ and Java programmers may find the ICU website useful: http://www.icu-project.org/ "} {"user":"26","questionId":580,"creationDate":"2008-08-04T18:00:50Z","answerId":1464,"type":"answer","body":"Like Rob Allen, I use SQL Compare / Data Compare by Redgate. I also use the Database publishing wizard by Microsoft. I also have a console app I wrote in C# that takes a sql script and runs it on a server. This way you can run large scripts with 'GO' commands in it from a command line or in a batch script. I use Microsoft.SqlServer.BatchParser.dll and Microsoft.SqlServer.ConnectionInfo.dll libraries in the console application. "} {"user":"333","questionId":1457,"creationDate":"2008-08-04T18:02:03Z","answerId":1465,"type":"answer","body":"This is similar to what Kevin said. You can have your client state as some javascript object, and when you want to save the state, you serialize the object (using JSON and base64 encoding). You can then set the fragment of the href to this string. var encodedState = base64(json(state)); var newLocation = oldLocationWithoutFragment + \"#\" + encodedState; document.location = newLocation; // adds new entry in browser history document.location.replace(newLocation); // replaces current entry in browser history The first way will treat the new state as a new location (so the back button will take them to the previous location). The latter does not. "} {"user":"192","questionId":1451,"creationDate":"2008-08-04T18:03:57Z","answerId":1466,"type":"answer","body":"An approach I've used in various applications is to have a generic PermissionToken class which has a changeable Value property. Then you query the requested application, it tells you which PermissionTokens are needed in order to use it. For example, the Shipping application might tell you it needs: new PermissionToken() { Target = PermissionTokenTarget.Application, Action = PermissionTokenAction.View, Value = \"ShippingApp\" }; This can obviously be extended to Create, Edit, Delete etc and, because of the custom Value property, any application, module or widget can define its own required permissions. YMMV, but this has always been an efficient method for me which I have found to scale well. "} {"user":"60","questionId":1457,"creationDate":"2008-08-04T18:04:48Z","answerId":1468,"type":"answer","body":"The way to do this is to manipulate location.hash when AJAX updates result in a state change that you'd like to have a discreet URL. For example, if your page's url is: http://example.com/ If a client side function executed this code: // AJAX code to display the \"foo\" state goes here. location.hash = 'foo'; Then, the URL displayed in the browser would be updated to: http://example.com/#foo This allows users to bookmark the \"foo\" state of the page, and use the browser history to navigate between states. With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server. Ben Alman's hashchange plugin makes the latter a breeze if you're using jQuery. "} {"user":"198","questionId":1104,"creationDate":"2008-08-04T18:14:20Z","answerId":1474,"type":"answer","body":" Is there a way one can ensure that the exceptions thrown are always caught using try/catch by the calling function? I find it rather funny, that the Java crowd - including myself - is trying to avoid checked Exceptions. They are trying to work their way around being forced to catch Exceptions by using RuntimeExceptions. "} {"user":"92","tags":["python","syntax","binary","integer","literals"],"questionId":1476,"creationDate":"2008-08-04T18:20:36Z","title":"How do you express binary literals in Python?","acceptedAnswerId":13107,"type":"question","body":"How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF 4783 >>> 0x100 256 and octal: >>> 01267 695 >>> 0100 64 How do you use literals to express binary in Python? Summary of Answers Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal. Python 2.5 and earlier: there is no way to express binary literals. Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111. Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal. Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals. "} {"user":"296","questionId":1451,"creationDate":"2008-08-04T18:23:40Z","answerId":1477,"type":"answer","body":"I agree with John Downey. Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items. \"[Flags] public enum Permission { VIEWUSERS = 1, // 2^0 // 0000 0001 EDITUSERS = 2, // 2^1 // 0000 0010 VIEWPRODUCTS = 4, // 2^2 // 0000 0100 EDITPRODUCTS = 8, // 2^3 // 0000 1000 VIEWCLIENTS = 16, // 2^4 // 0001 0000 EDITCLIENTS = 32, // 2^5 // 0010 0000 DELETECLIENTS = 64, // 2^6 // 0100 0000 }\" Then, you can combine several permissions using the AND bitwise operator. For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3. You can then store the permission of one user into a single column of your DataBase (in our case it would be 3). Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not. "} {"user":"305","questionId":1476,"creationDate":"2008-08-04T18:26:13Z","answerId":1478,"type":"answer","body":"As far as I can tell Python, up through 2.5, only supports hexadecimal & octal literals. I did find some discussions about adding binary to future versions but nothing definite. "} {"user":"269","questionId":1476,"creationDate":"2008-08-04T18:27:26Z","answerId":1479,"type":"answer","body":"I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct(). EDIT: lbrandy's answer is correct in all cases. "} {"user":"2089740","questionId":1476,"creationDate":"2008-08-04T18:34:45Z","answerId":1484,"type":"answer","body":">>> print int('01010101111',2) 687 >>> print int('11111111',2) 255 Another way. "} {"user":"35","questionId":1451,"creationDate":"2008-08-04T18:39:56Z","answerId":1488,"type":"answer","body":"In addition to John Downey and jdecuyper's solutions, I've also added an \"Explicit Deny\" bit at the end/beginning of the bitfield, so that you can perform additive permissions by group, role membership, and then subtract permissions based upon explicit deny entries, much like NTFS works, permission-wise. "} {"user":"198","questionId":1276,"creationDate":"2008-08-04T18:44:15Z","answerId":1490,"type":"answer","body":"In general this is a very subtle issue and not trivial whatsoever. I encourage you to read mysqlperformanceblog.com and High Performance MySQL. I really think there is no general answer for this. I'm working on a project which has a MySQL database with almost 1TB of data. The most important scalability factor is RAM. If the indexes of your tables fit into memory and your queries are highly optimized, you can serve a reasonable amount of requests with a average machine. The number of records do matter, depending of how your tables look like. It's a difference to have a lot of varchar fields or only a couple of ints or longs. The physical size of the database matters as well: think of backups, for instance. Depending on your engine, your physical db files on grow, but don't shrink, for instance with innodb. So deleting a lot of rows, doesn't help to shrink your physical files. There's a lot to this issues and as in a lot of cases the devil is in the details. "} {"user":"269","questionId":761,"creationDate":"2008-08-04T18:50:34Z","answerId":1495,"type":"answer","body":"I have to agree with the OP 'wrong' dates really jar with my DD/MM/YYYY upbringing and I find ISO 8601 dates and times extremely easy to work with. For once the standard got it right and engtech has the obvious answer that doesn't require localisation. I was going to report the birthday input form on stack overflow as a bug because of how much of a sore thumb it is to the majority of the world. "} {"user":"136","tags":["osx","vim","emacs","editor"],"questionId":1496,"creationDate":"2008-08-04T18:51:38Z","title":"What are the preferred versions of Vim and Emacs on Mac OS X?","acceptedAnswerId":1517,"type":"question","body":"For those of us that like to use the graphical version of Vim or Emacs, instead of the console version, which version do you recommend? For Vim, there's Mac OS X Vim, MacVim, Vim-Cocoa. For Emacs, CarbonEmacs, XEmacs, and Aquamacs. Are there more? Which of these are ready for prime-time? If it's a tough call, what are the trade-offs? Are all of these still being maintained? No discussion of Vim vs. Emacs, if you don't mind, or comparisons with other editors. "} {"user":"27","tags":["visual-studio","unit-testing","continuous-integration","cruisecontrol.net"],"questionId":1503,"creationDate":"2008-08-04T19:01:14Z","title":"Integrating Visual Studio Test Project with Cruise Control","acceptedAnswerId":1514,"type":"question","body":"I'm looking into using Visual Studio 2008's built in unit test projects instead of NUnit and I was wondering if anyone has any experience in trying to integrate this type of unit test project with Cruise Control.Net. "} {"user":"59","questionId":1276,"creationDate":"2008-08-04T19:01:23Z","answerId":1504,"type":"answer","body":"Also watch out for complex joins. Transaction complexity can be a big factor in addition to transaction volume. Refactoring heavy queries sometimes offers a big performance boost. "} {"user":"83","tags":["iphone","html","favicon","apple-touch-icon"],"questionId":1505,"creationDate":"2008-08-04T19:02:36Z","title":"How do I give my web sites an icon for iPhone?","acceptedAnswerId":3507075,"type":"question","body":"How do I set the icon that appears on the iPhone for the web sites I create? "} {"user":"83","questionId":1505,"creationDate":"2008-08-04T19:04:03Z","answerId":1506,"type":"answer","body":"From the Apple Developer Connection Safari Web Content Guide for iPhone page Specifying a Webpage Icon for Web Clip... The user can add a web application or webpage link to the Home screen. These links, represented by an icon, are called web clips. Follow these simple steps to specify an icon to represent your web application or webpage on iPhone. To specify an icon for the entire website (every page on the website), place an icon file in PNG format in the root document folder called apple-touch-icon.png. To specify an icon for a single webpage, or replace the website icon with a webpage-specific icon, add a link element to the webpage as in: In the above example, replace custom_icon.png with your icon filename. See \"Create an Icon for Your Web Application or Webpage\" in iPhone Human Interface Guidelines in iPhone Human Interface Guidelines for webpage icon metrics. Note: The web clip feature is available in iPhone 1.1.3 and later. "} {"user":"149","tags":["version-control","dvcs"],"questionId":1508,"creationDate":"2008-08-04T19:04:47Z","title":"Different Distributed Version Control Systems working together","acceptedAnswerId":1525,"type":"question","body":"My office has a central Source Safe 2005 install that we use for source control. I can't change what the office uses on the server. I develop on a laptop and would like to have a different local source control repository that can sync with the central server (when available) regardless of the what that central provider is. The reason for the request is so I can maintain a local stable branch/build for client presentations while continuing to develop without having to jump through flaming hoops. Also, as a consultant, my clients may request that I use their source control provider and flexibility here would make life easier. Can any of the existing distributed source control clients handle that? "} {"user":"91","questionId":1505,"creationDate":"2008-08-04T19:06:12Z","answerId":1509,"type":"answer","body":"And for the sake of completeness, a link to Scott Hanselman's posting, which contains some additional tips as well: Add Home Screen iPhone Icons and Adjust the ViewPort "} {"user":"27","questionId":1503,"creationDate":"2008-08-04T19:09:44Z","answerId":1514,"type":"answer","body":"From some of the initial research it doesn't appear to be a super simple solution. It appears that doing this involves having Visual Studio 2008 actually installed on the continuous integration server, which could be a deal breaker. Then configure the MSTest.exe to run in the tasks list, but first you'll have to make a batch file to delete the results files from previous passes as this file's existence causes an error. Then create a xslt to format the results and put it into the dashboard.config file. The code project article I found has a lot more detail. Integrating Visual Studio Team System 2008 Unit Tests with CruiseControl.NET "} {"user":"2089740","questionId":1508,"creationDate":"2008-08-04T19:10:29Z","answerId":1515,"type":"answer","body":"You should be able to check out the current version of the code and then create a git repository around it. Updating that and committing it to your local git repository should be painless. As should cloning it. The only catch is that you need to have them both ignore each other (I've done something similar with SVN) by messing with the appropriate ignore files. I'm presuming SourceSafe let's you ignore things. And you'll need to do certain operations twice (like telling both that you are deleting a file). "} {"user":"199","questionId":1496,"creationDate":"2008-08-04T19:11:02Z","answerId":1517,"type":"answer","body":"MacVim works well and certainly looks more mature than Vim-Cocoa, moreover there is a Cocoa plugin architecture in the pipeline for MacVim (and someone is already working on a TextMate style file browser tray plugin which is a huge ++ IMHO). There was also a Carbon version of Vim, but this didn't offer a great deal over the Terminal version. i.e. only allowed one window open, not very OSX in appearance... Aquamacs is very usable and looks pretty good. Supports both traditional Mac OS style keyboard shortcuts (command-O, command-S) and the Control/Meta shortcuts for those raised on traditional Emacs. It is definitely more Mac-like than Carbon Emacs. It seems stable and fast, but I am not an Emacs guru so I don't stress it all that much when I use it. I can't speak to the extensiveness of the included elisp packages, either. Someone syncs Carbon Emacs with the upstream tree quarterly I think. Aquamacs has a more irregular schedule, but it's seen some pretty major updates over the last year. GNU Emacs for OSX can be found at emacsformacosx.com. In addition to the latest stable release, there are also pre-release test builds and nightly builds, and Atom feeds are provided for tracking all three release types. "} {"user":"83","questionId":1505,"creationDate":"2008-08-04T19:13:02Z","answerId":1522,"type":"answer","body":"I've made a suggestion that Stack Overflow implement an apple-touch-icon: Add an apple-touch-icon for Safari on iPhone "} {"user":"304","questionId":761,"creationDate":"2008-08-04T19:13:17Z","answerId":1524,"type":"answer","body":"A short form is convenient and helps avoid spelling mistakes. Localize as applicable, but be sure to display the expected format (do not leave the user blind). Provide a date-picker control as an optional aide to filling in the field. As an extra, on-the-fly parsing and display of the date in long form might help too. "} {"user":"59","questionId":1508,"creationDate":"2008-08-04T19:13:23Z","answerId":1525,"type":"answer","body":"Well... KernelTrap has something on this. Looks like you can use vss2svn to pipe the Source Safe repo into a Subversion repository, then use the very nice git-svn to pull into a local git repo. I would assume the commits back to VSS would not be a smooth, automatic process using this method. "} {"user":"149","questionId":1401,"creationDate":"2008-08-04T19:13:46Z","answerId":1527,"type":"answer","body":"While I would still like an answer to why my javascript wasn't being recognized, the solution I found in the meantime (and should have done in the first place) is to use an Asp:CompareValidator instead of an Asp:CustomValidator. "} {"user":"93","tags":["c#","wpf","silverlight","polymorphism","dependency-properties"],"questionId":1528,"creationDate":"2008-08-04T19:13:54Z","title":"Hiding inherited members","acceptedAnswerId":1556,"type":"question","body":"I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using IntelliSense or using the classes in a visual designer. These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about ICustomTypeDescriptor and ICustomPropertyProvider, but I'm pretty certain those can't be used in Silverlight. It's not as much a functional issue as a usability issue. What should I do? Update Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the new operator. (I know, it's ridiculous) "} {"user":"91","questionId":1528,"creationDate":"2008-08-04T19:19:33Z","answerId":1533,"type":"answer","body":"While you cannot prevent usage of those inherited members to my knowledge, you should be able to hide them from IntelliSense using the EditorBrowsableAttribute: Using System.ComponentModel; [EditorBrowsable(EditorBrowsableState.Never)] private string MyHiddenString = \"Muahahahahahahahaha\"; Edit: Just saw this in the documentation comments, which makes it kinda useless for this purpose: There is a prominent note that states that this attribute \"does not suppress members from a class in the same assembly\". That is true but not complete. Actually, the attribute does not suppress members from a class in the same solution. "} {"user":"34","questionId":1528,"creationDate":"2008-08-04T19:19:34Z","answerId":1534,"type":"answer","body":"I think you're best least hackish way is to consider composition as opposed to inheritance. Or, you could create an interface that has the members you want, have your derived class implement that interface, and program against the interface. "} {"user":"332","tags":["c#","exception","error-handling"],"questionId":1535,"creationDate":"2008-08-04T19:21:48Z","title":"Reducing duplicate error handling code in C#?","acceptedAnswerId":2047,"type":"question","body":"I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process. Anyway, here's the problem: Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc. The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic. Here's an example code snippet: RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { // do some file IO which may succeed or fail success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw e; } fileIORetryTimer.SleepUntilNextRetry(); } } So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods: this.RetryFileIO( delegate() { // some code block } ); I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem. "} {"user":"122","questionId":1528,"creationDate":"2008-08-04T19:22:48Z","answerId":1536,"type":"answer","body":"One potential thing you can do is contain the object rather than extend from the other class. This will give you the most flexibility in terms of exposing what you want to expose, but if you absolutely need the object to be of that type it is not the ideal solution (however you could expose the object from a getter). Thus: public class MyClass : BaseClass { // Your stuff here } Becomes: public class MyClass { private BaseClass baseClass; public void ExposeThisMethod() { baseClass.ExposeThisMethod(); } } Or: public class MyClass { private BaseClass baseClass; public BaseClass BaseClass { get { return baseClass; } } } "} {"user":"224","questionId":1041,"creationDate":"2008-08-04T19:44:24Z","answerId":1546,"type":"answer","body":"If you use Visual Studio you can use Visual C++ 2008 Feature Pack Release, this implements some of TR1, and includes regular expression parsing. Get it "} {"user":"313","questionId":650,"creationDate":"2008-08-04T19:51:49Z","answerId":1550,"type":"answer","body":"Some time ago I wrote a quick and dirty exe that would update the version #'s in an assemblyinfo.{cs/vb} - I also have used rxfind.exe (a simple and powerful regex-based search replace tool) to do the update from a command line as part of the build process. A couple of other helpfule hints: separate the assemblyinfo into product parts (company name, version, etc.) and assembly specific parts (assembly name etc.). See here Also - i use subversion, so I found it helpful to set the build number to subversion revision number thereby making it really easy to always get back to the codebase that generated the assembly (e.g. was built from revision 1502). "} {"user":"96","questionId":1535,"creationDate":"2008-08-04T20:07:41Z","answerId":1554,"type":"answer","body":"Just wondering, what do you feel your method leaves to be desired? You could replace the anonymous delegate with a.. named? delegate, something like public delegate void IoOperation(params string[] parameters); public void FileDeleteOperation(params string[] fileName) { File.Delete(fileName[0]); } public void FileCopyOperation(params string[] fileNames) { File.Copy(fileNames[0], fileNames[1]); } public void RetryFileIO(IoOperation operation, params string[] parameters) { RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { operation(parameters); success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw; } fileIORetryTimer.SleepUntilNextRetry(); } } } public void Foo() { this.RetryFileIO(FileDeleteOperation, \"L:\\file.to.delete\" ); this.RetryFileIO(FileCopyOperation, \"L:\\file.to.copy.source\", \"L:\\file.to.copy.destination\" ); } "} {"user":"313","questionId":1528,"creationDate":"2008-08-04T20:14:30Z","answerId":1556,"type":"answer","body":"Override them like Michael Suggests above and to prevent folks from using the overridden (sp?) methods, mark them as obsolete: [Obsolete(\"These are not supported in this class.\", true)] public override void dontcallmeanymore() { } If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated. "} {"user":"153","questionId":1496,"creationDate":"2008-08-04T20:22:32Z","answerId":1561,"type":"answer","body":"I've tried Aquamacs and it's very usable and looks pretty good. Supports both traditional Mac OS style keyboard shortcuts (command-O, command-S) and the Control/Meta shortcuts for those raised on traditional Emacs. It is definitely more Mac-like than Carbon Emacs. It seems stable and fast, but I am not an Emacs guru so I don't stress it all that much when I use it. I can't speak to the extensiveness of the included elisp packages, either. Someone syncs Carbon Emacs with the upstream tree quarterly I think. Aquamacs has a more irregular schedule, but it's seen some pretty major updates over the last year. "} {"user":"332","questionId":564,"creationDate":"2008-08-04T21:02:54Z","answerId":1582,"type":"answer","body":"This has already been answered for Java, here's the C# answer: \"Integer\" is not a valid type name in C# and \"int\" is just an alias for System.Int32. Also, unlike in Java (or C++) there aren't any special primitive types in C#, every instance of a type in C# (including int) is an object. Here's some demonstrative code: void DoStuff() { System.Console.WriteLine( SomeMethod((int)5) ); System.Console.WriteLine( GetTypeName() ); } string SomeMethod(object someParameter) { return string.Format(\"Some text {0}\", someParameter.ToString()); } string GetTypeName() { return (typeof (T)).FullName; } "} {"user":"40","tags":["windows","iis","shell","command-line","terminal"],"questionId":1584,"creationDate":"2008-08-04T21:04:06Z","title":"Linux shell equivalent on IIS","acceptedAnswerId":44389,"type":"question","body":"As a LAMP developer considering moving to a .Net IIS platform, one of my concerns is the loss of productivity due to lack of shell... Has anyone else had this experience? Is there possibly a Linux shell equivalent for Windows? "} {"user":"2089740","questionId":1584,"creationDate":"2008-08-04T21:06:14Z","answerId":1585,"type":"answer","body":"I assume you don't mean cygwin, right? How about powershell, then? "} {"user":"341","questionId":888,"creationDate":"2008-08-04T21:07:09Z","answerId":1587,"type":"answer","body":"Xdebug, by Derick Rethans, is very good. I used it some time ago and found it was not so easy to install. Once you're done, you won't understand how you managed without it :-) There is a good article on Zend Developer Zone (installing on Linux doesn't seem any easier) and even a Firefox plugin, which I never used. "} {"user":"71","questionId":1584,"creationDate":"2008-08-04T21:08:24Z","answerId":1588,"type":"answer","body":"Are you asking about Linux shell as in an environment to work in? For that CygWin I think has been around the longest and is pretty robust: http://www.cygwin.com/ A while ago I found a windows port of all the popular linux commands I use (ls, grep, diff) and I simply unzip those to a file, add it to my PATH environment and then can run from there: http://unxutils.sourceforge.net/ Or are you talking about executing shell commands from within your code? If you're in the .net sphere, there is the Process.Start() method that will give you a lot of options. Hope this helps! "} {"user":"271","questionId":1584,"creationDate":"2008-08-04T21:14:10Z","answerId":1594,"type":"answer","body":"If you're referring to simply accessing your IIS server from a remote location, remote desktop generally solves that problem. Assuming your server has a static IP address or a host name you can access from the internet, remote desktop is a simple and relatively secure solution. Is there a problem with this answer? Now I have negative reputation... "} {"user":"102","questionId":746,"creationDate":"2008-08-04T21:16:22Z","answerId":1595,"type":"answer","body":" To capatilise it in, say, C - use the ascii codes (http://www.asciitable.com/) to find the integer value of the char and subtract 32 from it. This is a poor solution if you ever plan to accept characters beyond a-z and A-Z. For instance: ASCII 134: å, ASCII 143: Å. Using arithmetic gets you: ASCII 102: f Use library calls, don't assume you can use integer arithmetic on your characters to get back something useful. Unicode is tricky. "} {"user":"83","tags":["iphone","favicon","apple-touch-icon"],"questionId":1598,"creationDate":"2008-08-04T21:17:51Z","title":"What are the correct pixel dimensions for an apple-touch-icon?","acceptedAnswerId":3490980,"type":"question","body":"I'm not sure what the correct size should be. Many sites seem to repeat that the apple-touch-icon should be 57x57 pixels but cite a broken link as their source. Hanselman's and playgroundblues's comments suggest different sizes including 163x163 and 60x60. Apple's own apple.com icon is 129x129! See my related question: How do I give my web sites an icon for iPhone? "} {"user":"67","questionId":1598,"creationDate":"2008-08-04T21:22:50Z","answerId":1599,"type":"answer","body":"I don't think there is a \"correct size\". Since the iPhone really is running OSX, the icon rendering system is pretty robust. As long as you give it a high-quality image with the right aspect ratio and a resolution at least as high as the actual output will be, the OS will downscale very cleanly. My site uses a 158x158 and the icon looks pixel-perfect on the iPhone screen. "} {"user":"230","tags":["sql-server","sql-server-2008"],"questionId":1600,"creationDate":"2008-08-04T21:27:53Z","title":"What is the best way to copy a database?","acceptedAnswerId":1793,"type":"question","body":"I always create a new empty database, after that backup and restore of the existing database into it, but is this really the best way? As it seems very error prone and over complicated for me. "} {"user":"1384652","questionId":888,"creationDate":"2008-08-04T21:28:44Z","answerId":1602,"type":"answer","body":"In all honesty, a combination of print and print_r() to print out the variables. I know that many prefer to use other more advanced methods but I find this the easiest to use. I will say that I didn't fully appreciate this until I did some Microprocessor programming at Uni and was not able to use even this. "} {"user":"72","tags":["php","mysql","database","svn","migration"],"questionId":1607,"creationDate":"2008-08-04T21:31:40Z","title":"Mechanisms for tracking DB schema changes","acceptedAnswerId":1666,"type":"question","body":"What are the best methods for tracking and/or automating DB schema changes? Our team uses Subversion for version control and we've been able to automate some of our tasks this way (pushing builds up to a staging server, deploying tested code to a production server) but we're still doing database updates manually. I would like to find or create a solution that allows us to work efficiently across servers with different environments while continuing to use Subversion as a backend through which code and DB updates are pushed around to various servers. Many popular software packages include auto-update scripts which detect DB version and apply the necessary changes. Is this the best way to do this even on a larger scale (across multiple projects and sometimes multiple environments and languages)? If so, is there any existing code out there that simplifies the process or is it best just to roll our own solution? Has anyone implemented something similar before and integrated it into Subversion post-commit hooks, or is this a bad idea? While a solution that supports multiple platforms would be preferable, we definitely need to support the Linux/Apache/MySQL/PHP stack as the majority of our work is on that platform. "} {"user":"52","questionId":1584,"creationDate":"2008-08-04T21:33:58Z","answerId":1608,"type":"answer","body":"The best way I can think of would be to use Cygwin over an OpenSSH connection. Here's a document that explains how to do just that: http://www.ucl.ac.uk/cert/openssh_rdp_vnc.pdf "} {"user":"52","questionId":1598,"creationDate":"2008-08-04T21:36:58Z","answerId":1609,"type":"answer","body":"Depends on how much detail you want it to have, it needs to have the aspect ratio of 1:1 (basically - it needs to be square) I would go with the Apple's own 129*129 "} {"user":"328","tags":["sql-server"],"questionId":1610,"creationDate":"2008-08-04T21:37:31Z","title":"Can I logically reorder columns in a table?","acceptedAnswerId":1621,"type":"question","body":"If I'm adding a column to a table in Microsoft SQL Server, can I control where the column is displayed logically in queries? I don't want to mess with the physical layout of columns on disk, but I would like to logically group columns together when possible so that tools like SQL Server Management Studio list the contents of the table in a convenient way. I know that I can do this through SQL Management Studio by going into their \"design\" mode for tables and dragging the order of columns around, but I'd like to be able to do it in raw SQL so that I can perform the ordering scripted from the command line. "} {"user":"1384652","questionId":328,"creationDate":"2008-08-04T21:38:05Z","answerId":1611,"type":"answer","body":"I would check both IP and User Agent to see if they change if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT'] || $_SESSION['user_ip'] != $_SERVER['REMOTE_ADDR']) { //Something fishy is going on here? } "} {"user":"25","tags":["ruby","language-agnostic","xfdl"],"questionId":1615,"creationDate":"2008-08-04T21:42:37Z","title":"How can I modify .xfdl files? (Update #1)","acceptedAnswerId":1628,"type":"question","body":"The .XFDL file extension identifies XFDL Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications. I know how to view XFDL files using a file viewer I found here. I can also modify and save these files by doing File:Save/Save As. I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible? Update #1: I have now successfully decoded and unziped a .xfdl into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line) "} {"user":"173","questionId":1600,"creationDate":"2008-08-04T21:46:01Z","answerId":1617,"type":"answer","body":"It is possible to skip the step of creating the empty database. You can create the new database as part of the restore process. This is actually the easiest and best way I know of to clone a database. You can eliminate errors by scripting the backup and restore process rather than running it through the SQL Server Management Studio There are two other options you could explore: Detach the database, copy the .mdf file and re-attach. Use SQL Server Integration Services (SSIS) to copy all the objects over I suggest sticking with backup and restore and automating if necessary. "} {"user":"92","questionId":766,"creationDate":"2008-08-04T21:54:11Z","answerId":1619,"type":"answer","body":"MySQLdb is what I have used before. If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it. Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed. "} {"user":"318","questionId":833,"creationDate":"2008-08-04T21:54:15Z","answerId":1620,"type":"answer","body":"@ Mark Harrison : SQL Server does not support that syntax (SELECT ... FOR UPDATE). The SQL Server equivalent is the SELECT statement hint UPDLOCK. See SQL Server Books Online for more information. "} {"user":"224","questionId":1610,"creationDate":"2008-08-04T21:54:18Z","answerId":1621,"type":"answer","body":"You can not do this programatically (in a safe way that is) without creating a new table. What Enterprise Manager does when you commit a reordering is to create a new table, move the data and then delete the old table and rename the new table to the existing name. If you want your columns in a particular order/grouping without altering their physical order, you can create a view which can be whatever you desire. "} {"user":"230","tags":["visual-studio","design","projects-and-solutions"],"questionId":1623,"creationDate":"2008-08-04T22:00:41Z","title":"Folders or Projects in a Visual Studio Solution?","acceptedAnswerId":1667,"type":"question","body":"When spliting a solution in to logical layers, when is it best to use a separate project over just grouping by a folder? "} {"user":"192","questionId":1610,"creationDate":"2008-08-04T22:00:53Z","answerId":1624,"type":"answer","body":"When Management Studio does it, it's creating a temporary table, copying everything across, dropping your original table and renaming the temporary table. There's no simple equivalent T-SQL statement. If you don't fancy doing that, you could always create a view of the table with the columns in the order you'd like and use that? Edit: beaten! "} {"user":"204","tags":["windows","xml","linux"],"questionId":1625,"creationDate":"2008-08-04T22:01:10Z","title":"XML Editing/Viewing Software","acceptedAnswerId":1627,"type":"question","body":"What software is recommended for working with and editing large XML schemas? I'm looking for both Windows and Linux software (doesn't have to be cross platform, just want suggestions for both) that help with dealing with huge XML files. "} {"user":"92","questionId":1625,"creationDate":"2008-08-04T22:01:59Z","answerId":1627,"type":"answer","body":"I may be old fashioned, but I prefer my text editor. I use emacs, and it has a fairly decent xml mode. Most good text editors will have decent syntax hi-lighting and tag matching facilities. Your IDE might already do it (IntelliJ idea does, and I believe Eclipse does as well). Good text editors will be able to deal with huge files, but some text editors may not be able to handle them. How big are we talking about? "} {"user":"52","questionId":1615,"creationDate":"2008-08-04T22:02:35Z","answerId":1628,"type":"answer","body":"If the encoding is base64 then this is the solution I've stumbled upon on the web link : \"Decoding XDFL files saved with 'encoding=base64'. Files saved with: application/vnd.xfdl;content-encoding=\"base64-gzip\" are simple base64-encoded gzip files. They can be easily restored to XML by first decoding and then unzipping them. This can be done as follows on Ubuntu: sudo apt-get install uudeview uudeview -i yourform.xfdl gunzip -S \"\" < UNKNOWN.001 > yourform-unpacked.xfdl The first command will install uudeview, a package that can decode base64, among others. You can skip this step once it is installed. Assuming your form is saved as 'yourform.xfdl', the uudeview command will decode the contents as 'UNKNOWN.001', since the xfdl file doesn't contain a file name. The '-i' option makes uudeview uninteractive, remove that option for more control. The last command gunzips the decoded file into a file named 'yourform-unpacked.xfdl'. \" Another possible solution - here Side Note: Block quoted < code > doesn't work for long strings of code "} {"user":"27","questionId":1623,"creationDate":"2008-08-04T22:14:17Z","answerId":1640,"type":"answer","body":"I usually do a project for the GUI a project for the business logic a project for data access and a project for unit tests. But sometimes it is prudent to have separation based upon services (if you are using a service oriented architecture) Such as Authentication, Sales, etc. I guess the rule of thumb that I work off of is that if you can see it as a component that has a clear separation of concerns then a different project could be prudent. But I would think that folders versus projects could just be a preference or philosophy. I personally feel that if reusable code is split into projects it is simpler to use other places than if it is just in folders. "} {"user":"91","tags":["podcast"],"questionId":1644,"creationDate":"2008-08-04T22:17:08Z","title":"What good technology podcasts are out there?","type":"question","body":"Yes, Podcasts, those nice little Audiobooks I can listen to on the way to work. With the current amount of Podcasts, it's like searching a needle in a haystack, except that the haystack happens to be the Internet and is filled with too many of these \"Hot new Gadgets\" stuff :( Now, even though I am mainly a .NET developer nowadays, maybe anyone knows some good Podcasts from people regarding the whole software lifecycle? Unit Testing, Continous Integration, Documentation, Deployment... So - what are you guys and gals listening to? Please note that the categorizations are somewhat subjective and may not be 100% accurate as many podcasts cover several areas. Categorization is made against what is considered the \"main\" area. General Software Engineering / Productivity Stack Overflow (inactive, but still a good listen) TekPub (Requires Paid Subscription) Software Engineering Radio 43 Folders Perspectives Dr. Dobb's (now a video feed) The Pragmatic Podcast (Inactive) IT Matters Agile Toolkit Podcast The Stack Trace (Inactive) Parleys Techzing The Startup Success Podcast Berkeley CS class lectures FLOSS Weekly This Developer's Life .NET / Visual Studio / Microsoft Herding Code Hanselminutes .NET Rocks! Deep Fried Bytes Alt.Net Podcast (inactive) Polymorphic Podcast (inconsistent) Sparkling Client (The Silverlight Podcast) dnrTV! Spaghetti Code ASP.NET Podcast Channel 9 Radio TFS PowerScripting Podcast The Thirsty Developer Elegant Code (inactive) ConnectedShow Crafty Coders Coding QA jQuery yayQuery The official jQuery podcast Java / Groovy The Java Posse Grails Podcast Java Technology Insider Basement Coders Ruby / Rails Railscasts Rails Envy The Ruby on Rails Podcast Rubiverse Ruby5 Web Design / JavaScript / Ajax WebDevRadio Boagworld The Rissington podcast Ajaxian YUI Theater Unix / Linux / Mac / iPhone Mac Developer Network Hacker Public Radio Linux Outlaws Mac OS Ken LugRadio Linux radio show (Inactive) The Linux Action Show! Linux Kernel Mailing List (LKML) Summary Podcast Stanford's iPhone programming class Advanced iPhone Development Course - Madison Area Technical College WWDC 2010 Session Videos (requires Apple Developer registration) System Administration, Security or Infrastructure RunAs Radio Security Now! Crypto-Gram Security Podcast Hak5 VMWare VMTN Windows Weekly PaulDotCom Security The Register - Semi-Coherent Computing FeatherCast General Tech / Business Tekzilla This Week in Tech The Guardian Tech Weekly PCMag Radio Podcast (Inactive) Entrepreneurship Corner Manager Tools Other / Misc. / Podcast Networks IT Conversations Retrobits Podcast No Agenda Netcast Cranky Geeks The Command Line Freelance Radio IBM developerWorks The Register - Open Season Drunk and Retired Technometria Sod This Radio4Nerds Hacker Medley "} {"user":"225","questionId":1600,"creationDate":"2008-08-04T22:18:05Z","answerId":1646,"type":"answer","body":"Here's a dynamic sql script I've used in the past. It can be further modified but it will give you the basics. I prefer scripting it to avoid the mistakes you can make using the Management Studio: Declare @OldDB varchar(100) Declare @NewDB varchar(100) Declare @vchBackupPath varchar(255) Declare @query varchar(8000) /*Test code to implement Select @OldDB = 'Pubs' Select @NewDB = 'Pubs2' Select @vchBackupPath = '\\\\dbserver\\C$\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Backup\\pubs.bak' */ SET NOCOUNT ON; Select @query = 'Create Database ' + @NewDB exec(@query) Select @query = ' Declare @vBAKPath varchar(256) declare @oldMDFName varchar(100) declare @oldLDFName varchar(100) declare @newMDFPath varchar(100) declare @newLDFPath varchar(100) declare @restQuery varchar(800) select @vBAKPath = ''' + @vchBackupPath + ''' select @oldLDFName = name from ' + @OldDB +'.dbo.sysfiles where filename like ''%.ldf%'' select @oldMDFName = name from ' + @OldDB +'.dbo.sysfiles where filename like ''%.mdf%'' select @newMDFPath = physical_name from ' + @NewDB +'.sys.database_files where type_desc = ''ROWS'' select @newLDFPath = physical_name from ' + @NewDB +'.sys.database_files where type_desc = ''LOG'' select @restQuery = ''RESTORE DATABASE ' + @NewDB + ' FROM DISK = N'' + '''''''' + @vBAKpath + '''''''' + '' WITH MOVE N'' + '''''''' + @oldMDFName + '''''''' + '' TO N'' + '''''''' + @newMDFPath + '''''''' + '', MOVE N'' + '''''''' + @oldLDFName + '''''''' + '' TO N'' + '''''''' + @newLDFPath + '''''''' + '', NOUNLOAD, REPLACE, STATS = 10'' exec(@restQuery) --print @restQuery' exec(@query) "} {"user":"52","questionId":1615,"creationDate":"2008-08-04T22:18:47Z","answerId":1647,"type":"answer","body":"The only answer I can think of right now is - read the manual for uudeview. As much as I would like to help you, I am not an expert in this area, so you'll have to wait for someone more knowledgable to come down here and help you. Meanwhile I can give you links to some documents that might help you: UUDeview Home Page Using XDFLengine Gettting started with the XDFL Engine Sorry if this doesn't help you. "} {"user":"1384652","questionId":1644,"creationDate":"2008-08-04T22:21:17Z","answerId":1649,"type":"answer","body":"If you are into web design and website creation then I recommend Boagworld and also The Rissington podcast even if you are not. "} {"user":"72","questionId":1625,"creationDate":"2008-08-04T22:23:14Z","answerId":1651,"type":"answer","body":"I agree that your text editor is probably your best bet. I do know some people who swear by XMLSpy, if you need something that's tailored specifically for dealing with XML files in a visual way. I bet you could find some F/OSS work-alikse but I'm not aware of any. "} {"user":"117","questionId":1625,"creationDate":"2008-08-04T22:26:04Z","answerId":1653,"type":"answer","body":"The oXygen XML Editor a great IDE for Windows, bit expensive tho. "} {"user":"199","questionId":1644,"creationDate":"2008-08-04T22:26:29Z","answerId":1654,"type":"answer","body":"In the Stack Overflow podcast SE-radio was mentioned. It's pretty in depth. Also if you are an aspiring JavaScript developer, the Douglas Crockford \"The JavaScript Programming Language\" and \"Advanced JavaScript\" talks on YUI Developer Theatre are excellent. There are a few other gems on the podcast too. "} {"user":"52","questionId":1625,"creationDate":"2008-08-04T22:27:00Z","answerId":1655,"type":"answer","body":"Open source XML editors examined - it is a little bit outdated though. "} {"user":"122","questionId":1607,"creationDate":"2008-08-04T22:28:58Z","answerId":1656,"type":"answer","body":"It's kinda low tech, and there might be a better solution out there, but you could just store your schema in an SQL script which can be run to create the database. I think you can execute a command to generate this script, but I don't know the command unfortunately. Then, commit the script into source control along with the code that works on it. When you need to change the schema along with the code, the script can be checked in along with the code that requires the changed schema. Then, diffs on the script will indicate diffs on schema changes. With this script, you could integrate it with DBUnit or some kind of build script, so it seems it could fit in with your already automated processes. "} {"user":"207","questionId":1625,"creationDate":"2008-08-04T22:30:00Z","answerId":1657,"type":"answer","body":"I work a lot with XML, and have found Oxygen to be a great editor. It's cross-platform and has a graphical schema editor, but since I use DTDs and not schemas, I can't vouch for the schema editor's quality. The rest of the editing package (such as the XML editor and XSLT debugger) is solid, so it could be worth a try. "} {"user":"308","questionId":1644,"creationDate":"2008-08-04T22:35:52Z","answerId":1660,"type":"answer","body":"I like General Software Stackoverflow (perhaps too obvious) Deep Fried Bytes Hanselminutes Software Engineering Radio (via Brenden) Herding Code Dot Net Alt.NET Podcast Polymorphic Podcast Productivity 43 Folders "} {"user":"116","questionId":1644,"creationDate":"2008-08-04T22:36:18Z","answerId":1661,"type":"answer","body":"The Google Developer Podcast is good. "} {"user":"3","questionId":1623,"creationDate":"2008-08-04T22:42:55Z","answerId":1665,"type":"answer","body":"denny wrote: I personally feel that if reusable code is split into projects it is simpler to use other places than if it is just in folders. I really agree with this - if you can reuse it, it should be in a separate project. With that said, it's also very difficult to reuse effectively :) Here at SO, we've tried to be very simple with three projects: MVC Web project (which does a nice job of separating your layers into folders by default) Database project for source control of our DB Unit tests against MVC models/controllers I can't speak for everyone, but I'm happy with how simple we've kept it - really speeds the builds along! "} {"user":"216","questionId":1607,"creationDate":"2008-08-04T22:45:11Z","answerId":1666,"type":"answer","body":"In the Rails world, there's the concept of migrations, scripts in which changes to the database are made in Ruby rather than a database-specific flavour of SQL. Your Ruby migration code ends up being converted into the DDL specific to your current database; this makes switching database platforms very easy. For every change you make to the database, you write a new migration. Migrations typically have two methods: an \"up\" method in which the changes are applied and a \"down\" method in which the changes are undone. A single command brings the database up to date, and can also be used to bring the database to a specific version of the schema. In Rails, migrations are kept in their own directory in the project directory and get checked into version control just like any other project code. This Oracle guide to Rails migrations covers migrations quite well. Developers using other languages have looked at migrations and have implemented their own language-specific versions. I know of Ruckusing, a PHP migrations system that is modelled after Rails' migrations; it might be what you're looking for. "} {"user":"275","questionId":1623,"creationDate":"2008-08-04T22:45:32Z","answerId":1667,"type":"answer","body":"By default, always just create new folder within the same project You will get single assembly (without additional ILMerge gymnastic) Easier to obfuscate (because you will have less public types and methods, ideally none at all) Separating your source code into multiple projects makes only sense if you... Have some portions of the source code that are part of the project but not deployable by default or at all (unit tests, extra plugins etc.) More developers involved and you want to treat their work as consumable black box. (not very recommended) If you can clearly separate your project into isolated layers/modules and you want to make sure that they can't cross-consume internal members. (also not recommended because you will need to decide which aspect is the most important) If you think that some portions of your source code could be reusable, still don't create it as a new project. Just wait until you will really want to reuse it in another solution and isolate it out of original project as needed. Programming is not a lego, reusing is usually very difficult and often won't happen as planned. "} {"user":"340","tags":["compiler-construction","language-agnostic"],"questionId":1669,"creationDate":"2008-08-04T22:46:36Z","title":"Learning to write a compiler","acceptedAnswerId":1672,"type":"question","body":"Preferred languages: C/C++, Java, and Ruby. I am looking for some helpful books/tutorials on how to write your own compiler simply for educational purposes. I am most familiar with C/C++, Java, and Ruby, so I prefer resources that involve one of those three, but any good resource is acceptable. "} {"user":"230","questionId":1607,"creationDate":"2008-08-04T22:47:46Z","answerId":1670,"type":"answer","body":"If you are using C#, have a look at Subsonic, a very useful ORM tool, but is also generates sql script to recreated your scheme and\\or data. These scripts can then be put into source control. http://subsonicproject.com/ "} {"user":"91","questionId":1669,"creationDate":"2008-08-04T22:52:00Z","answerId":1672,"type":"answer","body":"Big List of Resources: A Nanopass Framework for Compiler Education ¶ Advanced Compiler Design and Implementation $ An Incremental Approach to Compiler Construction ¶ ANTLR 3.x Video Tutorial Basics of Compiler Design Building a Parrot Compiler Compiler Basics Compiler Construction $ Compiler Design and Construction $ Crafting a Compiler with C $ Compiler Design in C ¶ Dragon Book $ — Widely considered \"the book\" for compiler writing. Engineering a Compiler $ Essentials of Programming Languages Flipcode Article Archive (look for \"Implementing A Scripting Engine by Jan Niestadt\") Game Scripting Mastery $ How to build a virtual machine from scratch in C# ¶ Implementing Functional Languages Implementing Programming Languages (with BNFC) Implementing Programming Languages using C# 4.0 Interpreter pattern (described in Design Patterns $) specifies a way to evaluate sentences in a language Language Implementation Patterns: Create Your Own Domain-Specific and General Programming Languages Let's Build a Compiler — The PDF ¶ version Linkers and Loaders $ (Google Books) Lisp in Small Pieces (LiSP) $ LLVM Tutorial Modern Compiler Implementation in ML $ — There is a Java $ and C $ version as well - widely considered a very good book Object-Oriented Compiler Construction $ Parsing Techniques - A Practical Guide Project Oberon ¶ - Look at chapter 13 Programming a Personal Computer $ Programing Languages: Application and Interpretation Rabbit: A Compiler for Scheme¶ Reflections on Trusting Trust — A quick guide Roll Your Own Compiler for the .NET framework — A quick tutorial from MSDN Structure and Interpretation of Computer Programs Types and Programming Languages Want to Write a Compiler? - a quick guide Writing a Compiler in Ruby Bottom Up Legend: ¶ Link to a PDF file $ Link to a printed book "} {"user":"308","questionId":1300,"creationDate":"2008-08-04T22:52:31Z","answerId":1673,"type":"answer","body":"If you are quite happy with MSBuild, then I would stick with MSBuild. This may be one of those cases where the tool you learn first is the one you will prefer. I started with NAnt and can't quite get used to MSBuild. I'm sure they will both be around for quite some time. There are some fundamental differences between the two, probably best highlighted by this conversation between some NAnt fans and a Microsoftie. Interestingly, Jeremy Miller asked the exact opposite question on his blog last year. "} {"user":"52","questionId":1669,"creationDate":"2008-08-04T22:56:30Z","answerId":1678,"type":"answer","body":"\"Let's Build a Compiler\" is awesome, but it's a bit outdated. (I'm not saying it makes it even a little bit less valid.) Or check out SLANG. This is similar to \"Let's Build a Compiler\" but is a much better resource especially for beginners. This comes with a pdf tutorial which takes a 7 step approach at teaching you a compiler. Adding the quora link as it have the links to all the various ports of SLANG, in C++, Java and JS, also interpreters in python and java, originally written using C# and the .NET platform. "} {"user":"55","tags":["statistics","spss"],"questionId":1679,"creationDate":"2008-08-04T22:56:45Z","title":"How do I calculate these statistics?","acceptedAnswerId":1704,"type":"question","body":"I'm writing an app to help facilitate some research, and part of this involves doing some statistical calculations. Right now, the researchers are using a program called SPSS. Part of the output that they care about looks like this: They're really only concerned about the F and Sig. values. My problem is that I have no background in statistics, and I can't figure out what the tests are called, or how to calculate them. I thought the F value might be the result of the F-test, but after following the steps given on Wikipedia, I got a result that was different from what SPSS gives. "} {"user":"350","tags":["asp.net","profile"],"questionId":1683,"creationDate":"2008-08-04T23:06:23Z","title":"ASP.NET built in user profile vs. old stile user class/tables","acceptedAnswerId":3020,"type":"question","body":"I am looking for guidance regarding the best practice around the use of the Profile feature in ASP.NET. How do you decide what should be kept in the built-in user Profile, or if you should create your own DB Table and add a column for the desired fields? For example, a user has a ZIP code, should I save the ZIP code in my own table, or should I add it to the web.config xml profile and access it via the user profile ASP.NET mechanize? The pros/cons I can think of are that since I don't know the profile very well (it is a bit of a Matrix right now), I probably can do whatever I want if I go the table route (e.g., SQL to get all the users in the same ZIP code as the current user); I don't know if I can do the same if I use the ASP.NET profile. "} {"user":"115","questionId":657,"creationDate":"2008-08-04T23:07:15Z","answerId":1684,"type":"answer","body":"I'm not necessarily looking for the fastest but a nice balance, some of the server that this code is being developed for are fairly slow, the script that hashes and stores the password is taking 5-6 seconds to run, and I've narrowed it down to the hashing (if I comment the hashing out it runs, in 1-2 seconds). It doesn't have to be the MOST secure, I'm not codding for a bank (right now) but I certainly WILL NOT store the passwords as plain-text. "} {"user":"316","questionId":1669,"creationDate":"2008-08-04T23:08:18Z","answerId":1686,"type":"answer","body":"I concur with the Dragon Book reference; IMO, it is the definitive guide to compiler construction. Get ready for some hardcore theory, though. If you want a book that is lighter on theory, Game Scripting Mastery might be a better book for you. If you are a total newbie at compiler theory, it provides a gentler introduction. It doesn't cover more practical parsing methods (opting for non-predictive recursive descent without discussing LL or LR parsing), and as I recall, it doesn't even discuss any sort of optimization theory. Plus, instead of compiling to machine code, it compiles to a bytecode that is supposed to run on a VM that you also write. It's still a decent read, particularly if you can pick it up for cheap on Amazon. If you only want an easy introduction into compilers, Game Scripting Mastery is not a bad way to go. If you want to go hardcore up front, then you should settle for nothing less than the Dragon Book. "} {"user":"230","questionId":1683,"creationDate":"2008-08-04T23:10:05Z","answerId":1687,"type":"answer","body":"In my experience its best to keep an the info in the profile to a bare minimum, only put the essentials in there that are directly needed for authentication. Other information such as addresses should be saved in your own database by your own application logic, this approach is more extensible and maintainable. "} {"user":"91","questionId":1683,"creationDate":"2008-08-04T23:10:30Z","answerId":1688,"type":"answer","body":"I think that depends on how many fields you need. To my knowledge, Profiles are essentially a long string that gets split at the given field sizes, which means that they do not scale very well if you have many fields and users. On the other hand, they are built in, so it's an easy and standardized way, which means there is not a big learning curve and you can use it in future apps as well without needing to tweak it to a new table structure. Rolling your own thing allows you to put it in a properly normalized database, which drastically improves performance, but you have to write pretty much all the profile managing code yourself. Edit: Also, Profiles are not cached, so every access to a profile goes to the database first (it's then cached for that request, but the next request will get it from the database again) If you're thinking about writing your own thing, maybe a custom Profile Provider gives you the best of both worlds - seamless integration, yet the custom stuff you want to do. "} {"user":"101","questionId":1669,"creationDate":"2008-08-04T23:13:49Z","answerId":1693,"type":"answer","body":"If you're looking to use powerful, higher level tools rather than building everything yourself, going through the projects and readings for this course is a pretty good option. It's a languages course by the author of the Java parser engine ANTLR. You can get the book for the course as a PDF from the Pragmatic Programmers. The course goes over the standard compiler compiler stuff that you'd see elsewhere: parsing, types and type checking, polymorphism, symbol tables, and code generation. Pretty much the only thing that isn't covered is optimizations. The final project is a program that compiles a subset of C. Because you use tools like ANTLR and LLVM, it's feasible to write the entire compiler in a single day (I have an existence proof of this, though I do mean ~24 hours). It's heavy on practical engineering using modern tools, a bit lighter on theory. LLVM, by the way, is simply fantastic. Many situations where you might normally compile down to assembly, you'd be much better off compiling to LLVM's Intermediate Representation instead. It's higher level, cross platform, and LLVM is quite good at generating optimized assembly from it. "} {"user":"183","questionId":1176,"creationDate":"2008-08-04T23:29:03Z","answerId":1703,"type":"answer","body":"The active projects on Rubyforge are a great place to start. What would be a good starter project is to pick one that is pretty popular but not a lot of developers. If you are interested in Ruby on Rails, I'm working on Redmine right now. It's been one of the most active projects and only has 5 developers. Open Source Rails also has a good collection of projects. I've found doing a Refactotum a great way to get started on a project. Use the fact that you are new to your advantage, most people who have been on a project forget about simple things like gem dependencies and documentation "} {"user":"59","questionId":1679,"creationDate":"2008-08-04T23:32:54Z","answerId":1704,"type":"answer","body":"This website might help you out a bit more. Also this one. I'm working from a fairly rusty memory of a statistics course, but here goes nothing: When you're doing analysis of variance (ANOVA), you actually calculate the F statistic as the ratio from the mean-square variances \"between the groups\" and the mean-square variances \"within the groups\". The second link above seems pretty good for this calculation. This makes the F statistic measure exactly how powerful your model is, because the \"between the groups\" variance is explanatory power, and \"within the groups\" variance is random error. High F implies a highly significant model. As in many statistical operations, you back-determine Sig. using the F statistic. Here's where your Wikipedia information comes in slightly handy. What you want to do is - using the degrees of freedom given to you by SPSS - find the proper P value at which an F table will give you the F statistic you calculated. The P value where this happens [F(table) = F(calculated)] is the significance. Conceptually, a lower significance value shows a very strong ability to reject the null hypothesis (which for these purposes means to determine your model has explanatory power). Sorry to any math folks if any of this is wrong. I'll be checking back to make edits!!! Good luck to you. Stats is fun, just maybe not this part. =) "} {"user":"349","tags":["web-services","application-integration"],"questionId":1709,"creationDate":"2008-08-04T23:43:34Z","title":"How to pass enumerated values to a web service","acceptedAnswerId":1724,"type":"question","body":"My dilemma is, basically, how to share an enumeration between two applications. The users upload documents through a front-end application that is on the web. This application calls a web service of the back-end application and passes the document to it. The back-end app saves the document and inserts a row in the Document table. The document type (7 possible document types: Invoice, Contract etc.) is passed as a parameter to the web service's UploadDocument method. The question is, what should the type (and possible values) of this parameter be? Since you need to hardcode these values in both applications, I think it is O.K. to use a descriptive string (Invoice, Contract, WorkOrder, SignedWorkOrder). Is it maybe a better approach to create a DocumentTypes enumeration in the first application, and to reproduce it also in the second application, and then pass the corresponding integer value to the web service between them? "} {"user":"303","tags":["resources"],"questionId":1711,"creationDate":"2008-08-04T23:50:22Z","title":"What is the single most influential book every programmer should read?","type":"question","body":"If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be? I expect this list to be varied and to cover a wide range of things. To search: Use the search box in the upper-right corner. To search the answers of the current question, use inquestion:this. For example: inquestion:this \"Code Complete\" "} {"user":"92","questionId":1711,"creationDate":"2008-08-04T23:51:07Z","answerId":1713,"type":"answer","body":" Code Complete (2nd edition) by Steve McConnell The Pragmatic Programmer Structure and Interpretation of Computer Programs The C Programming Language by Kernighan and Ritchie Introduction to Algorithms by Cormen, Leiserson, Rivest & Stein Design Patterns by the Gang of Four Refactoring: Improving the Design of Existing Code The Mythical Man Month The Art of Computer Programming by Donald Knuth Compilers: Principles, Techniques and Tools by Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman Gödel, Escher, Bach by Douglas Hofstadter Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin Effective C++ More Effective C++ CODE by Charles Petzold Programming Pearls by Jon Bentley Working Effectively with Legacy Code by Michael C. Feathers Peopleware by Demarco and Lister Coders at Work by Peter Seibel Surely You're Joking, Mr. Feynman! Effective Java 2nd edition Patterns of Enterprise Application Architecture by Martin Fowler The Little Schemer The Seasoned Schemer Why's (Poignant) Guide to Ruby The Inmates Are Running The Asylum: Why High Tech Products Drive Us Crazy and How to Restore the Sanity The Art of Unix Programming Test-Driven Development: By Example by Kent Beck Practices of an Agile Developer Don't Make Me Think Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin Domain Driven Designs by Eric Evans The Design of Everyday Things by Donald Norman Modern C++ Design by Andrei Alexandrescu Best Software Writing I by Joel Spolsky The Practice of Programming by Kernighan and Pike Pragmatic Thinking and Learning: Refactor Your Wetware by Andy Hunt Software Estimation: Demystifying the Black Art by Steve McConnel The Passionate Programmer (My Job Went To India) by Chad Fowler Hackers: Heroes of the Computer Revolution Algorithms + Data Structures = Programs Writing Solid Code JavaScript - The Good Parts Getting Real by 37 Signals Foundations of Programming by Karl Seguin Computer Graphics: Principles and Practice in C (2nd Edition) Thinking in Java by Bruce Eckel The Elements of Computing Systems Refactoring to Patterns by Joshua Kerievsky Modern Operating Systems by Andrew S. Tanenbaum The Annotated Turing Things That Make Us Smart by Donald Norman The Timeless Way of Building by Christopher Alexander The Deadline: A Novel About Project Management by Tom DeMarco The C++ Programming Language (3rd edition) by Stroustrup Patterns of Enterprise Application Architecture Computer Systems - A Programmer's Perspective Agile Principles, Patterns, and Practices in C# by Robert C. Martin Growing Object-Oriented Software, Guided by Tests Framework Design Guidelines by Brad Abrams Object Thinking by Dr. David West Advanced Programming in the UNIX Environment by W. Richard Stevens Hackers and Painters: Big Ideas from the Computer Age The Soul of a New Machine by Tracy Kidder CLR via C# by Jeffrey Richter The Timeless Way of Building by Christopher Alexander Design Patterns in C# by Steve Metsker Alice in Wonderland by Lewis Carol Zen and the Art of Motorcycle Maintenance by Robert M. Pirsig About Face - The Essentials of Interaction Design Here Comes Everybody: The Power of Organizing Without Organizations by Clay Shirky The Tao of Programming Computational Beauty of Nature Writing Solid Code by Steve Maguire Philip and Alex's Guide to Web Publishing Object-Oriented Analysis and Design with Applications by Grady Booch Effective Java by Joshua Bloch Computability by N. J. Cutland Masterminds of Programming The Tao Te Ching The Productive Programmer The Art of Deception by Kevin Mitnick The Career Programmer: Guerilla Tactics for an Imperfect World by Christopher Duncan Paradigms of Artificial Intelligence Programming: Case studies in Common Lisp Masters of Doom Pragmatic Unit Testing in C# with NUnit by Andy Hunt and Dave Thomas with Matt Hargett How To Solve It by George Polya The Alchemist by Paulo Coelho Smalltalk-80: The Language and its Implementation Writing Secure Code (2nd Edition) by Michael Howard Introduction to Functional Programming by Philip Wadler and Richard Bird No Bugs! by David Thielen Rework by Jason Freid and DHH JUnit in Action "} {"user":"292","questionId":145,"creationDate":"2008-08-04T23:52:51Z","answerId":1716,"type":"answer","body":"This is very easy to do in java, and as stated above you can reach into the java.util.zip libraries from C#. For references see: java.util.zip javadocs sample code I used this a while ago to do a deep (recursive) zip of a folder structure, but I don't think I ever used the unzipping. If I'm so motivated I may pull that code out and edit it into here later. "} {"user":"137","questionId":1383,"creationDate":"2008-08-04T23:53:16Z","answerId":1718,"type":"answer","body":"This is my take on it. I would say unit testing is the practice of writing software tests to verify that your real software does what it is meant to. This started with jUnit in the Java world and has become a best practice in PHP as well with SimpleTest and phpUnit. It's a core practice of Extreme Programming and helps you to be sure that your software still works as intended after editing. If you have sufficient test coverage, you can do major refactoring, bug fixing or add features rapidly with much less fear of introducing other problems. It's most effective when all unit tests can be run automatically. Unit testing is generally associated with OO development. The basic idea is to create a script which sets up the environment for your code and then exercises it; you write assertions, specify the intended output that you should receive and then execute your test script using a framework such as those mentioned above. The framework will run all the tests against your code and then report back success or failure of each test. phpUnit is run from the Linux command line by default, though there are HTTP interfaces available for it. SimpleTest is web-based by nature and is much easier to get up and running, IMO. In combination with xDebug, phpUnit can give you automated statistics for code coverage which some people find very useful. Some teams write hooks from their subversion repository so that unit tests are run automatically whenever you commit changes. It's good practice to keep your unit tests in the same repository as your application. "} {"user":"101","questionId":1709,"creationDate":"2008-08-04T23:54:12Z","answerId":1721,"type":"answer","body":"I'd suggest against passing an integer between them, simply for purposes of readability and debugging. Say you're going through your logs and you see a bunch of 500 errors for DocumentType=4. Now you've got to go look up which DocumentType is 4. Or if one of the applications refers to a number that doesn't exist in the other, perhaps due to mismatched versions. It's a bit more code, and it rubs the static typing part of the brain a bit raw, but in protocols on top of HTTP the received wisdom is to side with legible strings over opaque enumerations. "} {"user":"91","questionId":1709,"creationDate":"2008-08-04T23:56:54Z","answerId":1724,"type":"answer","body":"I can only speak about .net, but if you have an ASP.net Webservice, you should be able to add an enumeration directly to it. When you then use the \"Add Web Reference\" in your Client Application, the resulting Class should include that enum But this is from the top of my head, i'm pretty sure i've done it in the past, but I can't say for sure. "} {"user":"275","questionId":1709,"creationDate":"2008-08-05T00:12:35Z","answerId":1733,"type":"answer","body":"I would still use enumeration internally but would expect consumers to pass me only the name, not the numeric value itself. just some silly example to illustrate: public enum DocumentType { Invoice, Contract, WorkOrder, SignedWorkOrder } [WebMethod] public void UploadDocument(string type, byte[] data) { DocumentType docType = (DocumentType)Enum.Parse(typeof(DocumentType), type); } "} {"user":"59","tags":["python","xml","database","protocol-buffers"],"questionId":1734,"creationDate":"2008-08-05T00:12:55Z","title":"Any experiences with Protocol Buffers?","acceptedAnswerId":1780,"type":"question","body":"I was just looking through some information about Google's protocol buffers data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data. "} {"user":"137","tags":["php","regex","html-parsing","preg-replace"],"questionId":1746,"creationDate":"2008-08-05T00:35:17Z","title":"How can I get at the matches when using preg_replace in PHP?","acceptedAnswerId":1749,"type":"question","body":"I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using preg_replace for extract and wrapping purposes, but it's not outputting anything. preg_replace(\"/[A-Z]/\", \"$1\", $str) "} {"user":"137","questionId":1746,"creationDate":"2008-08-05T00:36:08Z","answerId":1749,"type":"answer","body":"You need to put the pattern in parentheses /([A-Z])/, like this: preg_replace(\"/([A-Z])/\", \"$1\", $str) "} {"user":"332","questionId":11,"creationDate":"2008-08-05T00:42:56Z","answerId":1752,"type":"answer","body":"I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate \"months ago\" that didn't seem too over-engineered. I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected). For the below code PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago) returns the relative time message (e.g. \"yesterday\"). public class RelativeTimeRange : IComparable { public TimeSpan UpperBound { get; set; } public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta); public RelativeTimeTextDelegate MessageCreator { get; set; } public int CompareTo(object obj) { if (!(obj is RelativeTimeRange)) { return 1; } // note that this sorts in reverse order to the way you'd expect, // this saves having to reverse a list later return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound); } } public class PrintRelativeTime { private static List timeRanges; static PrintRelativeTime() { timeRanges = new List{ new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(1), MessageCreator = (delta) => { return \"one second ago\"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(60), MessageCreator = (delta) => { return delta.Seconds + \" seconds ago\"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(2), MessageCreator = (delta) => { return \"one minute ago\"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(60), MessageCreator = (delta) => { return delta.Minutes + \" minutes ago\"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromHours(2), MessageCreator = (delta) => { return \"one hour ago\"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromHours(24), MessageCreator = (delta) => { return delta.Hours + \" hours ago\"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromDays(2), MessageCreator = (delta) => { return \"yesterday\"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)), MessageCreator = (delta) => { return delta.Days + \" days ago\"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)), MessageCreator = (delta) => { return \"one month ago\"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)), MessageCreator = (delta) => { return (int)Math.Floor(delta.TotalDays / 30) + \" months ago\"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)), MessageCreator = (delta) => { return \"one year ago\"; } }, new RelativeTimeRange { UpperBound = TimeSpan.MaxValue, MessageCreator = (delta) => { return (int)Math.Floor(delta.TotalDays / 365.24D) + \" years ago\"; } } }; timeRanges.Sort(); } public static string GetRelativeTimeMessage(TimeSpan ago) { RelativeTimeRange postRelativeDateRange = timeRanges[0]; foreach (var timeRange in timeRanges) { if (ago.CompareTo(timeRange.UpperBound) <= 0) { postRelativeDateRange = timeRange; } } return postRelativeDateRange.MessageCreator(ago); } } "} {"user":"137","questionId":888,"creationDate":"2008-08-05T00:49:42Z","answerId":1758,"type":"answer","body":"+1 for print_r(). Use it to dump out the contents of an object or variable. To make it more readable, do it with a pre tag so you don't need to view source. echo '
'; print_r($arrayOrObject); Also var_dump($thing) - this is very useful to see the type of subthings "}
{"user":"234","tags":["c#",".net","unit-testing","testing"],"questionId":1760,"creationDate":"2008-08-05T00:51:49Z","title":".NET Unit Testing packages?","acceptedAnswerId":1821,"type":"question","body":"Getting back into a bit more .NET after a few-years of not using it full-time, and wondering what the good unit testing packages are these days. I'm familiar with NUnit (a few years ago), and have played briefly around with IronRuby, with the goal of getting something like rspec going, but don't know much beyond that. I realize I could google for this and call it a day but I believe I'm likely to get a better and more informed response from asking a question here :-) Suggestions? "}
{"user":"137","tags":["php","ternary-operator"],"questionId":1762,"creationDate":"2008-08-05T00:56:43Z","title":"Why is my ternary expression not working?","acceptedAnswerId":1771,"type":"question","body":"I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false. $canMerge = ($condition1 && $condition2) ? 'true' : 'false'; ... Stuff What's up? "}
{"user":"137","questionId":1762,"creationDate":"2008-08-05T00:57:30Z","answerId":1764,"type":"answer","body":"The value of 'false' is true. You need to remove the quotes: $canMerge = ($condition1 && $condition2) ? true : false; "}
{"user":"307","questionId":1760,"creationDate":"2008-08-05T00:57:48Z","answerId":1765,"type":"answer","body":"I like MbUnit, er, Gallio. Most importantly to me is having good tools support inside Visual Studio. For that I use Resharper, which has an MbUnit test runner. A lot of folks seem to like TestDriven.NET as their test runner as well. "}
{"user":"219","questionId":1762,"creationDate":"2008-08-05T01:03:12Z","answerId":1771,"type":"answer","body":"This is broken because 'false' as a string will evaluate to true as a boolean. However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent: $canMerge = ($condition1 && $condition2); "}
{"user":"164","questionId":1070,"creationDate":"2008-08-05T01:07:50Z","answerId":1773,"type":"answer","body":"The exact definitions of \"vsize,\" \"rss,\" \"rprvt,\" \"rshrd,\" and other obscure-looking abbreviations vary from OS to OS. The manual pages for the \"top\" and \"ps\" commands will have some sort of description, but all such descriptions are simplified greatly (or are based on long-extinct kernel implementations). \"Process size\" as a concept is fiendishly difficult to pin down in the general case. Answers in specific instances depend heavily on the actual memory management implementation in the OS, and are rarely as satisfying as the tidy \"process size\" concept that exists in the minds of most users (and most developers). For example, none of those numbers (nor, likely, any combination of them) can be used to tell you exactly how many such processes can run at once in a given amount of free memory. But really, your best bet is to come at it from that end: why do you want this number, and what will you use it for? Given that information, I think you'll get more useful answers. "}
{"user":"313","questionId":1600,"creationDate":"2008-08-05T01:11:30Z","answerId":1776,"type":"answer","body":"The Publish to Provider functionality has worked great for me. See Scott Gu's Blog Entry. If you need something really robust look at redgate software's tools here...if you are doing much SQL at all, these are worth the $$. "}
{"user":"234","questionId":36,"creationDate":"2008-08-05T01:12:37Z","answerId":1778,"type":"answer","body":"Wild guess here: If you don't want to modify the third party's tables, Can you create a view and then put a trigger on that view? "}
{"user":"77","questionId":1734,"creationDate":"2008-08-05T01:14:30Z","answerId":1780,"type":"answer","body":"If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea. Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... JSON? "}
{"user":"157","questionId":1711,"creationDate":"2008-08-05T01:25:46Z","answerId":1788,"type":"answer","body":"@Peter Coulton -- you don't read Knuth, you study it. For me, and my work... Purely Functional Data Structures is great for thinking and developing with functional languages in mind. "}
{"user":"77","questionId":1709,"creationDate":"2008-08-05T01:26:14Z","answerId":1789,"type":"answer","body":"In .NET, enumeration values are (by default) serialized into xml with the name. For instances where you can have multiple values (flags), then it puts a space between the values. This works because the enumeration doesn't contain spaces, so you can get the value again by splitting the string (ie. \"Invoice Contract SignedWorkOrder\", using lubos's example). You can control the serialization of values of in asp.net web services using the XmlEnumAttribute, or using the EnumMember attribute when using WCF. "}
{"user":"194","tags":["svn","version-control"],"questionId":1790,"creationDate":"2008-08-05T01:27:34Z","title":"Federated (Synced) Subversion servers?","acceptedAnswerId":2017,"type":"question","body":"Is it possible to create \"federated\" Subversion servers? As in one server at location A and another at location B that sync up their local versions of the repository automatically. That way when someone at either location interacts with the repository they are accessing their respective local server and therefore has faster response times. "}
{"user":"307","questionId":1600,"creationDate":"2008-08-05T01:31:16Z","answerId":1793,"type":"answer","body":"Backup and Restore is the most straight-forward way I know. You have to be careful between servers as security credentials don't come with the restored database. "}
{"user":"117","questionId":1790,"creationDate":"2008-08-05T01:32:34Z","answerId":1794,"type":"answer","body":"Sounds like you might like Git. There's a Google Talk explaining all about it. "}
{"user":"357","questionId":1709,"creationDate":"2008-08-05T01:34:40Z","answerId":1798,"type":"answer","body":"If you are consuming your Web service from a .NET page/application, you should be able to access the enumeration after you add your Web reference to the project that is consuming the service. "}
{"user":"332","questionId":1746,"creationDate":"2008-08-05T01:39:36Z","answerId":1803,"type":"answer","body":"From the preg_replace documentation on php.net: replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. See Flubba's example. "}
{"user":"292","questionId":1790,"creationDate":"2008-08-05T01:44:13Z","answerId":1806,"type":"answer","body":"Its probably not exactly what your looking for, but you may be able to implement OS level clustering. "}
{"user":"62","questionId":231,"creationDate":"2008-08-05T01:49:25Z","answerId":1812,"type":"answer","body":"@Dillie-O: Your answer put me in the right direction (I should have expected it to just be a registry change) and I got this working. But I'm going to mark this as the answer because I'm going to put some additional information that I found while working on this. The solution to this question really doesn't matter what programming language you're using, as long as there's some way to modify Windows registry settings. Finally, here's the answer: To associate a program with the mailto protocol for all users on a computer, change the HKEY_CLASSES_ROOT\\mailto\\shell\\open\\command Default value to: \"Your program's executable\" \"%1\" To associate a program with the mailto protocol for the current user, change the HKEY_CURRENT_USER\\Software\\Classes\\mailto\\shell\\open\\command Default value to: \"Your program's executable\" \"%1\" The %1 will be replaced with the entire mailto URL. For example, given the link: Email me The following will be executed: \"Your program's executable\" \"mailto:user@example.com\" Update (via comment by shellscape): As of Windows 8, this method no longer works as expected. Win8 enforces the following key: HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associati‌​ons\\URLAssociations\\‌​MAILTO\\UserChoice for which the ProgID of the selected app is hashed and can't be forged. It's a royal PITA "}
{"user":"358","questionId":1760,"creationDate":"2008-08-05T02:07:50Z","answerId":1820,"type":"answer","body":"I like TestDriven.NET (even though I use ReSharper) and I'm pretty happy with XUnit.net. It uses Facts instead of Tests which many people dislike but I like the difference in terminology. It's useful to think of a collection of automatically provable Facts about your software and see which ones you violate when you make a change. Be aware that Visual Studio 2008 Professional (and above) now comes with integrated Unit Testing (it used to be available only with the Team System Editions) and may be suitable for your needs. "}
{"user":"308","questionId":1760,"creationDate":"2008-08-05T02:15:24Z","answerId":1821,"type":"answer","body":"There are so many it's crazy. Crazy good, I guess. For the conservative types (me), NUnit is still available and still more than capable. For the Microsoft-types, MSTest is adequate, but slow and clunky compared to Nunit. It also lacks code coverage without paying the big bucks for the pricey versions of Visual Studio. There's also MbUnit. It's like NUnit, but has nifty features like RowTest (run the same test with different parameters) and Rollback (put the database back like you found it after a test) And finally, xUnit.net is the trendy option with some attitude. Oh, and TestDriven.NET will give you IDE integration for both Nunit and MBunit. I'm sure they're all just fine. I'd steer away from MSTest though, unless you just enjoy the convenience of having everything in one IDE out of the box. Scott Hanselman has a podcast on this very topic. "}
{"user":"205","questionId":1644,"creationDate":"2008-08-05T02:21:00Z","answerId":1824,"type":"answer","body":"This one's not specifically about development, but Security Now from Steve Gibson and Leo Laporte is an excellent discussion of security issues. I think it's a must-listen for just about any computer user who's concerned about security, and especially for web developers who are responsible both for the security of their site and at least partially responsible for their users' security. "}
{"user":"205","questionId":588,"creationDate":"2008-08-05T02:35:02Z","answerId":1826,"type":"answer","body":"Is your customer using Exchange 2007? If so, I'd have a look at Exchange Web Services. If not, as hairy as it can be, I think WebDAV is your best bet. Personally I don't like using the Outlook.Application COM object route, as its security prompts (\"An application is attempting to access your contacts. Allow this?\", etc.) can cause problems on a server. I also think it would be difficult to accomplish your impersonation-like tasks using Outlook, such as sending mail as a given user. "}
{"user":"30","tags":["python"],"questionId":1829,"creationDate":"2008-08-05T02:39:23Z","title":"How do I make a menu that does not require the user to press [enter] to make a selection?","acceptedAnswerId":1852,"type":"question","body":"I've got a menu in Python. That part was easy. I'm using raw_input() to get the selection from the user. The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far: import sys print \"\"\"Menu 1) Say Foo 2) Say Bar\"\"\" answer = raw_input(\"Make a selection> \") if \"1\" in answer: print \"foo\" elif \"2\" in answer: print \"bar\" It would be great to have something like print menu while lastKey = \"\": lastKey = check_for_recent_keystrokes() if \"1\" in lastKey: #do stuff... "}
{"user":"172","tags":["c#","winapi","mouse"],"questionId":1836,"creationDate":"2008-08-05T02:51:37Z","title":"Wiggling the mouse","acceptedAnswerId":1843,"type":"question","body":"OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up. I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes. I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there. "}
{"user":"116","questionId":1829,"creationDate":"2008-08-05T02:54:54Z","answerId":1840,"type":"answer","body":"On Linux: set raw mode select and read the keystroke restore normal settings import sys import select import termios import tty def getkey(): old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) answer = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) return answer print \"\"\"Menu 1) Say Foo 2) Say Bar\"\"\" answer=getkey() if \"1\" in answer: print \"foo\" elif \"2\" in answer: print \"bar\" "}
{"user":"275","questionId":1836,"creationDate":"2008-08-05T03:00:24Z","answerId":1843,"type":"answer","body":"for C# 3.5 without notifyicon therefore you will need to terminate this application in task manager manually using System; using System.Drawing; using System.Windows.Forms; static class Program { static void Main() { Timer timer = new Timer(); // timer.Interval = 4 minutes timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond); timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); }; timer.Start(); Application.Run(); } } "}
{"user":"36","tags":["c#","image","image-processing","artificial-intelligence"],"questionId":1848,"creationDate":"2008-08-05T03:04:43Z","title":"Locating Text within image","acceptedAnswerId":1856,"type":"question","body":"I am currently working on a project and my goal is to locate text in an image. OCR'ing the text is not my intention as of yet. I want to basically obtain the bounds of text within an image. I am using the AForge.Net imaging component for manipulation. Any assistance in some sense or another? Update 2/5/09: I've since went along another route in my project. However I did attempt to obtain text using MODI (Microsoft Office Document Imaging). It allows you to OCR an image and pull text from it with some ease. "}
{"user":"87","questionId":1836,"creationDate":"2008-08-05T03:07:41Z","answerId":1849,"type":"answer","body":"Something like this should work (though, you will want to change the interval). public Form1() { InitializeComponent(); Timer Every4Minutes = new Timer(); Every4Minutes.Interval = 10; Every4Minutes.Tick += new EventHandler(MoveNow); Every4Minutes.Start(); } void MoveNow(object sender, EventArgs e) { Cursor.Position = new Point(Cursor.Position.X - 1, Cursor.Position.Y - 1); } "}
{"user":"116","questionId":1829,"creationDate":"2008-08-05T03:11:55Z","answerId":1852,"type":"answer","body":"On Windows: import msvcrt answer=msvcrt.getch() "}
{"user":"116","tags":["python","cross-platform"],"questionId":1854,"creationDate":"2008-08-05T03:23:18Z","title":"Python: What OS am I running on?","acceptedAnswerId":1857,"type":"question","body":"What do I need to look at to see if I'm on Windows, Unix, etc? "}
{"user":"2089740","questionId":1848,"creationDate":"2008-08-05T03:24:27Z","answerId":1856,"type":"answer","body":"This is an active area of research. There are literally oodles of academic papers on the subject. It's going to be difficult to give you assistance especially w/o more deatails. Are you looking for specific types of text? Fonts? English-only? Are you familiar with the academic literature? \"Text detection\" is a standard problem in any OCR (optical character recognition) system and consequently there are lots of bits of code on the interwebs that deal with it. I could start listing piles of links from google but I suggest you just do a search for \"text detection\" and start reading :). There is ample example code available as well. "}
{"user":"2089740","questionId":1854,"creationDate":"2008-08-05T03:27:03Z","answerId":1857,"type":"answer","body":">>> import os >>> print os.name posix >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' See: platform — Access to underlying platform’s identifying data "}
{"user":"358","tags":["sql-server","database","documentation","data-dictionary"],"questionId":1869,"creationDate":"2008-08-05T03:50:42Z","title":"Which tools do people use to create Data Dictionaries?","acceptedAnswerId":968319,"type":"question","body":"On the project that I am working on I have a couple of databases. Each table and each column in the database has a description set (as an extended property in SQL 2005). As a part of the documentation going to the client we need to produce a data dictionary showing all of the tables and columns along with a collection of meta data (data-type, optionality, constraints). Is anyone using a tool to automatically create this kind of document? If so, which tools do you use? I have used Data Dictionary Creator which is awesome but it doesn't seem to do data types or optionality (unless you want to add in custom fields and fill them in yourself). "}
{"user":"30","questionId":1829,"creationDate":"2008-08-05T03:51:57Z","answerId":1870,"type":"answer","body":"Wow, that took forever. Ok, here's what I've ended up with #!C:\\python25\\python.exe import msvcrt print \"\"\"Menu 1) Say Foo 2) Say Bar\"\"\" while 1: char = msvcrt.getch() if char == chr(27): #escape break if char == \"1\": print \"foo\" break if char == \"2\": print \"Bar\" break It fails hard using IDLE, the python...thing...that comes with python. But once I tried it in DOS (er, CMD.exe), as a real program, then it ran fine. No one try it in IDLE, unless you have Task Manager handy. I've already forgotten how I lived with menus that arn't super-instant responsive. "}
{"user":"216","questionId":1854,"creationDate":"2008-08-05T03:57:22Z","answerId":1871,"type":"answer","body":"Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista! >>> import os >>> os.name 'nt' >>> import platform >>> platform.system() 'Windows' >>> platform.release() 'Vista' ...and I can’t believe no one’s posted one for Windows 10 yet: >>> import os >>> os.name 'nt' >>> import platform >>> platform.system() 'Windows' >>> platform.release() '10' "}
{"user":"242","tags":["asp.net","javascript","anchor","quotes"],"questionId":1873,"creationDate":"2008-08-05T04:05:53Z","title":"Triple Quotes? How do I delimit a databound Javascript string parameter in ASP.NET?","acceptedAnswerId":1886,"type":"question","body":"How do I delimit a Javascript databound string parameter in an anchor OnClick event? I have an anchor tag in an ASP.NET Repeater control. The OnClick event of the anchor contains a call to a Javascript function. The Javascript function takes a string for its input parameter. The string parameter is populated with a databound value from the Repeater. I need the \"double quotes\" for the Container.DataItem. I need the 'single quotes' for the OnClick. And I still need one more delimiter (triple quotes?) for the input string parameter of the Javascript function call. Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer? Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer. Cheers in advance for any knowledge you can drop. The anchor: Show/Hide and here is the Javascript:  "}
{"user":"30","questionId":1873,"creationDate":"2008-08-05T04:08:18Z","answerId":1875,"type":"answer","body":" Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer. Can you do some rudimentary string function to force JavaScript into changing it into a string? Like value = value + \"\" "}
{"user":"116","questionId":1854,"creationDate":"2008-08-05T04:13:53Z","answerId":1879,"type":"answer","body":"For the record here's the results on Mac: >>> import os >>> os.name 'posix' >>> import platform >>> platform.system() 'Darwin' >>> platform.release() '8.11.1' "}
{"user":"26","questionId":1873,"creationDate":"2008-08-05T04:19:36Z","answerId":1881,"type":"answer","body":"Try putting the extra text inside the server-side script block and concatenating. onclick='<%# \"ToggleDisplay(\"\"\" & DataBinder.Eval(Container.DataItem, \"JobCode\") & \"\"\");\" %>' Edit: I'm pretty sure you could just use double quotes outside the script block as well. "}
{"user":"50","questionId":1829,"creationDate":"2008-08-05T04:28:03Z","answerId":1885,"type":"answer","body":"The reason msvcrt fails in IDLE is because IDLE is not accessing the library that runs msvcrt. Whereas when you run the program natively in cmd.exe it works nicely. For the same reason that your program blows up on Mac and Linux terminals. But I guess if you're going to be using this specifically for windows, more power to ya. "}
{"user":"275","questionId":1873,"creationDate":"2008-08-05T04:28:21Z","answerId":1886,"type":"answer","body":"I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (') and double quotes ("). Source code was total mess of course but it worked. Try Show/Hide or Show/Hide "}
{"user":"160","questionId":1607,"creationDate":"2008-08-05T04:36:13Z","answerId":1894,"type":"answer","body":"I create folders named after the build versions and put upgrade and downgrade scripts in there. For example, you could have the following folders: 1.0.0, 1.0.1 and 1.0.2. Each one contains the script that allows you to upgrade or downgrade your database between versions. Should a client or customer call you with a problem with version 1.0.1 and you are using 1.0.2, bringing the database back to his version will not be a problem. In your database, create a table called \"schema\" where you put in the current version of the database. Then writing a program that can upgrade or downgrade your database for you is easy. Just like Joey said, if you are in a Rails world, use Migrations. :) "}
{"user":"81","tags":["c#","vb.net","file","csv","import"],"questionId":1898,"creationDate":"2008-08-05T04:43:22Z","title":"CSV File Imports in .Net","acceptedAnswerId":1901,"type":"question","body":"I realize this is a newbie question, but I'm looking for a simple solution - it seems like there should be one. What's the best way to import a CSV file into a strongly-typed data structure? Again simple = better. "}
{"user":"303","questionId":1898,"creationDate":"2008-08-05T04:47:30Z","answerId":1901,"type":"answer","body":"Check out FileHelpers Open Source Library. "}
{"user":"172","questionId":1644,"creationDate":"2008-08-05T04:49:15Z","answerId":1904,"type":"answer","body":"Extending on what Mike Powell has to say, I am actually a big fan of almost all of the podcasts at http://www.twit.tv. Most of the content is watered down a bit, but some of the speakers are top notch thinkers - especially on \"This Week in Tech\", the flagship program. Oh - and Car Talk on NPR but those guys hardly EVER get into the SDLC! "}
{"user":"50","questionId":1898,"creationDate":"2008-08-05T04:49:26Z","answerId":1905,"type":"answer","body":"A good simple way to do it is to open the file, and read each line into an array, linked list, data-structure-of-your-choice. Be careful about handling the first line though. This may be over your head, but there seems to be a direct way to access them as well using a connection string. Why not try using Python instead of C# or VB? It has a nice CSV module to import that does all the heavy lifting for you. "}
{"user":"79","tags":["math","maps","mapping","latitude-longitude"],"questionId":1908,"creationDate":"2008-08-05T04:55:28Z","title":"How to map a latitude/longitude to a distorted map?","acceptedAnswerId":1945,"type":"question","body":"I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map. Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this? At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either. You can't assume North is up: all you have is the existing lat/long->x/y mappings. EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute. Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough. "}
{"user":"363","questionId":1104,"creationDate":"2008-08-05T04:56:30Z","answerId":1909,"type":"answer","body":"Chris' probably has the best pure answer to the question: However, I'm curious about the root of the question. If the user should always wrap the call in a try/catch block, should the user-called function really be throwing exceptions in the first place? This is a difficult question to answer without more context regarding the code-base in question. Shooting from the hip, I think the best answer here is to wrap the function up such that the recommended (if not only, depending on the overall exception style of the code) public interface does the try/catch for the user. If you're just trying to ensure that there are no unhandled exceptions in your code, unit tests and code review are probably the best solution. "}
{"user":"157","questionId":361,"creationDate":"2008-08-05T04:57:52Z","answerId":1910,"type":"answer","body":"You are going to get a lot of strings, that's for sure... \\sum_{i=x}^y{\\frac{r!}{{(r-i)}!}} http://www.codecogs.com/eq.latex?%5Csum_%7Bi=x%7D%5Ey%20%7B%20%5Cfrac%7Br!%7D%7B%7B(r-i)%7D!%7D%20%7D Where, x and y is how you define them and r is the number of characters we are selecting from --if I am understanding you correctly. You should definitely generate these as needed and not get sloppy and say, generate a powerset and then filter the length of strings. The following definitely isn't the best way to generate these, but it's an interesting aside, none-the-less. Knuth (volume 4, fascicle 2, tells us that (s,t)-combination is equivalent to s+1 things taken t at a time with repetition -- an (s,t)-combination is notation used by Knuth that is equal to {t \\choose {s+t} http://www.codecogs.com/eq.latex?%7Bt%20%5Cchoose%20%7Bs+t%7D%7D. We can figure this out by first generating each (s,t)-combination in binary form (so, of length (s+t)) and counting the number of 0's to the left of each 1. 10001000011101 --> becomes the permutation: {0, 3, 4, 4, 4, 1} "}
{"user":"5","questionId":1644,"creationDate":"2008-08-05T04:59:43Z","answerId":1911,"type":"answer","body":"Brad's list is pretty good. I also listen to: Sparkling Client (Silverlight specific) Jon Udell's Perspectives series Herding Code (shameless plug for a podcast I put on with Kevin Dente, Scott \"lazycoder\" Koon, and K. Scott Allen. We recently interviewed Jeff Atwood about Stack Overflow, discussing both how the site is designed and the technology behind it. "}
{"user":"122","questionId":1898,"creationDate":"2008-08-05T05:02:37Z","answerId":1912,"type":"answer","body":"If you can guarantee that there are no commas in the data, then the simplest way would probably be to use String.split. For example: String[] values = myString.Split(','); myObject.StringField = values[0]; myObject.IntField = Int32.Parse(values[1]); There may be libraries you could use to help, but that's probably as simple as you can get. Just make sure you can't have commas in the data, otherwise you will need to parse it better. "}
{"user":"231","questionId":1384,"creationDate":"2008-08-05T05:07:11Z","answerId":1914,"type":"answer","body":"Slightly off topic, but in a similar vein. Have you looked at Castle ActiveRecord it is written on top of NHibernate and removes the need to spend time creating XML mappings from code to the database. Like NHibernate you can structure your domain objects as you want and later generate a database schema from this structure. Using ActiveWriter, a contributed tool, you can easily map from your database to domain objects. "}
{"user":"198","questionId":1644,"creationDate":"2008-08-05T05:13:05Z","answerId":1920,"type":"answer","body":"I listen to the javaposse regularly, they cover mostly Java, but not solely. "}
{"user":"157","questionId":1908,"creationDate":"2008-08-05T05:20:55Z","answerId":1926,"type":"answer","body":"the problem is that the sphere can be distorted a number of ways, and having all those points known on the equator, lets say, wont help you map points further away. You need better 'close' points, then you can assume these three points are on a plane with the fourth and do the interpolation --knowing that the distance of longitudes is a function, not a constant. "}
{"user":"342","questionId":1908,"creationDate":"2008-08-05T05:21:02Z","answerId":1927,"type":"answer","body":"Ummm. Maybe I am missing something about the question here, but if you have long/lat info, you also have the direction of north? It seems you need to map geodesic coordinates to a projected coordinates system. For example osgb to wgs84. The maths involved is non-trivial, but the code comes out a only a few lines. If I had more time I'd post more but I need a shower so I will be boring and link to the wikipedia entry which is pretty good. Note: Post shower edited. "}
{"user":"51","questionId":1898,"creationDate":"2008-08-05T05:24:03Z","answerId":1928,"type":"answer","body":"There are two articles on CodeProject that provide code for a solution, one that uses StreamReader and one that imports CSV data using the Microsoft Text Driver. "}
{"user":"328","questionId":1241,"creationDate":"2008-08-05T05:30:41Z","answerId":1934,"type":"answer","body":"I'm not clear on whether or not you're wanting to add the asynchronous bits to the server in C# or the client in C++. If you're talking about doing this in C++, desktop Windows platforms can do socket I/O asynchronously through the API's that use overlapped I/O. For sockets, WSASend, WSARecv both allow async I/O (read the documentation on their LPOVERLAPPED parameters, which you can populate with events that get set when the I/O completes). I don't know if Windows Mobile platforms support these functions, so you might have to do some additional digging. "}
{"user":"364","tags":["c#","asp.net-mvc"],"questionId":1936,"creationDate":"2008-08-05T05:33:41Z","title":"How to RedirectToAction in ASP.NET MVC without losing request data","acceptedAnswerId":1940,"type":"question","body":"Using ASP.NET MVC there are situations (such as form submission) that may require a RedirectToAction. One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to. As I require the form to contain the originally POSTed data, for user convenience, as well as validation purposes, how can I pass the data through the RedirectToAction()? If I use the viewData parameter, my POST parameters will be changed to GET parameters. "}
{"user":"364","questionId":1936,"creationDate":"2008-08-05T05:43:27Z","answerId":1940,"type":"answer","body":"The solution is to use the TempData property to store the desired Request components. For instance: public ActionResult Send() { TempData[\"form\"] = Request.Form; return this.RedirectToAction(a => a.Form()); } Then in your \"Form\" action you can go: public ActionResult Form() { /* Declare viewData etc. */ if (TempData[\"form\"] != null) { /* Cast TempData[\"form\"] to System.Collections.Specialized.NameValueCollection and use it */ } return View(\"Form\", viewData); } "}
{"user":"328","questionId":1908,"creationDate":"2008-08-05T05:48:22Z","answerId":1945,"type":"answer","body":"Are there any more specific details on the kind of distortion? If, for example, your latitudes and longitudes are \"distorted\" onto your 2D map using a Mercator projection, the conversion math is readily available. If the map is distorted truly arbitrarily, there are lots of things you could try, but the simplest would probably be to compute a weighted average from your existing point mappings. Your weights could be the squared inverse of the x/y distance from your new point to each of your existing points. Some pseudocode: estimate-latitude-longitude (x, y) numerator-latitude := 0 numerator-longitude := 0 denominator := 0 for each point, deltaX := x - point.x deltaY := y - point.y distSq := deltaX * deltaX + deltaY * deltaY weight := 1 / distSq numerator-latitude += weight * point.latitude numerator-longitude += weight * point.longitude denominator += weight return (numerator-latitude / denominator, numerator-longitude / denominator) This code will give a relatively simple approximation. If you can be more precise about the way the projection distorts the geographical coordinates, you can probably do much better. "}
{"user":"22","questionId":6,"creationDate":"2008-08-05T05:54:23Z","answerId":1948,"type":"answer","body":"Here is some sample code. I think this is what you are looking for. The following displays exactly the same in Firefox 3 (mac) and IE7. #absdiv { position: absolute; left: 100px; top: 100px; width: 80%; height: 60%; background: #999; } #pctchild { width: 60%; height: 40%; background: #CCC; } #reldiv { position: relative; left: 20px; top: 20px; height: 25px; width: 40%; background: red; } 
"} {"user":"51","tags":["asp.net",".net","linq-to-sql","datacontext"],"questionId":1949,"creationDate":"2008-08-05T05:54:34Z","title":"Are Multiple DataContext classes ever appropriate?","acceptedAnswerId":5310,"type":"question","body":"In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create DataContext classes (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql. My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc. However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext. Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)? "} {"user":"46","questionId":1848,"creationDate":"2008-08-05T06:00:46Z","answerId":1957,"type":"answer","body":"recognizing text inside an image is indeed a hot topic for researchers in that field, but only begun to grow out of control when captcha's became the \"norm\" in terms of defense against spam bots. Why use captcha's as protection? well because it is/was very hard to locate (and read) text inside an image! The reason why I mention captcha's is because the most advancement* is made within that tiny area, and I think that your solution could be best found there. especially because captcha's are indeed about locating text (or something that resembles text) inside a cluttered image and afterwards trying to read the letters correctly. so if you can find yourself a good open source captcha breaking tool you probably have all you need to continue your quest... You could probably even throw away the most dificult code that handles the character recognition itself, because those OCR's are used to read distorted text, something you don't have to do. *: advancement in terms of visible, usable, and practical information for a \"non-researcher\" "} {"user":"116","tags":["sql","database","postgresql","stored-procedures","triggers"],"questionId":1970,"creationDate":"2008-08-05T06:39:31Z","title":"What language do you use for PostgreSQL triggers and stored procedures?","acceptedAnswerId":59345,"type":"question","body":"PostgreSQL is interesting in that it supports several languages for writing stored procedures. Which one do you use, and why? "} {"user":"269","questionId":1970,"creationDate":"2008-08-05T06:43:30Z","answerId":1971,"type":"answer","body":"When I wrote my first trigger it was in Perl because that was the language used in the example I found but the last triggers I wrote where in Python because I'm more comfortable with that. I think programmer comfort is my main reason to choose python but I think Perl is still better supported. "} {"user":"2090742","tags":["c++","performance","cpu","throttle"],"questionId":1982,"creationDate":"2008-08-05T07:11:08Z","title":"CPU throttling in C++","acceptedAnswerId":47086,"type":"question","body":"I was just wondering if there is an elegant way to set the maximum CPU load for a particular thread doing intensive calculations. Right now I have located the most time consuming loop in the thread (it does only compression) and use GetTickCount() and Sleep() with hardcoded values. It makes sure that the loop continues for a certain period of time and than sleeps for a certain minimal time. It more or less does the job i.e. guarantees that the thread will not use more than 50% of CPU. However behavior is dependent on the number of CPU cores (huge disadvantage) and simply ugly (smaller disadvantage :)). Any ideas? "} {"user":"116","tags":["python","list","tuples"],"questionId":1983,"creationDate":"2008-08-05T07:18:55Z","title":"Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?","acceptedAnswerId":2277,"type":"question","body":"In many places, (1,2,3) and [1,2,3] can be used interchangeably. When should I use one or the other, and why? "} {"user":"269","questionId":1982,"creationDate":"2008-08-05T07:23:45Z","answerId":1986,"type":"answer","body":"I can't think of any cross platform way of what you want (or any guaranteed way full stop) but as you are using GetTickCount perhaps you aren't interested in cross platform :) I'd use interprocess communications and set the intensive processes nice levels to get what you require but I'm not sure that's appropriate for your situation. EDIT: I agree with Bernard which is why I think a process rather than a thread might be more appropriate but it just might not suit your purposes. "} {"user":"269","questionId":1983,"creationDate":"2008-08-05T07:27:40Z","answerId":1987,"type":"answer","body":"The list [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost. The tuple (1,2,3) is fixed (immutable) and therefore faster. "} {"user":"122","tags":["macros","lisp"],"questionId":1988,"creationDate":"2008-08-05T07:32:54Z","title":"How far can LISP macros go?","acceptedAnswerId":63737,"type":"question","body":"I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby? Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language. "} {"user":"269","questionId":1988,"creationDate":"2008-08-05T07:40:26Z","answerId":1992,"type":"answer","body":"If you want lisp to look like Ruby use Ruby. It's possible to use Ruby (and Python) in a very lisp like way which is one of the main reasons they have gained acceptance so quickly. "} {"user":"122","questionId":1988,"creationDate":"2008-08-05T07:45:14Z","answerId":1993,"type":"answer","body":"@sparkes Sometimes LISP is the clear language choice, namely Emacs extensions. I'm sure I could use Ruby to extend Emacs if I wanted to, but Emacs was designed to be extended with LISP, so it seems to make sense to use it in that situation. "} {"user":"195","tags":["c#","data-binding"],"questionId":1994,"creationDate":"2008-08-05T07:45:38Z","title":"Any solution to the \"illegal cross thread call\" ?","acceptedAnswerId":2012,"type":"question","body":"When you data bind in C#, the thread that changes the data causes the control to change too. But if this thread is not the one on which the control was created, you'll get the above exception. I surfed the net and found no good answer. Anyone? "} {"user":"51","tags":["c#",".net","double","int"],"questionId":1995,"creationDate":"2008-08-05T07:49:11Z","title":"Most Efficient Way to Test Object Type","acceptedAnswerId":2001,"type":"question","body":"I have values stored as strings in a DataTable where each value could really represent an int, double, or string (they were all converted to strings during an import process from an external data source). I need to test and see what type each value really is. What is more efficient for the application (or is there no practical difference)? Try to convert to int (and then double). If conversion works, the return true. If an exception is thrown, return false. Regular expressions designed to match the pattern of an int or double Some other method? "} {"user":"227","questionId":1994,"creationDate":"2008-08-05T07:49:43Z","answerId":1996,"type":"answer","body":"If the data modification is not too time consuming (meaning, if the main purpose of the background thread is not the actual data modification), try moving the section that modifies the data to a delegate and Invoke'ing that delegate. If the actual heavy work is on the data, you'll probably have to create a deep copy of this data to pass to the background thread, which will send the processed data back to the UI thread via Invoke again. "} {"user":"122","questionId":1994,"creationDate":"2008-08-05T07:51:54Z","answerId":1998,"type":"answer","body":"You should be able to do something like: if (control.InvokeRequired) { control.Invoke(delegateWithMyCode); } else { delegateWithMyCode(); } InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread. UPDATE: Actually, at my last job we did something like this: private void SomeEventHandler(Object someParam) { if (this.InvokeRequired) { this.Invoke(new SomeEventHandlerDelegate(SomeEventHandler), someParam); } // Regular handling code } which removes the need for the else block and kind of tightens up the code. "} {"user":"195","questionId":1995,"creationDate":"2008-08-05T07:54:12Z","answerId":2001,"type":"answer","body":"Would use double.TryParse, it has performance benefits. "} {"user":"192","questionId":1994,"creationDate":"2008-08-05T07:56:53Z","answerId":2002,"type":"answer","body":"As I don't have a test case to go from I can't guarantee this solution, but it seems to me that a scenario similar to the one used to update progress bars in different threads (use a delegate) would be suitable here. public delegate void DataBindDelegate(); public DataBindDelegate BindData = new DataBindDelegate(DoDataBind); public void DoDataBind() { DataBind(); } If the data binding needs to be done by a particular thread, then let that thread do the work! "} {"user":"232","questionId":1995,"creationDate":"2008-08-05T08:02:01Z","answerId":2005,"type":"answer","body":"I'd personally use int.tryparse, then double.tryparse. Performance on those methods is quite fast. They both return a Boolean. If both fail then you have a string, per how you defined your data. "} {"user":"116","questionId":1982,"creationDate":"2008-08-05T08:03:01Z","answerId":2006,"type":"answer","body":"On linux, you can change the scheduling priority of a thread with nice(). "} {"user":"122","questionId":1995,"creationDate":"2008-08-05T08:04:22Z","answerId":2009,"type":"answer","body":"I would say, don't worry so much about such micro performance. It is much better to just get something to work, and then make it as clear and concise and easy to read as possible. The worst thing you can do is sacrifice readability for an insignificant amount of performance. In the end, the best way to deal with performance issues is to save them for when you have data that indicates there is an actual performance problem... otherwise you will spend a lot of time micro-optimizing and actually cause higher maintenance costs for later on. If you find this parsing situation is really the bottleneck in your application, THEN is the time to try and figure out what the fastest way to solve the problem is. I think Jeff (and many others) have blogged about this sort of thing a lot. "} {"user":"227","questionId":1994,"creationDate":"2008-08-05T08:05:56Z","answerId":2012,"type":"answer","body":"Re: 2004 No, you will only move the code that changes the data into the delegate function (because the data change is what triggers the control update). Other than that, you should not have to write anything extra. "} {"user":"192","questionId":1994,"creationDate":"2008-08-05T08:06:42Z","answerId":2013,"type":"answer","body":"If the thread call is \"illegal\" (i.e. the DataBind call affects controls that were not created in the thread it is being called from) then you need to create a delegate so that even if the decision / preparation for the DataBind is not done in the control-creating thread, any resultant modification of them (i.e. DataBind()) will be. You would call my code from the worker thread like so: this.BindData.Invoke(); This would then cause the original thread to do the binding, which (presuming it is the thread that created the controls) should work. "} {"user":"48","questionId":1790,"creationDate":"2008-08-05T08:22:05Z","answerId":2017,"type":"answer","body":"This is more or less the perfect use case for SVK. SVK is a command line front end for subversion that works with an entire local copy of the repository. So your commits, updates, etc. work on the local repository and you can then sync with a master. I would generally recommend SVK over plain subversion anyway as it makes a lot of things nicer. No .svn folders, better branching and merging, better conflict resolution. "} {"user":"342","questionId":330,"creationDate":"2008-08-05T08:29:13Z","answerId":2019,"type":"answer","body":"One way of deciding whether or not to use nested classes is to think whether or not this class plays a supporting role or it's own part. If it exists solely for the purpose of helping another class then I generally make it a nested class. There are a whole load of caveats to that, some of which seem contradictory but it all comes down to experience and gut-feeling. "} {"user":"370","questionId":330,"creationDate":"2008-08-05T08:37:19Z","answerId":2023,"type":"answer","body":"sounds like a case where you could use the strategy pattern "} {"user":"298","questionId":1644,"creationDate":"2008-08-05T08:43:05Z","answerId":2025,"type":"answer","body":"Also make sure you don't miss the dnrTV webcast show that Carl Franklin (the man behind .NET rocks) publishes. Even if it's a not a podcast and requires a more attention while watching it it's really informative and if you're into .NET and Microsoft related techniques you'll learn a lot. "} {"user":"46","tags":["language-agnostic","oop","parameters","pass-by-reference","pass-by-value"],"questionId":2027,"creationDate":"2008-08-05T08:56:01Z","title":"Pass by reference or pass by value?","type":"question","body":"When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, pass-by-value or pass-by-reference. So here is my question to all of you, in your favorite language, how is it actually done? And what are the possible pitfalls? Your favorite language can, of course, be anything you have ever played with: popular, obscure, esoteric, new, old... "} {"user":"46","questionId":2027,"creationDate":"2008-08-05T08:56:35Z","answerId":2028,"type":"answer","body":"Here is my own contribution for the Java programming language. first some code: public void swap(int x, int y) { int tmp = x; x = y; y = tmp; } calling this method will result in this: int pi = 3; int everything = 42; swap(pi, everything); System.out.println(\"pi: \" + pi); System.out.println(\"everything: \" + everything); \"Output: pi: 3 everything: 42\" even using 'real' objects will show a similar result: public class MyObj { private String msg; private int number; //getters and setters public String getMsg() { return this.msg; } public void setMsg(String msg) { this.msg = msg; } public int getNumber() { return this.number; } public void setNumber(int number) { this.number = number; } //constructor public MyObj(String msg, int number) { setMsg(msg); setNumber(number); } } public static void swap(MyObj x, MyObj y) { MyObj tmp = x; x = y; y = tmp; } public static void main(String args[]) { MyObj x = new MyObj(\"Hello world\", 1); MyObj y = new MyObj(\"Goodbye Cruel World\", -1); swap(x, y); System.out.println(x.getMsg() + \" -- \"+ x.getNumber()); System.out.println(y.getMsg() + \" -- \"+ y.getNumber()); } \"Output: Hello world -- 1 Goodbye Cruel World -- -1\" thus it is clear that Java passes its parameters by value, as the value for pi and everything and the MyObj objects aren't swapped. be aware that \"by value\" is the only way in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using '&' after the parameter's type) now the tricky part, or at least the part that will confuse most of the new java developers: (borrowed from javaworld) Original author: Tony Sintes public void tricky(Point arg1, Point arg2) { arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; } public static void main(String [] args) { Point pnt1 = new Point(0,0); Point pnt2 = new Point(0,0); System.out.println(\"X: \" + pnt1.x + \" Y: \" +pnt1.y); System.out.println(\"X: \" + pnt2.x + \" Y: \" +pnt2.y); System.out.println(\" \"); tricky(pnt1,pnt2); System.out.println(\"X: \" + pnt1.x + \" Y:\" + pnt1.y); System.out.println(\"X: \" + pnt2.x + \" Y: \" +pnt2.y); } \"Output X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0\" tricky successfully changes the value of pnt1! This would imply that Objects are passed by reference, this is not the case! A correct statement would be: the Object references are passed by value. more from Tony Sintes: The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method. figure 1 http://www.javaworld.com/javaworld/javaqa/2000-05/images/03-qa-0512-pass2b.gif Conclusion or a long story short: Java passes it parameters by value \"by value\" is the only way in java to pass a parameter to a method using methods from the object given as parameter will alter the object as the references point to the original objects. (if that method itself alters some values) useful links: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html http://www.ibm.com/developerworks/java/library/j-passbyval/ http://www.ibm.com/developerworks/library/j-praxis/pr1.html http://javadude.com/articles/passbyvalue.htm "} {"user":"370","questionId":2027,"creationDate":"2008-08-05T09:10:58Z","answerId":2033,"type":"answer","body":"by value is slower than by reference since the system has to copy the parameter used for input only by reference faster since only a pointer is passed used for input and output can be very dangerous if used in conjunction with global variables "} {"user":"137","tags":["svn"],"questionId":2034,"creationDate":"2008-08-05T09:11:54Z","title":"What do the result codes in SVN mean?","acceptedAnswerId":2036,"type":"question","body":"What do the result codes in SVN mean? I need a quick reference. "} {"user":"137","questionId":2034,"creationDate":"2008-08-05T09:12:29Z","answerId":2036,"type":"answer","body":"For additional details see the SVNBook: \"Status of working copy files and directories\". The common statuses: U: Working file was updated G: Changes on the repo were automatically merged into the working copy M: Working copy is modified C: This file conflicts with the version in the repo ?: This file is not under version control !: This file is under version control but is missing or incomplete A: This file will be added to version control (after commit) A+: This file will be moved (after commit) D: This file will be deleted (after commit) S: This signifies that the file or directory has been switched from the path of the rest of the working copy (using svn switch) to a branch I: Ignored X: External definition ~: Type changed R: Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place. L : Item is locked E: Item existed, as it would have been created, by an svn update. "} {"user":"269","tags":["svn","version-control","branch","branching-and-merging"],"questionId":2041,"creationDate":"2008-08-05T09:25:29Z","title":"How do I create a branch in SVN?","acceptedAnswerId":2310,"type":"question","body":"How do I create a branch in SVN? "} {"user":"269","questionId":2041,"creationDate":"2008-08-05T09:25:40Z","answerId":2042,"type":"answer","body":"Subversion makes it easy (some think too easy) to create a new branch using the svn copy command. $ svn copy svn+ssh://host.example.com/repos/project/trunk \\ svn+ssh://host.example.com/repos/project/branches/NAME_OF_BRANCH \\ -m \"Creating a branch of project\" "} {"user":"369","tags":["windows","delphi","winapi","dll"],"questionId":2043,"creationDate":"2008-08-05T09:34:49Z","title":"Can a Windows dll retrieve its own filename?","acceptedAnswerId":2044,"type":"question","body":"A Windows exe file has access to the command string which invoked it, including its path and filename. eg. C:\\MyApp\\MyApp.exe --help. But this is not so for a dll invoked via LoadLibrary. Does anyone know of a way for a dll to find out what its path and filename is? Specifically I'm interested in a Delphi solution, but I suspect that the answer would be pretty much the same for any language. "} {"user":"91","questionId":2043,"creationDate":"2008-08-05T09:37:13Z","answerId":2044,"type":"answer","body":"I think you're looking for GetModuleFileName. http://www.swissdelphicenter.ch/torry/showcode.php?id=143: { If you are working on a DLL and are interested in the filename of the DLL rather than the filename of the application, then you can use this function: } function GetModuleName: string; var szFileName: array[0..MAX_PATH] of Char; begin FillChar(szFileName, SizeOf(szFileName), #0); GetModuleFileName(hInstance, szFileName, MAX_PATH); Result := szFileName; end; Untested though, been some time since I worked with Delphi :) "} {"user":"372","tags":["sql-server","unit-testing","tdd"],"questionId":2046,"creationDate":"2008-08-05T09:43:01Z","title":"How do I unit test persistence?","acceptedAnswerId":7641,"type":"question","body":"As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database. I know that technically this would be an integration test (not a unit test), but I want to find out the best strategies for the following: Testing queries. Testing inserts. How do I know that the insert that has gone wrong if it fails? I can test it by inserting and then querying, but how can I know that the query wasn't wrong? Testing updates and deletes -- same as testing inserts What are the best practices for doing these? Regarding testing SQL: I am aware that this could be done, but if I use an O/R Mapper like NHibernate, it attaches some naming warts in the aliases used for the output queries, and as that is somewhat unpredictable I'm not sure I could test for that. Should I just, abandon everything and simply trust NHibernate? I'm not sure that's prudent. "} {"user":"358","questionId":1535,"creationDate":"2008-08-05T09:43:55Z","answerId":2047,"type":"answer","body":"This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on AOP in .NET. The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32) [RetryFor( 10.Hours() )] public void DeleteArchive() { //.. code to just delete the archive } "} {"user":"298","tags":["rss"],"questionId":2048,"creationDate":"2008-08-05T09:45:41Z","title":"Monitor a specific RSS","acceptedAnswerId":2080,"type":"question","body":"For all the RSS feeds I subscribe to I use Google Reader, which I love. I do however have a couple of specific RSS feeds that I'd like to be notified of as soon as they get updated (say, for example, an RSS feed for a forum I like to monitor and respond to as quickly as possible). Are there any tools out there for this kind of monitoring which also have some kind of alert functionality (for example, a prompt window)? I've tried Simbolic RSS Alert but I found it a bit buggy and couldn't get it to alert me as often as I liked. Suggestions? Or perhaps a different experience with Simbolic? "} {"user":"266","questionId":2046,"creationDate":"2008-08-05T09:47:41Z","answerId":2049,"type":"answer","body":"You do the unit testing by mocking out the database connection. This way, you can build scenarios where specific queries in the flow of a method call succeed or fail. I usually build my mock expectations so that the actual query text is ignored, because I really want to test the fault tolerance of the method and how it handles itself -- the specifics of the SQL are irrelevant to that end. Obviously this means your test won't actually verify that the method works, because the SQL may be wrong. This is where integration tests kick in. For that, I expect someone else will have a more thorough answer, as I'm just beginning to get to grips with those myself. "} {"user":"200","questionId":1949,"creationDate":"2008-08-05T09:57:03Z","answerId":2050,"type":"answer","body":"In my experience with LINQ to SQL and LINQ to Entities a DataContext is synonymous to a connection to the database. So if you were to use multiple data stores you would need to use multiple DataContexts. My gut reaction is you wouldn't notice to much of a slow down with a DataContext that encompasses a large number of tables. If you did however you could always split the database logically at points where you can isolate tables that don't have any relationship to other sets of tables and create multiple contexts. "} {"user":"188","questionId":2027,"creationDate":"2008-08-05T10:00:46Z","answerId":2051,"type":"answer","body":"Don't forget there is also pass by name, and pass by value-result. Pass by value-result is similar to pass by value, with the added aspect that the value is set in the original variable that was passed as the parameter. It can, to some extent, avoid interference with global variables. It is apparently better in partitioned memory, where a pass by reference could cause a page fault (Reference). Pass by name means that the values are only calculated when they are actually used, rather than at the start of the procedure. Algol used pass-by-name, but an interesting side effect is that is it very difficult to write a swap procedure (Reference). Also, the expression passed by name is re-evaluated each time it is accessed, which can also have side effects. "} {"user":"188","questionId":2048,"creationDate":"2008-08-05T10:05:07Z","answerId":2054,"type":"answer","body":"RSS isn't \"push\", which means that you need to have something that polls the website. It's much less traffic than getting the whole site or front page (for instance, you can say \"Give me all articles newer than the last time I asked\"), but it's traffic nonetheless. It's generally understood you shouldn't have a refresh of more than 30 minutes in an automated client. (Citation required). Having said that, you may find a client which allows you to set a more frequent refresh. "} {"user":"358","tags":["design-patterns","model-view-controller","user-interface","mvp","glossary"],"questionId":2056,"creationDate":"2008-08-05T10:06:33Z","title":"What are MVP and MVC and what is the difference?","acceptedAnswerId":101561,"type":"question","body":"When looking beyond the RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called Model-View-Controller, Model-View-Presenter and Model-View-ViewModel. My question has three parts to it: What issues do these patterns address? How are they similar? How are they different? "} {"user":"200","questionId":2048,"creationDate":"2008-08-05T10:06:38Z","answerId":2057,"type":"answer","body":"I've used Pingie in the past to send me an SMS when a new items appears in an RSS feed. Perhaps that would be useful for you if you have a cell phone text messaging plan. "} {"user":"371","questionId":1010,"creationDate":"2008-08-05T10:07:51Z","answerId":2058,"type":"answer","body":"I enabled compression following similar articles to those posted above. The key to accessing the ViewState before the application sends it was overriding this method; protected override void SavePageStateToPersistenceMedium(object viewState) You can call the base method within this override and then add whatever additional logic you require to handle the ViewState. "} {"user":"269","questionId":2048,"creationDate":"2008-08-05T10:15:37Z","answerId":2064,"type":"answer","body":"RSS2mail is a simple python script which I used extensively a few years back. As Matthew stated you really shouldn't bother an RSS feed more than the producer allows but you can use http headers to check for changes in a very light way which is something rss2email does quite well. "} {"user":"259","questionId":2046,"creationDate":"2008-08-05T10:19:08Z","answerId":2066,"type":"answer","body":"I would also mock the database, and check that the queries are what you expected. There is the risk that the test checks the wrong sql, but this would be detected in the integration tests "} {"user":"364","questionId":2056,"creationDate":"2008-08-05T10:20:20Z","answerId":2067,"type":"answer","body":"Both of these frameworks aim to seperate concerns - for instance, interaction with a data source (model), application logic (or turning this data into useful information) (Controller/Presenter) and display code (View). In some cases the model can also be used to turn a data source into a higher level abstraction as well. A good example of this is the MVC Storefront project. There is a discussion here regarding the differences between MVC vs MVP. The distinction made is that in an MVC application traditionally has the view and the controller interact with the model, but not with each other. MVP designs have the Presenter access the model and interact with the view. Having said that, ASP.NET MVC is by these definitions an MVP framework because the Controller accesses the Model to populate the View which is meant to have no logic (just displays the variables provided by the Controller). To perhaps get an idea of the ASP.NET MVC distinction from MVP, check out this MIX presentation by Scott Hanselman. "} {"user":"372","questionId":2056,"creationDate":"2008-08-05T10:21:13Z","answerId":2068,"type":"answer","body":"I blogged about this a while back, quoting on Todd Snyder's excellent post on the difference between the two: Here are the key differences between the patterns: MVP Pattern View is more loosely coupled to the model. The presenter is responsible for binding the model to the view. Easier to unit test because interaction with the view is through an interface Usually view to presenter map one to one. Complex views may have multi presenters. MVC Pattern Controller are based on behaviors and can be shared across views Can be responsible for determining which view to display It is the best explanation on the web I could find. "} {"user":"307","questionId":2056,"creationDate":"2008-08-05T10:22:55Z","answerId":2069,"type":"answer","body":" MVP = Model-View-Presenter MVC = Model-View-Controller Both presentation patterns. They separate the dependencies between a Model (think Domain objects), your screen/web page (the View), and how your UI is supposed to behave (Presenter/Controller) They are fairly similar in concept, folks initialize the Presenter/Controller differently depending on taste. A great article on the differences is here. Most notable is that MVC pattern has the Model updating the View. "} {"user":"377","questionId":2048,"creationDate":"2008-08-05T10:24:08Z","answerId":2070,"type":"answer","body":"You could always knock something up yourself... I've done it in the past and it really isn't too difficult a job to write an RSS parser. Of course, as others have mentioned, there's an etiquette question as to how much of the website's valuable bandwidth you want to hog for yourself in RSS request traffic. That's a matter for your own conscience. ;) "} {"user":"198","questionId":2046,"creationDate":"2008-08-05T10:29:42Z","answerId":2073,"type":"answer","body":"The problem I experienced when unit testing persistence, especially without an ORM and thus mocking your database (connection), is that you don't really know if your queries succeed. It could be that you your queries are specifically designed for a particular database version and only succeed with that version. You'll never find that out if you mock your database. So in my opinion, unit testing persistence is only of limited use. You should always add tests running against the targeted database. "} {"user":"383","questionId":2048,"creationDate":"2008-08-05T10:50:35Z","answerId":2080,"type":"answer","body":"If you have access to Microsoft Outlook 2007 or Thunderbird, these email clients allow you to add RSS feeds in the same way you would add an email account. I use Google Reader generally but when I want to keep up-to-date with something specific, I add the RSS feed to Outlook and it arrives in my inbox as if it was an email. "} {"user":"95","questionId":14,"creationDate":"2008-08-05T11:01:47Z","answerId":2086,"type":"answer","body":"Some examples: Round(1.5) = 2 Round(2.5) = 2 Round(1.5, MidpointRounding.AwayFromZero) = 2 Round(2.5, MidpointRounding.AwayFromZero) = 3 Round(1.55, 1) = 1.6 Round(1.65, 1) = 1.6 Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6 Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7 Truncate(2.10) = 2 Truncate(2.00) = 2 Truncate(1.90) = 1 Truncate(1.80) = 1 "} {"user":"bill","tags":["java","testing","coldfusion","code-coverage"],"questionId":2092,"creationDate":"2008-08-05T11:15:16Z","title":"How to get started \"writing\" a code coverage tool?","type":"question","body":"Looking for books or other references that discuss actually \"how\" to write a code coverage tool in Java; some of the various techniques or tricks - source vs. byte code instrumentation. This is for a scripting language that generates java byte code under the hood. "} {"user":"266","questionId":2046,"creationDate":"2008-08-05T11:20:38Z","answerId":2096,"type":"answer","body":"For NHibernate, I'd definitely advocate just mocking out the NHibernate API for unit tests -- trust the library to do the right thing. If you want to ensure that the data actually goes to the DB, do an integration test. "} {"user":"230","questionId":2046,"creationDate":"2008-08-05T11:27:08Z","answerId":2099,"type":"answer","body":"Technically unit tests of persistance are not Unit tests they are Integration tests. With C# using mbUnit, you simply use the SqlRestoreInfo and RollBack attributes [TestFixture] [SqlRestoreInfo(, ,] public class Tests { [SetUp] public void Setup() { } [Test] [RollBack] public void TEST() { //test insert. } } The same can be done in NUnit, excpet the attribute names differ slighty. As for checking if your query was succeful, you normally need to follow it with a second query to see if the database has been changed as you expect. "} {"user":"369","questionId":1329,"creationDate":"2008-08-05T11:35:58Z","answerId":2114,"type":"answer","body":"I've been using Copy Handler. The nicest thing about it is that it queues up its jobs like a download manager. It has a shell extension so you can either rightclick drag, or just set copy with copyhandler as the default action. "} {"user":"389","questionId":1329,"creationDate":"2008-08-05T11:44:29Z","answerId":2118,"type":"answer","body":"I built myself a PC with 4GB RAM, dual core 1.8GHz 40GB PATA drive primary, and 250GB SATA drive secondary, and installed Windows Vista Business Edition. When I had to copy 120GB of data from my old PATA disk, Vista failed miserably and kept crashing. I definitely recommend Teracopy Free Edition. "} {"user":"383","tags":["sql","sql-server"],"questionId":2120,"creationDate":"2008-08-05T11:49:11Z","title":"Convert HashBytes to VarChar","acceptedAnswerId":2382,"type":"question","body":"I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command: SELECT HashBytes('MD5', 'HelloWorld') However, this returns a VarBinary instead of a VarChar value. If I attempt to convert 0x68E109F0F40CA72A15E05CC22786F8E6 into a VarChar I get há ðô§*à\\Â'†øæ instead of 68E109F0F40CA72A15E05CC22786F8E6. Is there any SQL-based solution? Yes "} {"user":"193","tags":["html","checkbox"],"questionId":2123,"creationDate":"2008-08-05T11:51:16Z","title":"How do I make a checkbox toggle from clicking on the text label as well?","acceptedAnswerId":2223,"type":"question","body":"Checkboxes in HTML forms don't have implicit labels with them. Adding an explicit label (some text) next to it doesn't toggle the checkbox. How do I make a checkbox toggle from clicking on the text label as well? "} {"user":"120","questionId":1329,"creationDate":"2008-08-05T11:54:16Z","answerId":2126,"type":"answer","body":"I would definitely prefer: 1) Teracopy - GUI based, replaces the default Windows copy/move UI and adds itself to context menu. Basic version is free (for home use I guess). 2) Robocopy - CLI based, useful when scripting. Free tool from MS and is included in Vista/Windows 2008. MS Technet has a GUI for robocopy as well - useful to create statements that you can later embed in scripts or on the command prompt. PS: I know these have been already suggested here and I would have voted on them, if I could. "} {"user":"383","questionId":2123,"creationDate":"2008-08-05T12:00:03Z","answerId":2133,"type":"answer","body":"If you correctly markup your HTML code, there is no need for javascript. The following code will allow the user to click on the label text to tick the checkbox. The for attribute on the label element links to the id attribute on the input element and the browser does the rest. This has been testing to work in: IE6 IE7 Firefox "} {"user":"380","tags":[".net","optimization","frameworks","performance"],"questionId":2134,"creationDate":"2008-08-05T12:00:28Z","title":"Do sealed classes really offer performance Benefits?","acceptedAnswerId":2183,"type":"question","body":"I have come across a lot of optimization tips which say that you should mark your classes as sealed to get extra performance benefits. I ran some tests to check the performance differential and found none. Am I doing something wrong? Am I missing the case where sealed classes will give better results? Has anyone run tests and seen a difference? Help me learn :) "} {"user":"373","tags":[".net","linq",".net-3.5",".net-2.0","clr"],"questionId":2138,"creationDate":"2008-08-05T12:03:10Z","title":"LINQ on the .NET 2.0 Runtime","acceptedAnswerId":2147,"type":"question","body":"Can a LINQ enabled app run on a machine that only has the .NET 2.0 runtime installed? In theory, LINQ is nothing more than syntactic sugar, and the resulting IL code should look the same as it would have in .NET 2.0. How can I write LINQ without using the .NET 3.5 libraries? Will it run on .NET 2.0? "} {"user":"371","questionId":145,"creationDate":"2008-08-05T12:04:41Z","answerId":2142,"type":"answer","body":"The .Net 2.0 framework namespace System.IO.Compression supports GZip and Deflate algorithms. Here are two methods that compress and decompress a byte stream which you can get from your file object. You can subsitute GZipStream for DefaultStream in the methods below to use that algorithm. This still leaves the problem of handling files compressed with different algorithms though. public static byte[] Compress(byte[] data) { MemoryStream output = new MemoryStream(); GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true); gzip.Write(data, 0, data.Length); gzip.Close(); return output.ToArray(); } public static byte[] Decompress(byte[] data) { MemoryStream input = new MemoryStream(); input.Write(data, 0, data.Length); input.Position = 0; GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true); MemoryStream output = new MemoryStream(); byte[] buff = new byte[64]; int read = -1; read = gzip.Read(buff, 0, buff.Length); while (read > 0) { output.Write(buff, 0, read); read = gzip.Read(buff, 0, buff.Length); } gzip.Close(); return output.ToArray(); } "} {"user":"372","questionId":2138,"creationDate":"2008-08-05T12:07:39Z","answerId":2146,"type":"answer","body":"No, because while you thought LINQ is really just syntactic sugar, it actually heavily used expression trees -- a feature absent in .NET 2.0. That being said .NET 3.5 only builds up on top of .NET 2.0, and that's the reason why the IL doesn't look \"different\" or \"special\". I do not see a reason why you shouldn't just install the .NET 3.5 Framework. Everything .NET 2.0 will work fine on it, promise :) "} {"user":"91","questionId":2138,"creationDate":"2008-08-05T12:07:41Z","answerId":2147,"type":"answer","body":"There are some \"Hacks\" that involve using a System.Core.dll from the 3.5 Framework to make it run with .net 2.0, but personally I would not want use such a somewhat shaky foundation. See here: LINQ support on .NET 2.0 Create a new console application Keep only System and System.Core as referenced assemblies Set Copy Local to true for System.Core, because it does not exist in .NET 2.0 Use a LINQ query in the Main method. For example the one below. Build Copy all the bin output to a machine where only .NET 2.0 is installed Run (Requires .net 2.0 SP1 and I have no idea if bundling the System.Core.dll violates the EULA) "} {"user":"200","questionId":2138,"creationDate":"2008-08-05T12:07:46Z","answerId":2148,"type":"answer","body":"In theory yes, provided you distribute the LINQ specific assemblies and any dependencies. However that is in violation of Microsoft's licensing. Scott Hanselman wrote a blog post about Deploying ASP.NET MVC on ASP.NET 2.0 which is similar to what you are wanting to do. "} {"user":"383","tags":["c#","asp.net-mvc","visual-studio"],"questionId":2154,"creationDate":"2008-08-05T12:13:40Z","title":"Developing for ASP.NET-MVC without Visual Studio","acceptedAnswerId":2335,"type":"question","body":"Instead of writing my ASP.NET C# applications in Visual Studio, I used my favorite text editor UltraEdit32. Is there anyway I can implement MVC without the use of VS? "} {"user":"371","tags":["asp.net"],"questionId":2155,"creationDate":"2008-08-05T12:13:40Z","title":"How do I define custom web.config sections with potential child elements and attributes for the properties?","acceptedAnswerId":2928,"type":"question","body":"The web applications I develop often require co-dependant configuration settings and there are also settings that have to change as we move between each of our environments. All our settings are currently simple key value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment. What's the best way to create custom config sections and are there any special considerations to make when retrieving the values? "} {"user":"296","questionId":2138,"creationDate":"2008-08-05T12:14:33Z","answerId":2156,"type":"answer","body":"As far as I know the LINQ library is only available since the framework 3.0. If you want to use something similar in the framework 2.0, you would need to rewritte it yourself :) or find a similar third-party library. I only found a bit of information here but it didn't convinced me either. "} {"user":"340","tags":["java","swing","jbutton"],"questionId":2158,"creationDate":"2008-08-05T12:15:08Z","title":"Creating a custom button in Java","acceptedAnswerId":2245,"type":"question","body":"Is there a way to create a JButton with your own button graphic and not just with an image inside the button? If not, is there another way to create a custom button in java? "} {"user":"136","questionId":2123,"creationDate":"2008-08-05T12:25:16Z","answerId":2177,"type":"answer","body":"You can wrap your checkbox in the label: "} {"user":"200","questionId":2155,"creationDate":"2008-08-05T12:25:20Z","answerId":2178,"type":"answer","body":"You can accomplish this with Section Handlers. There is a basic overview of how to write one at http://www.codeproject.com/KB/aspnet/ConfigSections.aspx however it refers to app.config which would be pretty much the same as writing one for use in web.config. This will allow you to essentially have your own XML tree in the config file and do some more advanced configuration. "} {"user":"200","questionId":2154,"creationDate":"2008-08-05T12:27:35Z","answerId":2179,"type":"answer","body":"Assuming you have the correct assemblies and a C# compiler you in theory can use whatever you want to edit the code and then just run the compiler by hand or using a build script. That being said it is a real pain doing .NET development without Visual Studio/SharpEdit/Monodevelop in my opinion. "} {"user":"383","questionId":2123,"creationDate":"2008-08-05T12:28:32Z","answerId":2180,"type":"answer","body":"Ronnie, If you wanted to enclose the label text and checkbox inside a wrapper element, you could do the following: "} {"user":"200","questionId":2158,"creationDate":"2008-08-05T12:30:34Z","answerId":2181,"type":"answer","body":"I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit javax.swing.AbstractButton and create your own. Should be pretty simple to wire something together with their existing framework. "} {"user":"267","questionId":2134,"creationDate":"2008-08-05T12:32:40Z","answerId":2183,"type":"answer","body":"The JITter will sometimes use non-virtual calls to methods in sealed classes since there is no way they can be extended further. There are complex rules regarding calling type, virtual/nonvirtual, and I don't know them all so I can't really outline them for you, but if you google for sealed classes and virtual methods you might find some articles on the topic. Note that any kind of performance benefit you would obtain from this level of optimization should be regarded as last-resort, always optimize on the algorithmic level before you optimize on the code-level. Here's one link mentioning this: Rambling on the sealed keyword "} {"user":"193","questionId":2123,"creationDate":"2008-08-05T12:34:27Z","answerId":2184,"type":"answer","body":"Wrapping with the label still doesn't allow clicking 'anywhere in the box' - still just on the text! This does the job for me:
Date of birth entry must be completed
but unfortunately has lots of javascript that is effectively toggling twice. "} {"user":"34","questionId":2134,"creationDate":"2008-08-05T12:37:07Z","answerId":2189,"type":"answer","body":"Sealed classes should provide a performance improvement. Since a sealed class cannot be derived, any virtual members can be turned into non-virtual members. Of course, we're talking really small gains. I wouldn't mark a class as sealed just to get a performance improvement unless profiling revealed it to be a problem. "} {"user":"120","questionId":2134,"creationDate":"2008-08-05T12:40:10Z","answerId":2195,"type":"answer","body":"@Vaibhav, what kind of tests did you execute to measure performance? I guess one would have to use Rotor and to drill into CLI and understand how a sealed class would improve performance. SSCLI (Rotor) SSCLI: Shared Source Common Language Infrastructure The Common Language Infrastructure (CLI) is the ECMA standard that describes the core of the .NET Framework. The Shared Source CLI (SSCLI), also known as Rotor, is a compressed archive of the source code to a working implementation of the ECMA CLI and the ECMA C# language specification, technologies at the heart of Microsoft’s .NET architecture. "} {"user":"192","tags":["asp.net","ajax","web-controls"],"questionId":2196,"creationDate":"2008-08-05T12:40:30Z","title":"Easy way to AJAX WebControls","acceptedAnswerId":2373,"type":"question","body":"I've got a web application that I'm trying to optimise. Some of the controls are hidden in dialog-style DIVs, so I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly Literal-based (various menus and widgets), but when I have what I call \"dirty\" controls - ones that write extensive information to the ViewState, put tons of CSS or script on the page, require lots of references etc - these are seemingly impossible to move \"out of page\", especially considering how ASP.NET will react on postback. I was considering some kind of step where I override Render, find markers for the bits I want to move out and put AJAX placeholders in there, but not only does the server overhead seem extreme, it also feels like a complete hack. Besides, the key element here are the dialog boxes that contain forms with validation controls on them, and I can't imagine how I would move the controls and their required scripts. In my fevered imagination, I want to do this: AJAXifier.AJAXify(ctlEditForm); Sadly, I know this is a dream. How close can I really get to a quick-and-easy AJAXification without causing too much load on the server? "} {"user":"72","questionId":2041,"creationDate":"2008-08-05T12:40:31Z","answerId":2197,"type":"answer","body":"Normally you'd copy it to svn+ssh://host.example.com/repos/project/branches/mybranch so that you can keep several branches in the repository, but your syntax is valid. Here's some advice on how to set up your repository layout. "} {"user":"287","questionId":2041,"creationDate":"2008-08-05T12:46:40Z","answerId":2207,"type":"answer","body":"If you even plan on merging your branch, I highly suggest you look at this: Svnmerge.py I hear Subversion 1.5 builds more of the merge tracking in, I have no experience with that. My project is on 1.4.x and svnmerge.py is a life saver! "} {"user":"396","tags":["c#","asp.net",".net","master-pages"],"questionId":2209,"creationDate":"2008-08-05T12:46:45Z","title":"How can I change the background of a masterpage from the code behind of a content page?","acceptedAnswerId":2233,"type":"question","body":"I specifically want to add the style of background-color to the tag of a master page, from the code behind (C#) of a content page that uses that master page. I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme. I have a solution below: I'm looking for something more like: Master.Attributes.Add(\"style\", \"background-color: 2e6095\"); Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the background-color for the tag of the page. "} {"user":"246","questionId":2158,"creationDate":"2008-08-05T12:47:17Z","answerId":2210,"type":"answer","body":"You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this: try { SynthLookAndFeel synth = new SynthLookAndFeel(); Class aClass = MainFrame.class; InputStream stream = aClass.getResourceAsStream(\"\\\\default.xml\"); if (stream == null) { System.err.println(\"Missing configuration file\"); System.exit(-1); } synth.load(stream, aClass); UIManager.setLookAndFeel(synth); } catch (ParseException pe) { System.err.println(\"Bad configuration file\"); pe.printStackTrace(); System.exit(-2); } catch (UnsupportedLookAndFeelException ulfe) { System.err.println(\"Old JRE in use. Get a new one\"); System.exit(-3); } From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file. The xml file might look like this: The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to \"dirt\"). And a couple of useful links: http://javadesktop.org/articles/synth/ http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html "} {"user":"383","questionId":2209,"creationDate":"2008-08-05T12:49:29Z","answerId":2212,"type":"answer","body":"I believe you are talking about a content management system. The way I have delt with this situation in the past is to either: Allow a page/content to define an extra custom stylesheet or Allow a page/content to define inline style tags "} {"user":"72","questionId":1453,"creationDate":"2008-08-05T12:49:44Z","answerId":2213,"type":"answer","body":"This will allow you to pass a weight of 0 and still work properly. Notice the === operator, this checks to see if weight matches \"null\" in both value and type (as opposed to ==, which is just value, so 0 == null == false). PHP: public function createShipment($startZip, $endZip, $weight=null){ if ($weight === null) $weight = $this->getDefaultWeight(); } "} {"user":"395","tags":["c#",".net","testing","tdd","bdd"],"questionId":2214,"creationDate":"2008-08-05T12:50:15Z","title":"What's the best way to implement BDD/TDD in .NET 2.0?","acceptedAnswerId":3443,"type":"question","body":"I'm looking to add a testing suite to my application, however I can't move to the newer testing frameworks for .NET 3.5. Does anyone have a suggestion about good testing frameworks to use? "} {"user":"bill","questionId":2092,"creationDate":"2008-08-05T12:50:59Z","answerId":2216,"type":"answer","body":"Thxm, Mc! http://asm.objectweb.org/ is another one. Excellent documentation on byte code instrumentation, but nothing \"directly\" aimed at writing a coverage tool - just some hints or ideas. "} {"user":"227","questionId":2155,"creationDate":"2008-08-05T12:51:16Z","answerId":2219,"type":"answer","body":"Quick'n Dirty: First create your ConfigurationSection and ConfigurationElement classes: public class MyStuffSection : ConfigurationSection { ConfigurationProperty _MyStuffElement; public MyStuffSection() { _MyStuffElement = new ConfigurationProperty(\"MyStuff\", typeof(MyStuffElement), null); this.Properties.Add(_MyStuffElement); } public MyStuffElement MyStuff { get { return this[_MyStuffElement] as MyStuffElement; } } } public class MyStuffElement : ConfigurationElement { ConfigurationProperty _SomeStuff; public MyStuffElement() { _SomeStuff = new ConfigurationProperty(\"SomeStuff\", typeof(string), \"\"); this.Properties.Add(_SomeStuff); } public string SomeStuff { get { return (String)this[_SomeStuff]; } } } Then let the framework know how to handle your configuration classes in web.config:
... And actually add your own section below: Then you can use it in your code thus: MyWeb.Configuration.MyStuffSection configSection = ConfigurationManager.GetSection(\"MyStuffSection\") as MyWeb.Configuration.MyStuffSection; if (configSection != null && configSection.MyStuff != null) { Response.Write(configSection.MyStuff.SomeStuff); } "} {"user":"17","questionId":2214,"creationDate":"2008-08-05T12:51:47Z","answerId":2220,"type":"answer","body":"NUnit is always a favorite of mine. However if you are using TFS as your source control I suggest you stick with the Microsoft Stack. "} {"user":"266","tags":["flex","eclipse","unit-testing","build-automation","cairngorm"],"questionId":2222,"creationDate":"2008-08-05T12:52:42Z","title":"How can I unit test Flex applications from within the IDE or a build script?","acceptedAnswerId":8753,"type":"question","body":"I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of FlexUnit but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist? Also, are there any other resources on how to do Flex development \"the right way\" besides the Cairngorm microarchitecture example? "} {"user":"48","questionId":2123,"creationDate":"2008-08-05T12:52:50Z","answerId":2223,"type":"answer","body":"Set the CSS display property for the label to be a block element and use that instead of your div - it keeps the semantic meaning of a label while allowing whatever styling you like. For example: label { width: 100px; height: 100px; display: block; background-color: #e0e0ff; } "} {"user":"304","questionId":2158,"creationDate":"2008-08-05T12:53:35Z","answerId":2225,"type":"answer","body":"Yes, this is possible. One of the main pros for using Swing is the ease with which the abstract controls can be created and manipulates. Here is a quick and dirty way to extend the existing JButton class to draw a circle to the right of the text. package test; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JFrame; public class MyButton extends JButton { private static final long serialVersionUID = 1L; private Color circleColor = Color.BLACK; public MyButton(String label) { super(label); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Dimension originalSize = super.getPreferredSize(); int gap = (int) (originalSize.height * 0.2); int x = originalSize.width + gap; int y = gap; int diameter = originalSize.height - (gap * 2); g.setColor(circleColor); g.fillOval(x, y, diameter, diameter); } @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.width += size.height; return size; } /*Test the button*/ public static void main(String[] args) { MyButton button = new MyButton(\"Hello, World!\"); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); Container contentPane = frame.getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(button); frame.setVisible(true); } } Note that by overriding paintComponent that the contents of the button can be changed, but that the border is painted by the paintBorder method. The getPreferredSize method also needs to be managed in order to dynamically support changes to the content. Care needs to be taken when measuring font metrics and image dimensions. For creating a control that you can rely on, the above code is not the correct approach. Dimensions and colours are dynamic in Swing and are dependent on the look and feel being used. Even the default Metal look has changed across JRE versions. It would be better to implement AbstractButton and conform to the guidelines set out by the Swing API. A good starting point is to look at the javax.swing.LookAndFeel and javax.swing.UIManager classes. http://docs.oracle.com/javase/8/docs/api/javax/swing/LookAndFeel.html http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html Understanding the anatomy of LookAndFeel is useful for writing controls: Creating a Custom Look and Feel "} {"user":"266","questionId":2214,"creationDate":"2008-08-05T12:54:20Z","answerId":2228,"type":"answer","body":"For a Mock Object library, I've found the BSD-licensed Rhino.Mocks to be rather pleasing. "} {"user":"25","tags":["ruby","shell","interop"],"questionId":2232,"creationDate":"2008-08-05T12:56:52Z","title":"Calling shell commands from Ruby","acceptedAnswerId":2400,"type":"question","body":"How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby? "} {"user":"384","questionId":2209,"creationDate":"2008-08-05T12:56:54Z","answerId":2233,"type":"answer","body":"What I would do for the particular case is: i. Define the body as a server side control ii. In your content aspx page, register the MasterPage with the register: <% MasterPageFile=\"...\" %> iii. In the Content Page, you can now simply use Master.FindControl(\"masterpageBody\") and have access to the control. Now, you can change whatever properties/style that you like! "} {"user":"40","questionId":2158,"creationDate":"2008-08-05T13:03:43Z","answerId":2245,"type":"answer","body":"When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you. Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value. Here are the basic steps: Create a class that extends JComponent Call parent constructor super() in your constructors Make sure you class implements MouseListener Put this in the constructor: enableInputMethods(true); addMouseListener(this); Override these methods: public Dimension getPreferredSize() public Dimension getMinimumSize() public Dimension getMaximumSize() Override this method: public void paintComponent(Graphics g) The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different. And finally, the source code. In case I missed anything. "} {"user":"193","questionId":2214,"creationDate":"2008-08-05T13:03:45Z","answerId":2246,"type":"answer","body":"NUnit is available at http://www.nunit.org I would suggest this even when working on the MS stack - the support for non-MS frameworks is happening in the MVC previews which shows a definite movement in the right direction to allow us all to customise our stacks to fit. "} {"user":"383","tags":["c#","dataset","datatable"],"questionId":2250,"creationDate":"2008-08-05T13:07:40Z","title":"Datatable vs Dataset","acceptedAnswerId":2258,"type":"question","body":"I currently use a DataTable to get results from a database which I can use in my code. However, many example on the web show using a DataSet instead and accessing the table(s) through the collections method. Is there any advantage, performance wise or otherwise, of using DataSets or DataTables as a storage method for SQL results? "} {"user":"34","questionId":2250,"creationDate":"2008-08-05T13:10:26Z","answerId":2254,"type":"answer","body":"in 1.x there used to be things DataTables couldn't do which DataSets could (don't remember exactly what). All that was changed in 2.x. My guess is that's why a lot of examples still use DataSets. DataTables should be quicker as they are more lightweight. If you're only pulling a single resultset, its your best choice between the two. "} {"user":"379","tags":["c#","c++","data-structures"],"questionId":2256,"creationDate":"2008-08-05T13:11:14Z","title":"Mapping Stream data to data structures in C#","acceptedAnswerId":2490,"type":"question","body":"Is there a way of mapping data collected on a stream or array to a data structure or vice-versa? In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse) eg: in C++ Mystruct * pMyStrct = (Mystruct*)&SomeDataStream; pMyStrct->Item1 = 25; int iReadData = pMyStrct->Item2; obviously the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy. "} {"user":"377","questionId":2250,"creationDate":"2008-08-05T13:12:15Z","answerId":2258,"type":"answer","body":"It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object. Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the \"wrong\" choice of .NET construct. At least, that's been my experience. "} {"user":"383","tags":["asp.net","url","url-rewriting","url-routing","rewrite"],"questionId":2262,"creationDate":"2008-08-05T13:14:48Z","title":"ASP.NET URL Rewriting","acceptedAnswerId":2268,"type":"question","body":"How do I rewrite URL's in ASP.NET? I would like users to be able to goto http://www.website.com/users/smith instead of http://www.website.com/?user=smith "} {"user":"26","questionId":2250,"creationDate":"2008-08-05T13:15:53Z","answerId":2264,"type":"answer","body":"One feature of the DataSet is that if you can call multiple select statements in your stored procedures, the DataSet will have one DataTable for each. "} {"user":"111","tags":["c#",".net"],"questionId":2267,"creationDate":"2008-08-05T13:17:46Z","title":"How to filter and combine 2 datasets in C#","type":"question","body":"I am building a web page to show a customer what software they purchased and to give them a link to download said software. Unfortunately, the data on what was purchased and the download information are in separate databases so I can't just take care of it with joins in a query. The common item is SKU. I'll be pulling back a list of SKUs from the customer purchases database, and on the download table is a comma delineated list of SKUs associated with that download. My intention, at the moment, is to create from this one datatable to populate a GridView. Any suggestions on how to do this efficiently would be appreciated. If it helps, I can pretty easily pull back the data as a DataSet or a DataReader, if either one would be better for this purpose. "} {"user":"17","questionId":2262,"creationDate":"2008-08-05T13:18:39Z","answerId":2268,"type":"answer","body":"Try the Managed Fusion Url Rewriter and Reverse Proxy: http://urlrewriter.codeplex.com The rule for rewriting this would be: # clean up old rules and forward to new URL RewriteRule ^/?user=(.*) /users/$1 [NC,R=301] # rewrite the rule internally RewriteRule ^/users/(.*) /?user=$1 [NC,L] "} {"user":"156","questionId":1983,"creationDate":"2008-08-05T13:22:43Z","answerId":2277,"type":"answer","body":"From the Python FAQ: Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data. "} {"user":"149","tags":["visual-studio"],"questionId":2279,"creationDate":"2008-08-05T13:24:11Z","title":"Add Custom Tag to Visual Studio Validation","acceptedAnswerId":2314,"type":"question","body":"How can I add rules to Visual Studio (2005 and up) for validating property markup (HTML) for a vendor's proprietary controls? My client uses a control which requires several properties to be set as tags in the aspx file which generates something like 215 validation errors on each build. It's not preventing me from building, but real errors are getting lost in the noise. "} {"user":"402","questionId":2232,"creationDate":"2008-08-05T13:24:16Z","answerId":2280,"type":"answer","body":"I'm definitely not a Ruby expert, but I'll give it a shot: $ irb system \"echo Hi\" Hi => true You should also be able to do things like: cmd = 'ls' system(cmd) "} {"user":"380","questionId":2267,"creationDate":"2008-08-05T13:24:43Z","answerId":2283,"type":"answer","body":"I am thinking off the top of my head here. If you load both as Data Tables in the same Data Sets, and define a relation between the two over SKU, and then run a query on the Data Set which produces the desired result. "} {"user":"307","tags":["language-agnostic","open-source","contribute"],"questionId":2284,"creationDate":"2008-08-05T13:25:29Z","title":"How to contribute code back to an Open Source project?","acceptedAnswerId":2301,"type":"question","body":"If you're following an Open Source project and would like to contribute code changes, what will you need to do? "} {"user":"33","questionId":2284,"creationDate":"2008-08-05T13:26:47Z","answerId":2287,"type":"answer","body":"It depends on the project, how and where it is hosted. The best thing is to find a contact and email them or see if there is a developers mailing list. "} {"user":"396","questionId":2209,"creationDate":"2008-08-05T13:28:01Z","answerId":2291,"type":"answer","body":"This is what I came up with: In the page load function: HtmlGenericControl body = (HtmlGenericControl)Master.FindControl(\"default_body\"); body.Style.Add(HtmlTextWriterStyle.BackgroundColor, \"#2E6095\"); Where default_body = the id of the body tag. "} {"user":"383","questionId":2284,"creationDate":"2008-08-05T13:28:06Z","answerId":2292,"type":"answer","body":"The first thing you should do is contact the main people who run the open source project. Ask them if it is ok to contribute to the code and go from there. Simply writing your improved code and then giving it to them may result in your code being rejected. "} {"user":"225","questionId":2262,"creationDate":"2008-08-05T13:28:32Z","answerId":2293,"type":"answer","body":"Scott Guthrie covers how to do this natively in .Net pretty extensively here. I've used the httpmodule approach and it works well. It's basically what ManagedFusion is doing for you. "} {"user":"195","questionId":2256,"creationDate":"2008-08-05T13:29:07Z","answerId":2294,"type":"answer","body":"if its .net on both sides: think you should use binary serialization and send the byte[] result. trusting your struct to be fully blittable can be trouble. you will pay in some overhead (both cpu and network) but will be safe. "} {"user":"193","tags":["asp-classic","vbscript"],"questionId":2300,"creationDate":"2008-08-05T13:30:46Z","title":"How do I traverse a collection in classic ASP?","acceptedAnswerId":2312,"type":"question","body":"I want to be able to do: For Each thing In things End For CLASSIC ASP - NOT .NET! "} {"user":"25","questionId":2284,"creationDate":"2008-08-05T13:30:58Z","answerId":2301,"type":"answer","body":"I would spend time getting to know the people first. Usually they have a IRC chatroom where everyone idles. Spend sometime getting to know the people, study the code, review the documentation, then if you feel like you are a correct fit for the project, start contributing to bug patches. Don't try to add new features at first. They won't generally be accepted. Also watch this google tech talk about How To Protect Your Open Source Project from Poisonous People. It will teach you what not to do. "} {"user":"383","tags":["asp.net","svn"],"questionId":2308,"creationDate":"2008-08-05T13:38:42Z","title":"ASP.NET Display SVN Revision Number","acceptedAnswerId":2320,"type":"question","body":"I see in the Stack Overflow footer that the SVN Revision number is displayed. Is this automated and if so, how does one implement it in ASP.NET? (Solutions in other languages are acceptable) "} {"user":"193","questionId":2041,"creationDate":"2008-08-05T13:40:20Z","answerId":2310,"type":"answer","body":"Branching in Subversion is facilitated by a very very light and efficient copying facility. Branching and tagging are effectively the same. Just copy a whole folder in the repository to somewhere else in the repository using the svn copy command. Basically this means that it is by convention what copying a folder means - whether it be a backup, tag, branch or whater. Depending upon how you want to think about things (normally depending upon which SCM tool you have used in the past) you need to set up a folder structure within your repository to support your style. Common styles are to have a bunch of folders at the top of your repository called tags, branches, trunk, etc. - that allows you to copy your whole trunk (or sub-sets) into the tags and/or branches folders. If you have more than one project you might want to replicate this kind of structure under each project: It can take a while to get used to the concept - but it works - just make sure you (and your team) are clear on the conventions that you are going to use. It is also a good idea to have a good naming convention - something that tells you why the branch/tag was made and whether it is still appropriate - consider ways of archiving branches that are obsolete. "} {"user":"394","tags":["php","python","ftp","webserver"],"questionId":2311,"creationDate":"2008-08-05T13:40:47Z","title":"File size differences after copying a file to a server vía FTP","acceptedAnswerId":2316,"type":"question","body":"I have created a PHP-script to update a webserver that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp_put. from ftplib import FTP ftpserver = \"myserver\" ftpuser = \"myuser\" ftppass = \"mypwd\" locfile = \"g:/test/style.css\" ftpfile = \"/temp/style.css\" try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit (\"Cannot connect\") f = open (locfile, \"r\") try: ftp.delete (ftpfile) except: pass # ftp.sendcmd (\"TYPE I\") # ftp.storlines(\"STOR %s\" % ftpfile, f) ftp.storbinary(\"STOR %s\" % ftpfile, f) f.close() ftp.dir (ftpfile) ftp.quit() Any suggestions? "} {"user":"307","questionId":2300,"creationDate":"2008-08-05T13:42:15Z","answerId":2312,"type":"answer","body":"Whatever your [things] are need to be written outside of VBScript. In VB6, you can write a Custom Collection class, then you'll need to compile to an ActiveX DLL and register it on your webserver to access it. "} {"user":"106","questionId":2279,"creationDate":"2008-08-05T13:43:27Z","answerId":2314,"type":"answer","body":"Right-click on the Source view of an HTML / ASP page and select \"Formatting and Validation\". Click \"Tag Specific Options\". Expand \"Client HTML Tags\" and select the heading. Click \"New Tag...\". And just fill it in! I wish that I could add custom CSS values as well. "} {"user":"259","questionId":2311,"creationDate":"2008-08-05T13:45:38Z","answerId":2316,"type":"answer","body":"Do you need to open the locfile in binary using rb? f = open (locfile, \"rb\") "} {"user":"17","questionId":2311,"creationDate":"2008-08-05T13:45:47Z","answerId":2317,"type":"answer","body":"Well if you go under the properties of your file in Windows or a *nix environment, you will notice two sizes. One is the sector size, and one is the actual size. The sector size is the number of sectors in bytes that are used up on your hard disk. That is because two files cannot be in the same sector with most modern file systems, so if your file fills up half of the sector the whole sector is marked as filled. So you might be comparing the sector file size to the actual file size on the FTP server or vice versa. "} {"user":"91","questionId":2308,"creationDate":"2008-08-05T13:47:00Z","answerId":2320,"type":"answer","body":"Make sure that the file has svn:keywords \"Rev Id\" and then put $Rev$ somewhere in there. See this question and the answers to it. "} {"user":"390","questionId":2256,"creationDate":"2008-08-05T13:47:23Z","answerId":2322,"type":"answer","body":"If you need to populate each member variable by hand you can generalize it a bit as far as the primitives are concerned by using FormatterServices to retrieve in order the list of variable types associated with an object. I've had to do this in a project where I had a lot of different message types coming off the stream and I definitely didn't want to write the serializer/deserializer for each message. Here's the code I used to generalize the deserialization from a byte[]. public virtual bool SetMessageBytes(byte[] message) { MemberInfo[] members = FormatterServices.GetSerializableMembers(this.GetType()); object[] values = FormatterServices.GetObjectData(this, members); int j = 0; for (int i = 0; i < members.Length; i++) { string[] var = members[i].ToString().Split(new char[] { ' ' }); switch (var[0]) { case \"UInt32\": values[i] = (UInt32)((message[j] << 24) + (message[j + 1] << 16) + (message[j + 2] << 8) + message[j + 3]); j += 4; break; case \"UInt16\": values[i] = (UInt16)((message[j] << 8) + message[j + 1]); j += 2; break; case \"Byte\": values[i] = (byte)message[j++]; break; case \"UInt32[]\": if (values[i] != null) { int len = ((UInt32[])values[i]).Length; byte[] b = new byte[len * 4]; Array.Copy(message, j, b, 0, len * 4); Array.Copy(Utilities.ByteArrayToUInt32Array(b), (UInt32[])values[i], len); j += len * 4; } break; case \"Byte[]\": if (values[i] != null) { int len = ((byte[])values[i]).Length; Array.Copy(message, j, (byte[])(values[i]), 0, len); j += len; } break; default: throw new Exception(\"ByteExtractable::SetMessageBytes Unsupported Type: \" + var[1] + \" is of type \" + var[0]); } } FormatterServices.PopulateObjectMembers(this, members, values); return true; } "} {"user":"51","questionId":2267,"creationDate":"2008-08-05T13:48:19Z","answerId":2324,"type":"answer","body":"As long as the two databases are on the same physical server (assuming MSSQL) and the username/password being used in the connection string has rights to both DBs, then you should be able to perform a join across the two databases. Example: select p.Date, p.Amount, d.SoftwareName, d.DownloadLink from PurchaseDB.dbo.Purchases as p join ProductDB.dbo.Products as d on d.sku = p.sku where p.UserID = 12345 "} {"user":"67","tags":["asp.net","ajax","asp.net-ajax","viewstate"],"questionId":2328,"creationDate":"2008-08-05T13:52:12Z","title":"Tracking state using ASP.NET AJAX / ICallbackEventHandler","acceptedAnswerId":4910,"type":"question","body":"I have a problem with maintaining state in an ASP.NET AJAX page. Short version: I need some way to update the page ViewState after an async callback has been made, to reflect any state changes the server made during the async call. This seems to be a common problem, but I will describe my scenario to help explain: I have a grid-like control which has some JavaScript enhancements - namely, the ability to drag and drop columns and rows. When a column or row is dropped into a new position, an AJAX method is invoked to notify the control server-side and fire a corresponding server-side event (\"OnColumnMoved\" or \"OnRowMoved\"). ASP.NET AJAX calls, by default, send the entire page as the request. That way the page goes through a complete lifecycle, viewstate is persisted and the state of the control is restored before the RaiseCallbackEvent method is invoked. However, since the AJAX call does not update the page, the ViewState reflects the original state of the control, even after the column or row has been moved. So the second time a client-side action occurs, the AJAX request goes to the server and the page & control are built back up again to reflect the first state of the control, not the state after the first column or row was moved. This problem extends to many implications. For example if we have a client-side/AJAX action to add a new item to the grid, and then a row is dragged, the grid is built server-side with one less item than on the client-side. And finally & most seriously for my specific example, the actual data source object we are acting upon is stored in the page ViewState. That was a design decision to allow keeping a stateful copy of the manipulated data which can either be committed to DB after many manipulations or discarded if the user backs out. That is very difficult to change. So, again, I need a way for the page ViewState to be updated on callback after the AJAX method is fired. "} {"user":"137","tags":["osx","textwrangler"],"questionId":2332,"creationDate":"2008-08-05T13:57:05Z","title":"How do I turn on line numbers by default in TextWrangler on the Mac?","acceptedAnswerId":2333,"type":"question","body":"I am fed up having to turn them on every time I open the application. "} {"user":"137","questionId":2332,"creationDate":"2008-08-05T13:57:10Z","answerId":2333,"type":"answer","body":"Go to TextWrangler > Preferences. Choose Text Status Display in the category pane, then check the option \"Show line numbers\" and close the preferences. This should now be on by default when you open existing documents. "} {"user":"140","questionId":2232,"creationDate":"2008-08-05T13:57:47Z","answerId":2334,"type":"answer","body":"You can also use the backtick operators (`), similar to Perl: directoryListing = `ls /` puts directoryListing # prints the contents of the root directory Handy if you need something simple. Which method you want to use depends on exactly what you're trying to accomplish; check the docs for more details about the different methods. "} {"user":"193","questionId":2154,"creationDate":"2008-08-05T13:58:52Z","answerId":2335,"type":"answer","body":"There is nothing VS specific with the MVC framework - it is just a bunch of DLLs that you can use. The wizards in VS just build you a quick-start framework. ASP.NET MVC is \"bin-deployable\" - there is nothing too clever to set up on the server either - just point the wildcard ISAPI filter to ASP.NET "} {"user":"91","questionId":2308,"creationDate":"2008-08-05T14:04:50Z","answerId":2342,"type":"answer","body":"The search seems to be an \"OR\" instead of an \"AND\" :-( If you do a search for ASP.NET SVN on the search bar, you will not find it on Page 6 or so. it definitely should get some refining. "} {"user":"307","questionId":2267,"creationDate":"2008-08-05T14:06:44Z","answerId":2346,"type":"answer","body":"Why not create a Domain object based approach to this problem: public class CustomerDownloadInfo { private string sku; private readonly ICustomer customer; public CustomerDownloadInfo(ICustomer Customer){ customer = Customer; } public void AttachSku(string Sku){ sku = Sku; } public string Sku{ get { return sku; } } public string Link{ get{ // etc... etc... } } } There are a million variations on this, but once you aggregate this information, wouldn't it be easier to present? "} {"user":"193","tags":["arrays","asp-classic","vbscript"],"questionId":2348,"creationDate":"2008-08-05T14:07:58Z","title":"What is the best way to iterate through an array in Classic Asp VBScript?","acceptedAnswerId":2393,"type":"question","body":"In the code below For i = LBound(arr) To UBound(arr) What is the point in asking using LBound? Surely that is always 0. "} {"user":"26","tags":["osx","mouse","keyboard-shortcuts"],"questionId":2349,"creationDate":"2008-08-05T14:07:58Z","title":"How to tab focus onto a dropdown field in Mac OSX","acceptedAnswerId":2360,"type":"question","body":"In Windows, in any windows form or web browser, you can use the tab button to switch focus through all of the form fields. It will stop on textboxes, radiobuttons, checkboxes, dropdown menus, etc. However, in Mac OSX, tab skips dropdown menus. Is there anyway to change this behavior, or access the above items mentioned, without using a mouse? "} {"user":"410","questionId":2232,"creationDate":"2008-08-05T14:08:13Z","answerId":2350,"type":"answer","body":"The way I like to do this is using the %x literal, which makes it easy (and readable!) to use quotes in a command, like so: directorylist = %x[find . -name '*test.rb' | sort] Which, in this case, will populate file list with all test files under the current directory, which you can process as expected: directorylist.each do |filename| filename.chomp! # work with file end "} {"user":"137","questionId":2349,"creationDate":"2008-08-05T14:13:12Z","answerId":2360,"type":"answer","body":"Go to System Preferences > Keyboard and Mouse, then choose Keyboard Shortcuts. At the bottom, ensure Full Keyboard Access is set to \"All controls\". It's a long time since I turned it on but I think that's all you need to do "} {"user":"140","questionId":2349,"creationDate":"2008-08-05T14:13:58Z","answerId":2361,"type":"answer","body":"Apple Menu > System Preferences > Keyboard & Mouse > Keyboard Shortcuts: Change the radio button at the bottom from \"Text boxes and lists only\" to \"All controls.\" Edit: Dammit. We're a fast group around here aren't we? :-) "} {"user":"user290","tags":["unit-testing","tdd","sqa"],"questionId":2364,"creationDate":"2008-08-05T14:14:36Z","title":"What is Your Experience with Unit Testing in Practice?","acceptedAnswerId":2390,"type":"question","body":"//Yes, Virginia, there is a wikipedia. What I'm asking here is what you've found unit testing to be in your own practice. It would be helpful to know the pros, cons, obstacles to introducing unit testing, flaws in the unit testing process, value gained by unit testing, and so on that the developers here have observed in their day to day practice. What we're doing: I work on a web application w/ an Oracle backend. The application has been in production for 8+ years, and there are ongoing enhancement efforts along with the maintenance work. My development team does Unit Test Scripts (UTS) that aim to walk a developer through the unit test of a given code package. These UTS are 2-20 page Word documents that describe the purpose of the package, the structure, and elaborate on given modules within a package. The UTS concludes with a section that describes an Application Test of the package. This doesn't sound like unit testing to me. It sounds a lot more like system integration testing w/ a description of the package. It certainly is not automated. With our UTS practice in its current state, managing/editing/follwing the documents is not a trivial task. And when enhancements or maintenance work to a given package is needed, there are not strict testing procedures put in place to guarantee outputs are satisfactory. Instead, we have this higher level UTS to follow, which does not come close to guaranteeing correct output in various code traces. "} {"user":"402","tags":["haskell","functional-programming","monads","glossary"],"questionId":2366,"creationDate":"2008-08-05T14:16:02Z","title":"Can anyone explain Monads?","type":"question","body":" Possible Duplicate: What is a monad? I think I understand what 'Maybe Monads' are, but I'm not sure about the other types. "} {"user":"95","questionId":930,"creationDate":"2008-08-05T14:17:22Z","answerId":2369,"type":"answer","body":"This is an alternative way (DataReader is faster than this one): string s = \"\"; SqlConnection conn = new SqlConnection(\"Server=;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;\"); SqlDataAdapter da = new SqlDataAdapter(\"SELECT TOP 5 name, dbid FROM sysdatabases\", conn); DataTable dt = new DataTable(); da.Fill(dt); for (int i = 0; i < dt.Rows.Count; i++) { s += dt.Rows[i][\"name\"].ToString() + \" -- \" + dt.Rows[i][\"dbid\"].ToString() + \"\\n\"; } MessageBox.Show(s); "} {"user":"149","questionId":2196,"creationDate":"2008-08-05T14:19:01Z","answerId":2372,"type":"answer","body":"Step one is to make your \"dirty\" pieces self contained user controls Step two is to embed those controls on your consuming page Step three is to wrap each user control tag in their own Asp:UpdatePanel Step four is to ensure your control gets the data it needs by having it read from properties which check against the viewstate for pre-existing values. I know this makes your code rely on ugly global variables but it's a fast way to get this done. Your mileage may vary. "} {"user":"51","questionId":2196,"creationDate":"2008-08-05T14:19:26Z","answerId":2373,"type":"answer","body":"Check out the RadAjax control from Telerik - it allows you to avoid using UpdatePanels, and limit the amount of info passed back and forth between server and client by declaring direct relationships between calling controls, and controls that should be \"Ajaxified\" when the calling controls submit postbacks. "} {"user":"170","questionId":2284,"creationDate":"2008-08-05T14:21:16Z","answerId":2374,"type":"answer","body":"As previous posters have said, it's a matter for the project. You will find that some are more open to change than others. From a mechanical perspective, you will need to see if they use SVN (for example on google code) or CVS (for example on sourceforge) and determine if they use patch or some other method. A good example of the sort of procedure you might need to employ can be seen on the gimp site: http://www.gimp.org/bugs/howtos/submit-patch.html Note their use of Bugzilla, patch and CVS "} {"user":"35","questionId":2349,"creationDate":"2008-08-05T14:23:14Z","answerId":2376,"type":"answer","body":"It's in the System Preferences - this blog post shows where the setting is. "} {"user":"409","questionId":1644,"creationDate":"2008-08-05T14:23:59Z","answerId":2377,"type":"answer","body":"Suggest someone with the reputation to do it revise this question to say, \"What good technology podcasts are out there?\" I've got all kinds of audio fiction I could recommend, but then this question really runs off into the weeds. "} {"user":"39","questionId":2348,"creationDate":"2008-08-05T14:24:13Z","answerId":2378,"type":"answer","body":"Probably it comes from VB6. Because with Option Base statement in VB6, you can alter the lower bound of arrays like this: Option Base 1 Also in VB6, you can alter the lower bound of a specific array like this: Dim myArray(4 To 42) As String "} {"user":"51","questionId":2328,"creationDate":"2008-08-05T14:25:19Z","answerId":2379,"type":"answer","body":"Check out this blog post: Tweaking the ICallbackEventHandler and Viewstate. The author seems to be addressing the very situation that you are experiencing: So when using ICallbackEventHandler you have two obstacles to overcome to have updated state management for callbacks. First is the problem of the read-only viewstate. The other is actually registering the changes the user has made to the page before triggering the callback. See the blog post for his suggestions on how to solve this. Also check out this forum post which discusses the same problem as well. "} {"user":"383","questionId":2120,"creationDate":"2008-08-05T14:26:41Z","answerId":2382,"type":"answer","body":"I have found the solution else where: SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32) "} {"user":"143","tags":["c#","struct","io","binaryfiles"],"questionId":2384,"creationDate":"2008-08-05T14:28:57Z","title":"Read binary file into a struct","type":"question","body":"I'm trying to read binary data using C#. I have all information about the layout of the data in the files I want to read. I'm able to read the data \"chunk by chunk\", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes, ... Since there are at least three slightly different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it \"line by line\". I have tried the following approach but to no avail: StructType aStruct; int count = Marshal.SizeOf(typeof(StructType)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(stream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType)); handle.Free(); The stream is an opened FileStream from which I have began to read from. I get an AccessViolationException when using Marshal.PtrToStructure. The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file. The struct is defined like: [StructLayout(LayoutKind.Explicit)] struct StructType { [FieldOffset(0)] public string FileDate; [FieldOffset(8)] public string FileTime; [FieldOffset(16)] public int Id1; [FieldOffset(20)] public string Id2; } The examples code is changed from original to make this question shorter. How would I read binary data from a file into a struct? "} {"user":"121","questionId":1644,"creationDate":"2008-08-05T14:29:33Z","answerId":2385,"type":"answer","body":"All of the tech podcasts I listen to have been mentioned, but as long as we're discussing video I'd like to mention Hak.5. It is more focused on using existing programs rather than coding, but it has some good hardware segments, and it can often be an excellent source of inspiration. "} {"user":"414","questionId":44965,"creationDate":"2008-08-05T14:32:06Z","answerId":2388,"type":"answer","body":"The easiest way to grok them (at least for me) is as \"decorators\", adding behavior while preserving the underlying semantics. Or, an even dirtier definition: it's functional programming's operator overloading. "} {"user":"377","questionId":2364,"creationDate":"2008-08-05T14:34:33Z","answerId":2390,"type":"answer","body":"Unit test, for me, has been something of a mixed blessing. I have been in the situation where I must write unit tests for several years now, and I totally see the advantage for a clean and efficient development cycle, however these are some of the issues I have faced. Development may be clean, but when requirements change, you often have to start again at the unit test level. This is, of course, a process issue rather than a TDD one. Testing GUI stuff is nigh on impossible OOTB with most tools There is a large amount of self-discipline required to make sure you use best practice. It is unfortunate but it's very easy to fall away from test-driven to \"test-supported\" development. By that I mean starting off with the best of intentions, but not sticking to the idea of writing your test first. In all, though, I am in favour of using unit testing to improve stability, reliability, brevity and general quality of your code. Regression testing is a huge area for unit tests to come into their own, and I sure hope someone else can explain their views on that a little better than I can. :) "} {"user":"404","questionId":2348,"creationDate":"2008-08-05T14:36:12Z","answerId":2393,"type":"answer","body":"Why not use For Each? That way you don't need to care what the LBound and UBound are. Dim x, y, z x = Array(1, 2, 3) For Each y In x z = DoSomethingWith(y) Next "} {"user":"402","questionId":2232,"creationDate":"2008-08-05T14:42:45Z","answerId":2400,"type":"answer","body":"This explanation is based on a commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link. First, note that when Ruby calls out to a shell, it typically calls /bin/sh, not Bash. Some Bash syntax is not supported by /bin/sh on all systems. Here are ways to execute a shell script: cmd = \"echo 'hi'\" # Sample string that can be used Kernel#` , commonly called backticks – `cmd` This is like many other languages, including Bash, PHP, and Perl. Returns the result of the shell command. Docs: http://ruby-doc.org/core/Kernel.html#method-i-60 value = `echo 'hi'` value = `#{cmd}` Built-in syntax, %x( cmd ) Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters (, [, {, or <, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{ ... } is allowed. Returns the result of the shell command, just like the backticks. Docs: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html value = %x( echo 'hi' ) value = %x[ #{cmd} ] Kernel#system Executes the given command in a subshell. Returns true if the command was found and ran successfully, false otherwise. Docs: http://ruby-doc.org/core/Kernel.html#method-i-system wasGood = system( \"echo 'hi'\" ) wasGood = system( cmd ) Kernel#exec Replaces the current process by running the given external command. Returns none, the current process is replaced and never continues. Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec exec( \"echo 'hi'\" ) exec( cmd ) # Note: this will never be reached because of the line above Here's some extra advice: $?, which is the same as $CHILD_STATUS, accesses the status of the last system executed command if you use the backticks, system() or %x{}. You can then access the exitstatus and pid properties: $?.exitstatus For more reading see: http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html http://tech.natemurray.com/2007/03/ruby-shell-commands.html "} {"user":"307","tags":["language-agnostic","data-structures","file","binary"],"questionId":2405,"creationDate":"2008-08-05T14:45:17Z","title":"Binary file layout reference","acceptedAnswerId":2444,"type":"question","body":"Where are some good sources of information on binary file layout structures? If I wanted to pull in a BTrieve index file, parse MP3 headers, etc. Where does one get reliable information? "} {"user":"25","questionId":2405,"creationDate":"2008-08-05T14:47:18Z","answerId":2409,"type":"answer","body":"I'm not sure if there's a general information source for this kind of information. I always just search on google or wikipedia for that particular file type. The binary file layout structure information should be included. For example, http://en.wikipedia.org/wiki/MP3#File_structure\">MP3 file layout structure "} {"user":"409","questionId":1644,"creationDate":"2008-08-05T14:51:08Z","answerId":2421,"type":"answer","body":"Am I going to be downmodded for suggesting that the Stack Overflow podcast is hilariously bad as a podcast? Anywho, you can find it, and a number of not-bad podcasts at itconversations.com. As this question asked for a \"good\" rather than \"exhaustive\" list, then this is obviously just my opinion. My opinion bounces between .NET and Java and just geek. And obvious omissions would reflect my opinion on \"good\". (Ahem, DNR.) The rest of these are easily found by doing a podcast search in iTunes, or just googling (I'll do some repeating here to condense the list): Buzz Out Loud (General Consumer Tech, Daily) This Week in Tech (aka TWiT. Weekly Consumer Tech.) The Java Posse (Weekly.) Google Developer Podcast (which went long fallow, but seems to be coming back, possible renamed as the Google Code Review. Schedule uncertain, technologies vary.) Hanselminutes (Usually, but not always, .NET-related) MacBreak Weekly (The Mac version of TWiT) Polymorphic Podcast (All .NET, usually ASP.NET) Pixel8ed (All .NET, focused on UI. Same guy who does Polymorphic Podcast) tech5 (Consumer Tech. Mostly a fun waste of 5 minutes because Dvorak is so... Spolsky.) "} {"user":"377","questionId":1584,"creationDate":"2008-08-05T14:51:56Z","answerId":2426,"type":"answer","body":"You should make your choice of server platform based on the environment as a whole, and that includes the admin/management interfaces supplied. I'm afraid that if you don't like the way Windows implements management of IIS, then that's too bad. Having said that, a bit of delving around in the WMI interfaces will generally yield a solution that you should find usable. I used to do quite a bit of WMI scripting (mostly via PowerShell) in order to have a reliable environment rebuild capability. "} {"user":"95","tags":["sql-server","database","sql-server-2005","sql-server-2000"],"questionId":2432,"creationDate":"2008-08-05T14:54:03Z","title":"Have you ever encountered a query that SQL Server could not execute because it referenced too many tables?","acceptedAnswerId":2462,"type":"question","body":"Have you ever seen any of there error messages? -- SQL Server 2000 Could not allocate ancillary table for view or function resolution. The maximum number of tables in a query (256) was exceeded. -- SQL Server 2005 Too many table names in the query. The maximum allowable is 256. If yes, what have you done? Given up? Convinced the customer to simplify their demands? Denormalized the database? @(everyone wanting me to post the query): I'm not sure if I can paste 70 kilobytes of code in the answer editing window. Even if I can this this won't help since this 70 kilobytes of code will reference 20 or 30 views that I would also have to post since otherwise the code will be meaningless. I don't want to sound like I am boasting here but the problem is not in the queries. The queries are optimal (or at least almost optimal). I have spent countless hours optimizing them, looking for every single column and every single table that can be removed. Imagine a report that has 200 or 300 columns that has to be filled with a single SELECT statement (because that's how it was designed a few years ago when it was still a small report). "} {"user":"67","questionId":2328,"creationDate":"2008-08-05T14:54:23Z","answerId":2434,"type":"answer","body":"I actually found both of those links you provided, but as noted they are simply describing the problem, not solving it. The author of the blog post suggests a workaround by using a different ViewState provider, but unfortunately that isn't a possibility in this case...I really need to leave the particulars of the ViewState alone and just hook on to what is being done out-of-the-box. "} {"user":"373","questionId":2384,"creationDate":"2008-08-05T14:56:10Z","answerId":2436,"type":"answer","body":"Try this: using (FileStream stream = new FileStream(fileName, FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); StructType aStruct = (StructType)formatter.Deserialize(filestream); } "} {"user":"377","questionId":2432,"creationDate":"2008-08-05T14:57:40Z","answerId":2440,"type":"answer","body":"I have never come across this kind of situation, and to be honest the idea of referencing > 256 tables in a query fils me with a mortal dread. Your first question should probably by \"Why so many?\", closely followed by \"what bits of information do I NOT need?\" I'd be worried that the amount of data being returned from such a query would begin to impact performance of the application quite severely, too. "} {"user":"26","questionId":2432,"creationDate":"2008-08-05T14:58:55Z","answerId":2442,"type":"answer","body":"I'd like to see that query, but I imagine it's some problem with some sort of iterator, and while I can't think of any situations where its possible, I bet it's from a bad while/case/cursor or a ton of poorly implemented views. "} {"user":"304","questionId":2405,"creationDate":"2008-08-05T14:59:16Z","answerId":2444,"type":"answer","body":"Not comprehensive, but useful nonetheless: http://www.wotsit.org/ "} {"user":"N0mad","tags":["security","agile"],"questionId":2447,"creationDate":"2008-08-05T15:05:00Z","title":"Are there best practices for testing security in an Agile development shop?","type":"question","body":"Regarding Agile development, what are the best practices for testing security per release? If it is a monthly release, are there shops doing pen-tests every month? "} {"user":"383","questionId":48,"creationDate":"2008-08-05T15:08:42Z","answerId":2452,"type":"answer","body":"Using the example you gave:
If you click on \"Previous Page\" only the value of \"prev\" will be submitted. If you click on \"Next Page\" only the value of \"next\" will be submitted. If however, you press enter somewhere on the form, neither \"prev\" nor \"next\" will be submitted. So using pseudo code you could do the following: If \"prev\" submitted then Previous Page was click Else If \"next\" submitted then Next Page was click Else No button was click "} {"user":"72","questionId":2432,"creationDate":"2008-08-05T15:19:18Z","answerId":2460,"type":"answer","body":"@chopeen You could change the way you're calculating these statistics, and instead keep a separate table of all per-product stats.. when an order is placed, loop through the products and update the appropriate records in the stats table. This would shift a lot of the calculation load to the checkout page rather than running everything in one huge query when running a report. Of course there are some stats that aren't going to work as well this way, e.g. tracking customers' next purchases after purchasing a particular product. "} {"user":"71","questionId":2432,"creationDate":"2008-08-05T15:19:41Z","answerId":2462,"type":"answer","body":"For SQL Server 2005, I'd recommend using table variables and partially building the data as you go. To do this, create a table variable that represents your final result set you want to send to the user. Then find your primary table (say the orders table in your example above) and pull that data, plus a bit of supplementary data that is only say one join away (customer name, product name). You can do a SELECT INTO to put this straight into your table variable. From there, iterate through the table and for each row, do a bunch of small SELECT queries that retrieves all the supplemental data you need for your result set. Insert these into each column as you go. Once complete, you can then do a simple SELECT * from your table variable and return this result set to the user. I don't have any hard numbers for this, but there have been three distinct instances that I have worked on to date where doing these smaller queries has actually worked faster than doing one massive select query with a bunch of joins. "} {"user":"26","questionId":2432,"creationDate":"2008-08-05T15:26:55Z","answerId":2468,"type":"answer","body":"Post the query :D Also I feel like one of the possible problems could be having a ton (read 200+) of name/value tables which could condensed into a single lookup table. "} {"user":"72","questionId":1408,"creationDate":"2008-08-05T15:30:30Z","answerId":2471,"type":"answer","body":"A VirtualHost would also work for this and may work better for you as you can host several projects without the need for subdirectories. Here's how you do it: httpd.conf (or extra\\httpd-vhosts.conf relative to httpd.conf. Trailing slashes \"\\\" might cause it not to work): NameVirtualHost *:80 # ... DocumentRoot C:\\projects\\transitCalculator\\trunk\\ ServerName transitcalculator.localhost Order allow,deny Allow from all HOSTS file (c:\\windows\\system32\\drivers\\etc\\hosts usually): # localhost entries localhost transitcalculator.localhost Now restart XAMPP and you should be able to access http://transitcalculator.localhost/ and it will map straight to that directory. This can be helpful if you're trying to replicate a production environment where you're developing a site that will sit on the root of a domain name. You can, for example, point to files with absolute paths that will carry over to the server: \"My whereas in an environment using aliases or subdirectories, you'd need keep track of exactly where the \"images\" directory was relative to the current file. "} {"user":"116","tags":["browser","analytics"],"questionId":2472,"creationDate":"2008-08-05T15:30:42Z","title":"How can I tell if a web client is blocking advertisements?","acceptedAnswerId":2477,"type":"question","body":"What is the best way to record statistics on the number of visitors visiting my site that have set their browser to block ads? "} {"user":"275","questionId":2384,"creationDate":"2008-08-05T15:31:43Z","answerId":2474,"type":"answer","body":"I don't see any problem with your code. just out of my head, what if you try to do it manually? does it work? BinaryReader reader = new BinaryReader(stream); StructType o = new StructType(); o.FileDate = Encoding.ASCII.GetString(reader.ReadBytes(8)); o.FileTime = Encoding.ASCII.GetString(reader.ReadBytes(8)); ... ... ... also try StructType o = new StructType(); byte[] buffer = new byte[Marshal.SizeOf(typeof(StructType))]; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false); handle.Free(); then use buffer[] in your BinaryReader instead of reading data from FileStream to see whether you still get AccessViolation exception. I had no luck using the BinaryFormatter, I guess I have to have a complete struct that matches the content of the file exactly. That makes sense, BinaryFormatter has its own data format, completely incompatible with yours. "} {"user":"380","questionId":2472,"creationDate":"2008-08-05T15:32:21Z","answerId":2476,"type":"answer","body":"I suppose you could compare the ad prints with the page views on your website (which you can get from your analytics software). "} {"user":"383","questionId":2472,"creationDate":"2008-08-05T15:34:18Z","answerId":2477,"type":"answer","body":"Since programs like AdBlock actually never request the advert, you would have to look the server logs to see if the same user accessed a webpage but didn't access an advert. This is assuming the advert is on the same server. If your adverts are on a separate server, then I would suggest it's impossible to do so. The best way to stop users from blocking adverts, is to have inline text adverts which are generated by the server and dished up inside your html. "} {"user":"309844","questionId":2472,"creationDate":"2008-08-05T15:37:34Z","answerId":2478,"type":"answer","body":"Add the user id to the request for the ad: that way you can check what ads are seen by which users. "} {"user":"170","questionId":2472,"creationDate":"2008-08-05T15:37:36Z","answerId":2479,"type":"answer","body":"You need to think about the different ways that ads are blocked. The first thing to look at is whether they are running noscript, so you could add a script that would check for that. The next thing is to see if they are blocking flash, a small movie should do that. If you look at the adblock site, there is some indication of how it does blocking: How does element hiding work? If you look further down that page, you will see that conventional chrome probing will not work, so you need to try and parse the altered DOM. "} {"user":"152","tags":["data-structures","language-agnostic","binary-search-tree"],"questionId":2481,"creationDate":"2008-08-05T15:40:24Z","title":"Best self-balancing BST for quick insertion of a large number of nodes","acceptedAnswerId":2511,"type":"question","body":"I've been able to find details on several self-balancing BSTs through several sources, but I haven't found any good descriptions detailing which one is best to use in different situations (or if it really doesn't matter). I want a BST that is optimal for storing in excess of ten million nodes. The order of insertion of the nodes is basically random, and I will never need to delete nodes, so insertion time is the only thing that would need to be optimized. I intend to use it to store previously visited game states in a puzzle game, so that I can quickly check if a previous configuration has already been encountered. "} {"user":"311","tags":["multithreading","language-agnostic","concurrency"],"questionId":2482,"creationDate":"2008-08-05T15:42:09Z","title":"What are some good resources for learning threaded programming?","acceptedAnswerId":2513,"type":"question","body":"With the rise of multicore CPUs on the desktop, multithreading skills will become a valuable asset for programmers. Can you recommend some good resources (books, tutorials, websites, etc.) for a programmer who is looking to learn about threaded programming? "} {"user":"91","tags":["c#",".net"],"questionId":2483,"creationDate":"2008-08-05T15:42:30Z","title":"Casting: (NewType) vs. Object as NewType","acceptedAnswerId":2487,"type":"question","body":" Possible Duplicate: Casting vs using the 'as' keyword in the CLR What is actually the difference between these two casts? SomeClass sc = (SomeClass)SomeObject; SomeClass sc2 = SomeObject as SomeClass; Normally, they should both be explicit casts to the specified type? "} {"user":"277","tags":["ajax","progressive-enhancement"],"questionId":2486,"creationDate":"2008-08-05T15:44:39Z","title":"What is Progressive Enhancement?","acceptedAnswerId":2514,"type":"question","body":"Jeff mentioned the concept of 'Progressive Enhancement' when talking about using JQuery to write stackoverflow. After a quick Google, I found a couple of high-level discussions about it. Can anyone recommend a good place to start as a programmer. Specifically, I have been writing web apps in PHP and would like to use YUI to improve the pages I am writing, but a lot of them seem very JavaScript based, with most of the donkey work being done using JavaScript. To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it. Anyone have some good places to start using this idea, I don't really care about the language. Ideally, I would like to see how you start creating the static HTML first, and then adding the YUI (or whatever Ajax framework) to it so that you get the benefits of a richer client? "} {"user":"266","questionId":2483,"creationDate":"2008-08-05T15:44:46Z","answerId":2487,"type":"answer","body":"The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception. [Edit] My original answer is certainly the most pronounced difference, but as Eric Lippert points out, it's not the only one. Other differences include: You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value You can't use 'as' to convert things, like numbers to a different representation (float to int, for example). And finally, using 'as' vs. the cast operator, you're also saying \"I'm not sure if this will succeed.\" "} {"user":"58","tags":["mysql","database","database-design","diagram"],"questionId":2488,"creationDate":"2008-08-05T15:45:02Z","title":"Auto Generate Database Diagram MySQL","acceptedAnswerId":2495,"type":"question","body":"I'm tired of opening Dia and creating a database diagram at the beginning of every project. Is there a tool out there that will let me select specific tables and then create a database diagram for me based on a MySQL database? Preferably it would allow me to edit the diagram afterward since none of the foreign keys are set... Here is what I am picturing diagram-wise (please excuse the horrible data design, I didn't design it. Let's focus on the diagram concept and not on the actual data it represents for this example ;) ): see full size diagram "} {"user":"316","questionId":2483,"creationDate":"2008-08-05T15:45:06Z","answerId":2489,"type":"answer","body":"The parenthetical cast throws an exception if the cast attempt fails. The \"as\" cast returns null if the cast attempt fails. "} {"user":"275","questionId":2256,"creationDate":"2008-08-05T15:46:35Z","answerId":2490,"type":"answer","body":"Most people use .NET serialization (there is faster binary and slower XML formatter, they both depend on reflection and are version tolerant to certain degree) However, if you want the fastest (unsafe) way - why not: Writing: YourStruct o = new YourStruct(); byte[] buffer = new byte[Marshal.SizeOf(typeof(YourStruct))]; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false); handle.Free(); Reading: handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); o = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct)); handle.Free(); "} {"user":"316","questionId":2482,"creationDate":"2008-08-05T15:47:15Z","answerId":2491,"type":"answer","body":"I've honestly never read it myself, but Concurrent Programming in Java is a book I've heard recommended by several people. "} {"user":"2089740","questionId":1908,"creationDate":"2008-08-05T15:47:51Z","answerId":2492,"type":"answer","body":"Alright. From a theoretical point of view, given that the distortion is \"arbitrary\", and any solution requires you to model this arbitrary distortion, you obviously can't get an \"answer\". However, any solution is going to involve imposing (usually implicitly) some model of the distortion that may or may not reflect the reality of the situation. Since you seem to be most interested in models that presume some sort of local continuity of the distortion mapping, the most obvious choice is the one you've already tried: linear interpolaton between the nearest points. Going beyond that is going to require more sophisticated mathematical and numerical analysis knowledge. You are incorrect, however, in presuming you cannot expand this to more points. You can by using a least-squared error approach. Find the linear answer that minimizes the error of the other points. This is probably the most straight-forward extension. In other words, take the 5 nearest points and try to come up with a linear approximation that minimizes the error of those points. And use that. I would try this next. If that doesn't work, then the assumption of linearity over the area of N points is broken. At that point you'll need to upgrade to either a quadratic or cubic model. The math is going to get hectic at that point. "} {"user":"305","questionId":2488,"creationDate":"2008-08-05T15:48:10Z","answerId":2494,"type":"answer","body":"I believe DB Designer does something like that. And I think they even have a free version. edit Never mind. Michael's link is much better. "} {"user":"91","questionId":2488,"creationDate":"2008-08-05T15:48:11Z","answerId":2495,"type":"answer","body":"Try MySQL Workbench, formerly DBDesigner 4: http://dev.mysql.com/workbench/ This has a \"Reverse Engineer Database\" mode: "} {"user":"398","questionId":2482,"creationDate":"2008-08-05T15:48:57Z","answerId":2496,"type":"answer","body":"http://www.cilk.com/multicore-e-book/ That's a nice general overview of the sitution, if you're looking for tuorials and books it might be best to specify a language as a starting point so you can mess around with some code. "} {"user":"402","questionId":2483,"creationDate":"2008-08-05T15:49:34Z","answerId":2497,"type":"answer","body":"They'll throw different exceptions. () : NullReferenceException as : InvalidCastException Which could help for debugging. The \"as\" keyword attempts to cast the object and if the cast fails, null is returned silently. The () cast operator will throw an exception immediately if the cast fails. \"Only use the C# \"as\" keyword where you are expecting the cast to fail in a non-exceptional case. If you are counting on a cast to succeed and are unprepared to receive any object that would fail, you should use the () cast operator so that an appropriate and helpful exception is thrown.\" For code examples and a further explanation: http://blog.nerdbank.net/2008/06/when-not-to-use-c-keyword.html "} {"user":"316","questionId":2481,"creationDate":"2008-08-05T15:50:05Z","answerId":2498,"type":"answer","body":"The two self-balancing BSTs I'm most familiar with are red-black and AVL, so I can't say for certain if any other solutions are better, but as I recall, red-black has faster insertion and slower retrieval compared to AVL. So if insertion is a higher priority than retrieval, red-black may be a better solution. "} {"user":"383","questionId":2486,"creationDate":"2008-08-05T15:51:11Z","answerId":2500,"type":"answer","body":"As you've said To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it. This isn't progressive enhancement. Progressive enhancement is when the site works perfectly without JavaScript or CSS, and then adding (layering) these extra technologies/code to increase the usability and functionality of the website. The best example I can give is the tag input box on this website. With JavaScript turned off, it would still work allowing you to enter tags separated with a space. With JavaScript turned on, you get a drop down with suggestions of previous entries. This is progressive enhancement. "} {"user":"399","questionId":2486,"creationDate":"2008-08-05T15:55:59Z","answerId":2504,"type":"answer","body":"I wrote a tutorial on creating a poll that used progressive enhancement at NETTUTS. The idea is to create a functional site using XHTML/CSS and PHP, and then intercept forms etc with Javascript. (I used JQuery). "} {"user":"312","questionId":2486,"creationDate":"2008-08-05T15:57:00Z","answerId":2506,"type":"answer","body":"Going at it from the other direction is sometimes referred to as graceful degradation. This is usually needed when the site is built first with the enhanced functionality afforded by the various technologies then modified to degrade gracefully for browsers with those technologies are not available. It is also graceful degradation when designing to work with older browsers (ancient in the Internets terminology) such as IE 5.5, Netscape, etc... In my opinion it is much more work to gracefully degrade the application. Progressively enhancing it tends to be much more efficient; however, sometimes the need to take an existing app and make it accessible in these lacking environments arise. "} {"user":"303","tags":["unit-testing","tdd","bdd"],"questionId":2509,"creationDate":"2008-08-05T15:58:08Z","title":"What are the primary differences between TDD and BDD?","acceptedAnswerId":2548,"type":"question","body":"Test Driven Development has been the rage in the .NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD? "} {"user":"269","questionId":2311,"creationDate":"2008-08-05T15:59:24Z","answerId":2510,"type":"answer","body":"Small files take up a whole node on the filesystem whatever size that is. My host tends to report all small files as 4kb in ftp but in a shell gives an accurate size so it might be a 'feature' common to ftp clients. "} {"user":"2089740","questionId":2481,"creationDate":"2008-08-05T15:59:27Z","answerId":2511,"type":"answer","body":"Red-black is better than AVL for insertion-heavy applications. If you foresee relatively uniform look-up, then Red-black is the way to go. If you foresee a relatively unbalanced look-up where more recently viewed elements are more likely to be viewed again, you want to use splay trees. "} {"user":"342","questionId":2482,"creationDate":"2008-08-05T16:02:41Z","answerId":2513,"type":"answer","body":"Take a look at Herb Sutter's \"The Free Lunch Is Over\" and then his series of articles on Effective Concurrency. "} {"user":"269","questionId":2486,"creationDate":"2008-08-05T16:05:29Z","answerId":2514,"type":"answer","body":"See also Unobtrusive Javascript which is the bedrock progressive enhancement is built. "} {"user":"91","questionId":2509,"creationDate":"2008-08-05T16:06:36Z","answerId":2515,"type":"answer","body":"Behaviour Driven Development seems to focus more on the interaction and communication between Developers and also between Developers and testers. The Wikipedia Article has an explanation: Behavior-driven development Not practicing BDD myself though. "} {"user":"200","questionId":2488,"creationDate":"2008-08-05T16:08:40Z","answerId":2517,"type":"answer","body":"The \"Reverse Engineer Database\" mode in Workbench is only part of the paid version, not the free one. "} {"user":"26","tags":["actionscript-3","flex","sqlite","air","adobe"],"questionId":2518,"creationDate":"2008-08-05T16:09:12Z","title":"Using multiple SQLite databases at once","acceptedAnswerId":10020,"type":"question","body":"I have 2 SQLite databases, one downloaded from a server (server.db), and one used as storage on the client (client.db). I need to perform various sync queries on the client database, using data from the server database. For example, I want to delete all rows in the client.db tRole table, and repopulate with all rows in the server.db tRole table. Another example, I want to delete all rows in the client.db tFile table where the fileID is not in the server.db tFile table. In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air? "} {"user":"312","questionId":2509,"creationDate":"2008-08-05T16:11:02Z","answerId":2520,"type":"answer","body":"It seems to me that BDD is a broader scope. It almost implies TDD is used, that BDD is the encompasing methodology that gathers the information and requirements for using, amongh other things, TDD practices to ensure rapid feedback. "} {"user":"269","questionId":2284,"creationDate":"2008-08-05T16:12:03Z","answerId":2521,"type":"answer","body":"Things like this used to be simple. There was a mailing list for users and one for developers. If you see a problem and can fix it fix it and then run Larry Wall's Patch and send the resulting patch to the devs list with a quick explanation of what it does. Generally a dev with write access to the CVS (or in the real old days whose floppy the project resided on ;) ) would check things over and if your patch does what it says on the tin and doesn't break anything else it gets into the source tree proper. These days there are many, many more projects using open development and lots of them are run by people who have never run a software project before let alone an open sourced one so things can be more tricky. Generally mailing a patch to someone doing lots of dev in the right area of the project gets the right eyes looking at it quickly even today. A browse of the online repository will tell you the folks who do the work rather than those who get their names on the front page of the web site, contact those guys first :) "} {"user":"27","questionId":2483,"creationDate":"2008-08-05T16:15:38Z","answerId":2522,"type":"answer","body":"Also note that you can only use the as keyword with a reference type or a nullable type ie: double d = 5.34; int i = d as int; will not compile double d = 5.34; int i = (int)d; will compile. "} {"user":"422","questionId":1669,"creationDate":"2008-08-05T16:16:01Z","answerId":2523,"type":"answer","body":"The Dragon Book is definitely the \"building compilers\" book, but if your language isn't quite as complicated as the current generation of languages, you may want to look at the Interpreter pattern from Design Patterns. The example in the book designs a regular expression-like language and is well thought through, but as they say in the book, it's good for thinking through the process but is effective really only on small languages. However, it is much faster to write an Interpreter for a small language with this pattern than having to learn about all the different types of parsers, yacc and lex, et cetera... "} {"user":"417","tags":["asp.net","visual-studio","visual-studio-2008","debugging","iis"],"questionId":2524,"creationDate":"2008-08-05T16:18:18Z","title":"Visual Studio \"Unable to start debugging on the web server. The web server did not respond in a timely manner.\"","acceptedAnswerId":151931,"type":"question","body":"I get the following error pretty regularly when compiling in Visual Studio and running my web application: \"Unable to start debugging on the web server. The web server did not respond in a timely manner. This may be because another debugger is already attached to the web server.\" Normally this is after having debug the application once already. From the command line I run \"iisreset /restart\" and it fixes the problem. How do I prevent this from happening in the first place? "} {"user":"350","tags":[".net","security","obfuscation"],"questionId":2525,"creationDate":"2008-08-05T16:20:37Z","title":".NET obfuscation tools/strategy","acceptedAnswerId":8739,"type":"question","body":"My product has several components: ASP.NET, Windows Forms App and Windows Service. 95% or so of the code is written in VB.NET. For Intellectual Property reasons, I need to obfuscate the code, and until now I have been using a version of dotfuscator which is now over 5 years old. I'm thinking it is time to move to a new generation tool. What I'm looking for is a list of requirements which I should consider when searching for a new obfuscator. What I know I should look for so far: Serialization/De-serialization. In my current solution, I simply tell the tool not to obfuscate any class data members because the pain of not being able to load data which was previously serialized is simply too big. Integration with Build Process Working with ASP.NET. In the past, I have found this problematic due to changing .dll names (you often have one per page) - which not all tools handle well. "} {"user":"428","tags":["c#","winforms","treeview","contextmenu"],"questionId":2527,"creationDate":"2008-08-05T16:21:14Z","title":"Find node clicked under context menu","acceptedAnswerId":2546,"type":"question","body":"How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. I can't use the TreeViews' SelectedNode property because the node is only been right-clicked and not selected. "} {"user":"26","questionId":2525,"creationDate":"2008-08-05T16:21:56Z","answerId":2528,"type":"answer","body":"I have been using smartassembly. Basically, you pick a dll and it returns it obfuscated. It seems to work fine and I've had no problems so far. Very, very easy to use. "} {"user":"307","tags":["html","autocomplete"],"questionId":2530,"creationDate":"2008-08-05T16:22:32Z","title":"How do you disable browser Autocomplete on web form field / input tag?","acceptedAnswerId":2531,"type":"question","body":"How do you disable autocomplete in the major browsers for a specific input (or form field)? "} {"user":"157","questionId":2530,"creationDate":"2008-08-05T16:24:53Z","answerId":2531,"type":"answer","body":"Firefox 30 ignores autocomplete=\"off\" for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following commentary from May 5, 2014: The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user. We are the third browser to implement this change, after IE and Chrome. According to Mozilla developer documentation the form element attribute autocomplete prevents form data from being cached in older browsers. "} {"user":"269","questionId":2530,"creationDate":"2008-08-05T16:26:26Z","answerId":2535,"type":"answer","body":" was a none standard way to do this (I think mozilla and IE still support it) but messing with the users expectations is normally a bad idea. If the user enters their credit card details into a form and then let's someone else use that browser it's not your concern :) "} {"user":"1384652","questionId":2530,"creationDate":"2008-08-05T16:27:39Z","answerId":2536,"type":"answer","body":"Use a non-standard name and id for the fields, so rather than \"name\" have \"name_\". Browsers will then not see it as being the name field. The best part about it is that you can do this to some but not all fields and it will autocomplete some but not all fields. "} {"user":"225","questionId":2530,"creationDate":"2008-08-05T16:27:40Z","answerId":2537,"type":"answer","body":"
This will work in IE and FF, the downside is that it is not XHTML standard. "} {"user":"157","questionId":44965,"creationDate":"2008-08-05T16:28:41Z","answerId":2538,"type":"answer","body":"But, You could have invented Monads! sigfpe says: But all of these introduce monads as something esoteric in need of explanation. But what I want to argue is that they aren't esoteric at all. In fact, faced with various problems in functional programming you would have been led, inexorably, to certain solutions, all of which are examples of monads. In fact, I hope to get you to invent them now if you haven't already. It's then a small step to notice that all of these solutions are in fact the same solution in disguise. And after reading this, you might be in a better position to understand other documents on monads because you'll recognise everything you see as something you've already invented. Many of the problems that monads try to solve are related to the issue of side effects. So we'll start with them. (Note that monads let you do more than handle side-effects, in particular many types of container object can be viewed as monads. Some of the introductions to monads find it hard to reconcile these two different uses of monads and concentrate on just one or the other.) In an imperative programming language such as C++, functions behave nothing like the functions of mathematics. For example, suppose we have a C++ function that takes a single floating point argument and returns a floating point result. Superficially it might seem a little like a mathematical function mapping reals to reals, but a C++ function can do more than just return a number that depends on its arguments. It can read and write the values of global variables as well as writing output to the screen and receiving input from the user. In a pure functional language, however, a function can only read what is supplied to it in its arguments and the only way it can have an effect on the world is through the values it returns. "} {"user":"136","tags":["c","architecture","data-structures"],"questionId":2540,"creationDate":"2008-08-05T16:30:37Z","title":"Good STL-like library for C","acceptedAnswerId":2697,"type":"question","body":"What are good libraries for C with datastructures like vectors, deques, stacks, hashmaps, treemaps, sets, etc.? Plain C, please, and platform-independent. "} {"user":"428","questionId":2525,"creationDate":"2008-08-05T16:30:40Z","answerId":2541,"type":"answer","body":"If your looking for a free one you could try DotObfuscator Community Edition that comes with Visual Studio or Eazfuscator.NET. Since June 29, 2012, Eazfuscator.NET is now commercial. The last free available version is 3.3. "} {"user":"106","questionId":2530,"creationDate":"2008-08-05T16:32:11Z","answerId":2542,"type":"answer","body":"Just set autocomplete=\"off\". There is a very good reason for doing this: You want to provide your own autocomplete functionality! "} {"user":"136","tags":["flash","graph"],"questionId":2543,"creationDate":"2008-08-05T16:34:37Z","title":"What are the best solutions for flash charts and graphs?","acceptedAnswerId":2564,"type":"question","body":"I'm aware of FusionCharts, are there other good solutions, or APIs, for creating charts in Adobe Flash? "} {"user":"312","questionId":2524,"creationDate":"2008-08-05T16:35:17Z","answerId":2544,"type":"answer","body":"It sounds like you are probably hitting F5 in Visual Studio when you receive this error? There are a few things you can try. The easiest is to hit the Stop button before hitting F5. Optionally, when you are finished debugging and starting to make changes you can go to the Debug menu and choose either Stop Debugging or Terminate All. "} {"user":"308","questionId":2524,"creationDate":"2008-08-05T16:35:50Z","answerId":2545,"type":"answer","body":"It sounds like something is eating up your web server's resources. Perhaps you have some resources (file handlers, wcf proxies) that are being opened and not closed? I've had this happen to me specifically when I was not closing WCF client proxy connections. The problem is not necessarily that you have a debugger attached, but only that the web server is not responding in a timely manner. Note that the message says \"This may be because another debugger is attached\". "} {"user":"152","questionId":2527,"creationDate":"2008-08-05T16:36:43Z","answerId":2546,"type":"answer","body":"You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs. void treeView1MouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { // Select the clicked node treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y); if(treeView1.SelectedNode != null) { myContextMenuStrip.Show(treeView1, e.Location); } } } "} {"user":"91","questionId":2543,"creationDate":"2008-08-05T16:36:43Z","answerId":2547,"type":"answer","body":"XML/SWF Charts does Chart off XML: http://www.maani.us/xml_charts/ "} {"user":"341","questionId":2509,"creationDate":"2008-08-05T16:36:53Z","answerId":2548,"type":"answer","body":"I understand BDD to be more about specification than testing. It is linked to Domain Driven Design (don't you love these *DD acronyms?). It is linked with a certain way to write user stories, including high-level tests. An example by Tom ten Thij: Story: User logging in As a user I want to login with my details So that I can get access to the site Scenario: User uses wrong password Given a username 'jdoe' And a password 'letmein' When the user logs in with username and password Then the login form should be shown again (In his article, Tom goes on to directly execute this test specification in Ruby.) The pope of BDD is Dan North. You'll find a great introduction in his Introducing BDD article. You will find a comparison of BDD and TDD in this video. Also an opinion about BDD as \"TDD done right\" by Jeremy D. Miller March 25, 2013 update The video above has been missing for a while. Here is a recent one by Llewellyn Falco, BDD vs TDD (explained). I find his explanation clear and to the point. "} {"user":"308","tags":["asp.net","flash","video","embed"],"questionId":2550,"creationDate":"2008-08-05T16:39:04Z","title":"What are effective options for embedding video in an ASP.NET web site?","acceptedAnswerId":2560,"type":"question","body":"A quick glance at the present-day internet would seem to indicate that Adobe Flash is the obvious choice for embedding video in a web page. Is this accurate, or are they other effective choices? Does the choice of ASP.NET as a platform influence this decision? "} {"user":"46","questionId":2027,"creationDate":"2008-08-05T16:40:35Z","answerId":2554,"type":"answer","body":"Here is another article for the c# programming language c# passes its arguments by value (by default) private void swap(string a, string b) { string tmp = a; a = b; b = tmp; } calling this version of swap will thus have no result: string x = \"foo\"; string y = \"bar\"; swap(x, y); \"output: x: foo y: bar\" however, unlike java c# does give the developer the opportunity to pass parameters by reference, this is done by using the 'ref' keyword before the type of the parameter: private void swap(ref string a, ref string b) { string tmp = a; a = b; b = tmp; } this swap will change the value of the referenced parameter: string x = \"foo\"; string y = \"bar\"; swap(x, y); \"output: x: bar y: foo\" c# also has a out keyword, and the difference between ref and out is a subtle one. from msdn: The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning. and In contrast ref parameters are considered initially assigned by the callee. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method. a small pitfall is, like in java, that objects passed by value can still be changed using their inner methods conclusion: c# passes its parameters, by default, by value but when needed parameters can also be passed by reference using the ref keyword inner methods from a parameter passed by value will alter the object (if that method itself alters some values) useful links: http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx http://www.c-sharpcorner.com/UploadFile/saragana/Willswapwork11162005012542AM/Willswapwork.aspx http://en.csharp-online.net/Value_vs_Reference "} {"user":"77","questionId":2543,"creationDate":"2008-08-05T16:40:37Z","answerId":2555,"type":"answer","body":"I know you said flash, but this is a good silverlight chart api. http://www.visifire.com/. Always good to keep your options open right? Had to plug silverlight, but you can also take a look at Yahoo!'s YUI charting component. "} {"user":"136","tags":["payment"],"questionId":2556,"creationDate":"2008-08-05T16:41:50Z","title":"What's the best online payment processing solution?","acceptedAnswerId":100758,"type":"question","body":"Should be available to non-U.S. companies, easy to setup, reliable, cheap, customizable, etc. What are your experiences? "} {"user":"414","questionId":2540,"creationDate":"2008-08-05T16:43:11Z","answerId":2558,"type":"answer","body":"As always, Google is your friend: http://nixbit.com/cat/programming/libraries/c-generic-library/ specifically: http://nixbit.com/cat/programming/libraries/generic-data-structures-library/ "} {"user":"72","questionId":2550,"creationDate":"2008-08-05T16:44:01Z","answerId":2560,"type":"answer","body":"Flash is certainly the most ubiquitous and portable solution. 98% of browsers have Flash installed. Other alternatives are Quicktime, Windows Media Player, or even Silverlight (Microsoft's Flash competitor, which can be used to embed several video formats). I would recommend using Flash (and it's FLV video file format) for embedding your video unless you have very specific requirements as far as video quality or DRM. "} {"user":"30","questionId":2556,"creationDate":"2008-08-05T16:44:35Z","answerId":2561,"type":"answer","body":"I'd say paypal or GoogleCheckout. Google Checkout is either 2% + .20USD or free depending on how much you spend on adwords. If you spend a dollar on adWords, your next $10 on Google checkout is free. Paypal is 1.9% to 2.9% + $0.30 USD (2.9% for up to $30,000/month, 1.9% for more than $100,000/month) Without factoring in the 20/30 cents, Paypal is just barely cheaper if you sell more than $100,000 per month, and spend nothing on adwords. "} {"user":"91","questionId":2550,"creationDate":"2008-08-05T16:44:43Z","answerId":2562,"type":"answer","body":"Flash is usually the product of choice: Everyone has it, and using the JW FLV Player makes it relatively easy on your side. As for other Video Formats, there are WMV and QuickTime, but the players are rather \"heavy\", not everyone might have them and they feel so 1990ish... Real Player... Don't let me even start ranting about that pile of ... The only other alternative of Flash that I would personally consider is Silverlight, which allows streaming WMV Videos. I found the production of WMV much better and easier than FLV because all Windows FLV Encoders I tried are not really good and stable, whereas pretty much every tool can natively output WMV. The problem with Silverlight is that no one has that Browser Plugin (yet?). There is also a player from JW. "} {"user":"307","tags":["excel","csv","grid","clipboard"],"questionId":2563,"creationDate":"2008-08-05T16:47:28Z","title":"What is a good web-based Grid that accepts Excel clipboard data?","acceptedAnswerId":2801,"type":"question","body":"Any good recommendations for a platform agnostic (i.e. Javascript) grid control/plugin that will accept pasted Excel data and can emit Excel-compliant clipboard data during a Copy? I believe Excel data is formatted as CSV during \"normal\" clipboard operations. dhtmlxGrid looks promising, but the online demo's don't actually copy contents to my clipboard! "} {"user":"55","questionId":2543,"creationDate":"2008-08-05T16:49:06Z","answerId":2564,"type":"answer","body":"Is there a reason that you want it in Flash? If a plain, old PNG will work, try the Google Chart API. "} {"user":"91","questionId":2556,"creationDate":"2008-08-05T16:49:21Z","answerId":2565,"type":"answer","body":"Epoch is pretty large and available in US and EU: http://www.epoch.com/en/index.html I have no idea about their conditions though. "} {"user":"46","questionId":2550,"creationDate":"2008-08-05T16:49:31Z","answerId":2566,"type":"answer","body":"I have worked for a company that developed a system for distributing media content to dedicated \"players\". It was web based and used ASP.NET technology and have tried almost every possible media format you can think of and your choice really comes down to asking yourself: does it needs to play directly out of the box, or can I make sure that the components required to play the videos can be installed beforehand? If your answer is that it needs to play out of the box then really your only option is flash (I know that it is not installed by default, but most will already have it installed) If it is not a big issue that extra components are needed then you can go with formats that are supported by windows media player The reason why windows media player falls into the second option is because for some browsers and some formats extra components must be installed. We had the luxury that the \"players\" were provided by us, so we could go for the second option, however even we tried to convert as much as possible back to flash because it handles way better than windows media player "} {"user":"50","questionId":2556,"creationDate":"2008-08-05T16:52:43Z","answerId":2569,"type":"answer","body":"I'd have to go with paypal. I've used it in the past, and its really quite painless. All you need to do is create an account, and it's automatically available to you. "} {"user":"30","questionId":2543,"creationDate":"2008-08-05T16:53:15Z","answerId":2570,"type":"answer","body":"I can vouch that I've had good experiences with PHP/SWF charts (and by extension, the XML/SWF charts too). It's easy to create really subtle chart effects. Pie charts fading in one slice at a time looks fairly professional without being annoying. Edit: Scratch that, Open-Flash-Chart looks WAY better. I recede my suggestion. "} {"user":"285","questionId":2556,"creationDate":"2008-08-05T16:53:28Z","answerId":2571,"type":"answer","body":"http://www.authorize.net/ works well. This type of solution would allow your customer to enter his/her credit card directly. "} {"user":"423","questionId":2364,"creationDate":"2008-08-05T16:54:37Z","answerId":2575,"type":"answer","body":"If done right, unit testing can be very useful. But to be done right, it really has to be done from the beginning of the project, using some sort of TDD approach. If you write your code first, and then try to write unit tests for it later, you are going to be in for a world of hurt. The code will not likely be very testable, and what you will actually be writing are integration tests, not unit tests. If you are going to write \"true\" unit tests, you really need to use TDD principles such as Inversion of Control and Dependency Injection. Without these, you are really just writing integration tests, which are also useful, but they're not unit tests. "} {"user":"285","questionId":2543,"creationDate":"2008-08-05T16:54:48Z","answerId":2576,"type":"answer","body":"http://teethgrinder.co.uk/open-flash-chart/ seems really sweet. I suggest you give it a look. UPDATE: Open Flash Chart 2 is out: http://teethgrinder.co.uk/open-flash-chart-2/ "} {"user":"71","questionId":109,"creationDate":"2008-08-05T17:02:30Z","answerId":2585,"type":"answer","body":"Hazzah!!!! I went back to Michael's post, did some more poking and realized that I did need to do a double conversion, and eventually worked out this little nugget: Convert.ToString(Convert.ToChar(Int32.Parse(EncodedString.Substring(intParseIndex, 2), System.Globalization.NumberStyles.HexNumber))); From there I simply made a loop to go through all the characters 2 by 2 and get them \"hexified\" and then translated to a string. To Nick, and anybody else interested, I went ahead and posted my little application over in CodePlex. Feel free to use/modify as you need. "} {"user":"423","tags":["sql-server","windows"],"questionId":2588,"creationDate":"2008-08-05T17:07:16Z","title":"Appropriate Windows O/S pagefile size for SQL Server","acceptedAnswerId":1780172,"type":"question","body":"Does any know a good rule of thumb for the appropriate pagefile size for a Windows 2003 server running SQL Server? "} {"user":"72","questionId":2447,"creationDate":"2008-08-05T17:19:03Z","answerId":2596,"type":"answer","body":"I'm no expert on Agile development, but I would imagine that integrating some basic automated pen-test software into your build cycle would be a good start. I have seen several software packages out there that will do basic testing and are well suited for automation. "} {"user":"106","questionId":2486,"creationDate":"2008-08-05T17:20:25Z","answerId":2598,"type":"answer","body":"Basically, if your site still works with JavaScript turned off, then anything you add with JavaScript can be considered progressive enhancement. Some people may think that this is unnecessary, but plenty of people browse with addons like NoScript (or, with JavaScript simply turned off in their browser settings). In addition, many Mobile web browsers may or may not support JavaScript. So, it's always a good idea to test your site completely with and without JavaScript. "} {"user":"238","questionId":888,"creationDate":"2008-08-05T17:22:09Z","answerId":2599,"type":"answer","body":"You can use Firephp an add-on to firebug to debug php in the same environment as javascript. I also use Xdebug mentioned earlier for profiling php. "} {"user":"350","questionId":2563,"creationDate":"2008-08-05T17:23:21Z","answerId":2601,"type":"answer","body":"Not an answer, but a warning: my company bought the 2007 Infragistics ASP.NET controls just for the Grid, and we regret that choice. The quality of API is horrible (in our opinion at least), making it very hard to program against the grid (for example, inconsistent naming conventions, but this is just an inconvenience, we have complaints about the object model as well). So I can't say that I know of a better option, I just know I will give a try to something else before paying for Infragistics products again (and the email support we got was horrible as well). "} {"user":"431","questionId":1711,"creationDate":"2008-08-05T17:28:24Z","answerId":2602,"type":"answer","body":"Code Complete is the number one choice, but I'd also cite Gang of Four's Design Patterns and Craig Larman's Applying UML and Patterns. The Timeless Way of Building, by Christopher Alexander, is another great one. Even though it's about archtecture, it's included in the bibliography of many great programming books I have already read. Another one, from which I'm learning lots of new things, is Data Access Patterns, by Clifton Nock. "} {"user":"414","questionId":2364,"creationDate":"2008-08-05T17:34:49Z","answerId":2603,"type":"answer","body":"If you don't write unit tests from the start, alongside your code, they either do not get written or get written poorly. The first is the most common occurrence. "} {"user":"350","questionId":2556,"creationDate":"2008-08-05T17:35:24Z","answerId":2605,"type":"answer","body":"esellerate if it is Digital stuff that you are selling, I recommend http://www.esellerate.net/ . they have nice support for website payment, delivery of serial numbers upon sell and even have API so you can integrate the buying process into your application in case it is a desktop application. "} {"user":"431","questionId":1284,"creationDate":"2008-08-05T17:38:53Z","answerId":2608,"type":"answer","body":"Oracle has got an online tutorial about SQL Injection. Even though you want a ready-made solution, this might give you some hints on how to use it better to defend yourself. "} {"user":"17","questionId":2556,"creationDate":"2008-08-05T17:40:27Z","answerId":2609,"type":"answer","body":"Well by cheap do you mean processing fees or month fees? Also is this for micro or normal transactions? PayPal in my experience is an all around good choice because it offers both starter to professional level payment processing services that fit most needs. "} {"user":"17","questionId":2483,"creationDate":"2008-08-05T17:46:00Z","answerId":2614,"type":"answer","body":"Here is a good way to remember the process that each of them follow that I use when trying to decide which is better for my circumstance. DateTime i = (DateTime)value; // is like doing DateTime i = value is DateTime ? value as DateTime : throw new Exception(...); and the next should be easy to guess what it does DateTime i = value as DateTime; in the first case if the value cannot be cast than an exception is thrown in the second case if the value cannot be cast, i is set to null. So in the first case a hard stop is made if the cast fails in the second cast a soft stop is made and you might encounter a NullReferenceException later on. "} {"user":"373","questionId":2556,"creationDate":"2008-08-05T17:48:39Z","answerId":2619,"type":"answer","body":"I've used CyberSource in the past, and had a good experience. They support several interfaces including SOAP, they work internationally, and have a pretty good web interface. I'm not sure about a cheap, though. http://www.cybersource.com/products_and_services/global_payment_services/credit_card_processing/ "} {"user":"198","questionId":2447,"creationDate":"2008-08-05T17:50:49Z","answerId":2620,"type":"answer","body":"I'm not a security expert, but I think the most important fact you should be aware of, before testing security, is what you are trying to protect. Only if you know what you are trying to protect, you can do a proper analysis of your security measures and only then you can start testing those implemented measures. Very abstract, I know. However, I think it should be the first step of every security audit. "} {"user":"383","questionId":651,"creationDate":"2008-08-05T18:01:12Z","answerId":2629,"type":"answer","body":"In IIS, enable annonymous access and allow the web.config to handle user authentication. If this doesn't work, please can you send a sample of your web.config. "} {"user":"17","tags":["powershell","cmdlets"],"questionId":2630,"creationDate":"2008-08-05T18:01:32Z","title":"What are your favorite Powershell Cmdlets?","acceptedAnswerId":64636,"type":"question","body":"I just found /n softwares free Powershell NetCmdlets, and after playing with them I love the functionality they bring to the command line. So it raises the question what are your favorite Cmdlets, and how do you use them? "} {"user":"434","tags":["language-agnostic"],"questionId":2639,"creationDate":"2008-08-05T18:07:26Z","title":"What are some web-based knowledge-base solutions?","acceptedAnswerId":2712,"type":"question","body":"I've used a WordPress blog and a Screwturn Wiki (at two separate jobs) to store private, company-specific KB info, but I'm looking for something that was created to be a knowledge base. Specifically, I'd like to see: Free/low cost Simple method for users to subscribe to KB (or just sections) to get updates Ability to do page versioning/audit changes Limit access to certain pages for certain users Very simple method of posting/editing articles Very simple method of adding images to articles Excellent (fast, accurate) searching abilities Ability to rate and comment on articles I liked using the Wordpress blog because it allowed me to use Live Writer to add/edit articles and images, but it didn't have page versioning (that I could see). I like using Screwturn wiki because of it's ability to track article versions, and I like it's clean look, but some non-technical people balk at the input and editing. "} {"user":"225","questionId":2639,"creationDate":"2008-08-05T18:12:14Z","answerId":2643,"type":"answer","body":"Cerberus - it's more a full featured Help Desk/Issue Tracking system but it has a nice KB solution built in. It can be free but they do have a low cost pay version that is also very good. "} {"user":"383","tags":["sql","sql-server-2005","split"],"questionId":2647,"creationDate":"2008-08-05T18:15:47Z","title":"How do I split a string so I can access item x?","acceptedAnswerId":2657,"type":"question","body":"Using SQL Server 2005, how do I split a string so I can access item x? For example Take a string \"Hello John Smith\". How can I split the string by space and access the item at index 1 which should return \"John\"? "} {"user":"434","tags":["sql-server"],"questionId":2649,"creationDate":"2008-08-05T18:18:39Z","title":"What's the best way to determine if a temporary table exists in SQL Server?","acceptedAnswerId":2653,"type":"question","body":"When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it). I'll post the method that I use, but I'd like to see if there is a better way. "} {"user":"434","questionId":2649,"creationDate":"2008-08-05T18:21:31Z","answerId":2652,"type":"answer","body":"The OBJECT_ID function returns the internal object id for the given object name and type. 'tempdb..#t1' refers to the table #t1 in the tempdb database. 'U' is for user-defined table. IF OBJECT_ID('tempdb..#t1', 'U') IS NOT NULL DROP TABLE #t1 CREATE TABLE #t1 ( id INT IDENTITY(1,1), msg VARCHAR(255) ) "} {"user":"383","questionId":2649,"creationDate":"2008-08-05T18:21:38Z","answerId":2653,"type":"answer","body":"IF Object_Id('TempDB..#TempTable') IS NOT NULL BEGIN DROP TABLE #TempTable END "} {"user":"152","questionId":2647,"creationDate":"2008-08-05T18:28:38Z","answerId":2657,"type":"answer","body":"You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project). You can use this simple logic: Declare @products varchar(200) = '1|20|3|343|44|6|8765' Declare @individual varchar(20) = null WHILE LEN(@products) > 0 BEGIN IF PATINDEX('%|%', @products) > 0 BEGIN SET @individual = SUBSTRING(@products, 0, PATINDEX('%|%', @products)) SELECT @individual SET @products = SUBSTRING(@products, LEN(@individual + '|') + 1, LEN(@products)) END ELSE BEGIN SET @individual = @products SET @products = NULL SELECT @individual END END "} {"user":"406","tags":["git","svn","version-control","language-agnostic","dvcs"],"questionId":2658,"creationDate":"2008-08-05T18:29:14Z","title":"Getting started with Version Control","acceptedAnswerId":2668,"type":"question","body":"I need to implement version control, even for just the developing I do at home. I have read about how great Subversion is for the past couple years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system. Given the situation, should I hold off and see which one comes out on top? What are their relative advantages? One issue I noticed with Git is there are not many full featured GUIs, which is important to many users on my team. Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.) "} {"user":"380","questionId":2639,"creationDate":"2008-08-05T18:31:19Z","answerId":2662,"type":"answer","body":"I think Drupal is a very possible choice. It has a lot of built-in support for book-type information capturing. And there is a rich collection of user generated modules which you can use to enhance the features. I think it has almost all the features you ask for out of the box. Drupal CMS Benefits "} {"user":"34","questionId":2658,"creationDate":"2008-08-05T18:31:56Z","answerId":2665,"type":"answer","body":"Use subversion, it's easy to setup, easy to use, and has plenty of tools. Any future revision system will have an import from SVN feature, so it isn't like you can't change down the road if your needs grow. "} {"user":"380","questionId":2658,"creationDate":"2008-08-05T18:33:56Z","answerId":2667,"type":"answer","body":"Go for SVN. If you have never used source control before, it won't matter to you one way or the other. Also, there is not a large amount of learning involved in using a Source Control system. If you learn one, you can easily switch over to another at a later date. SVN is a great tool, and it should take care of most of your needs. And since it's been around, it has a fair sharer of GUI tools (TortoiseSVN, for example). Go for SVN. "} {"user":"309844","questionId":2658,"creationDate":"2008-08-05T18:34:44Z","answerId":2668,"type":"answer","body":"The most important thing about version control is: JUST START USING IT Not using version control is a horrible idea. If you are not using version control, stop reading right now and start using it. It is very easy to convert from cvs<->svn<->git<->hg It doesn't matter which one you choose. Just pick the easiest one for you to use and start recording the history of your code. You can always migrate to another (D)VCS later. If you are looking for a easy to use GUI look at TortoiseSVN (Windows) and Versions (Mac) (Suggested by codingwithoutcomments) Edit: pix0r said: Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion. This. Using git is pointless if you don't know what version control can do for you. Edit 2: Just saw this link on reddit: Subversion Cheat Sheet. Good quick reference for the svn command line. "} {"user":"149","questionId":2658,"creationDate":"2008-08-05T18:35:27Z","answerId":2669,"type":"answer","body":"Don't wait. Pick one, and go with it. All systems will have their pluses and minuses. Your power could go out, you computer gets stolen, or you forget to undo a major change and all your code gets fried while you're waiting to see who emerges victorious. "} {"user":"383","questionId":2658,"creationDate":"2008-08-05T18:36:01Z","answerId":2670,"type":"answer","body":"When I decided I must use a code versioning system, I looked around for any good tutorials on how to get started but didn't find any that could help me. So I simplely installed the SVN Server and Tortoise SVN for the client and dived into the deepend and i learn't how to use it along the way. "} {"user":"71","questionId":2647,"creationDate":"2008-08-05T18:36:15Z","answerId":2671,"type":"answer","body":"Well, mine isn't all that simpler, but here is the code I use to split a comma-delimited input variable into individual values, and put it into a table variable. I'm sure you could modify this slightly to split based on a space and then to do a basic SELECT query against that table variable to get your results. -- Create temporary table to parse the list of accounting cycles. DECLARE @tblAccountingCycles table ( AccountingCycle varchar(10) ) DECLARE @vchAccountingCycle varchar(10) DECLARE @intPosition int SET @vchAccountingCycleIDs = LTRIM(RTRIM(@vchAccountingCycleIDs)) + ',' SET @intPosition = CHARINDEX(',', @vchAccountingCycleIDs, 1) IF REPLACE(@vchAccountingCycleIDs, ',', '') <> '' BEGIN WHILE @intPosition > 0 BEGIN SET @vchAccountingCycle = LTRIM(RTRIM(LEFT(@vchAccountingCycleIDs, @intPosition - 1))) IF @vchAccountingCycle <> '' BEGIN INSERT INTO @tblAccountingCycles (AccountingCycle) VALUES (@vchAccountingCycle) END SET @vchAccountingCycleIDs = RIGHT(@vchAccountingCycleIDs, LEN(@vchAccountingCycleIDs) - @intPosition) SET @intPosition = CHARINDEX(',', @vchAccountingCycleIDs, 1) END END The concept is pretty much the same. One other alternative is to leverage the .NET compatibility within SQL Server 2005 itself. You can essentially write yourself a simple method in .NET that would split the string and then expose that as a stored procedure/function. "} {"user":"72","questionId":2658,"creationDate":"2008-08-05T18:36:48Z","answerId":2672,"type":"answer","body":"The Subversion Book is your best bet for learning the tool. There may be other quick-start tutorials out there, but the Book is the best single reference you'll find. Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion. I'd definitely agree with the previous posters and start with Subversion. "} {"user":"227","questionId":2658,"creationDate":"2008-08-05T18:38:00Z","answerId":2673,"type":"answer","body":"Start using SVN for your actual work, but try to make time for fiddling around with Git and/or Mercurial. SVN is reasonably stable for production, but eventually you'll face a scenario where you'll need a distributed SCM, by which time you'll be properly armed and the new systems will be mature enough. "} {"user":"423","questionId":2658,"creationDate":"2008-08-05T18:39:20Z","answerId":2675,"type":"answer","body":"My vote goes to Subversion. It's very powerful, yet easy to use, and has some great tools like TortoiseSVN. But as others have said before me, JUST START USING IT. Source control is such an important part of the software development process. No \"serious\" software project should be without it. "} {"user":"266","questionId":2658,"creationDate":"2008-08-05T18:39:23Z","answerId":2676,"type":"answer","body":"For a friendly explanation of most of the basic concepts, see A Visual Guide to Version Control. The article is very SVN-friendly. "} {"user":"225","questionId":2647,"creationDate":"2008-08-05T18:39:58Z","answerId":2677,"type":"answer","body":"Here is a UDF which will do it. It will return a table of the delimited values, haven't tried all scenarios on it but your example works fine. CREATE FUNCTION SplitString ( -- Add the parameters for the function here @myString varchar(500), @deliminator varchar(10) ) RETURNS @ReturnTable TABLE ( -- Add the column definitions for the TABLE variable here [id] [int] IDENTITY(1,1) NOT NULL, [part] [varchar](50) NULL ) AS BEGIN Declare @iSpaces int Declare @part varchar(50) --initialize spaces Select @iSpaces = charindex(@deliminator,@myString,0) While @iSpaces > 0 Begin Select @part = substring(@myString,0,charindex(@deliminator,@myString,0)) Insert Into @ReturnTable(part) Select @part Select @myString = substring(@mystring,charindex(@deliminator,@myString,0)+ len(@deliminator),len(@myString) - charindex(' ',@myString,0)) Select @iSpaces = charindex(@deliminator,@myString,0) end If len(@myString) > 0 Insert Into @ReturnTable Select @myString RETURN END GO You would call it like this: Select * From SplitString('Hello John Smith',' ') Edit: Updated solution to handle delimters with a len>1 as in : select * From SplitString('Hello**John**Smith','**') "} {"user":"137","questionId":2658,"creationDate":"2008-08-05T18:40:30Z","answerId":2678,"type":"answer","body":"Yup, SVN for preference unless you really need git's particular features. SVN is hard enough; It sounds like git is more complicated to live with. You can get hosted svn from people like Beanstalk - unless you have in-house Linux people, I'd really recommend it. Things can go wrong horribly easily and it's nice to have someone else whose job it is to fix it. There's an excellent tutorial on revision control from Eric Sink which is worth reading no matter which system you use. "} {"user":"357","questionId":2647,"creationDate":"2008-08-05T18:41:34Z","answerId":2681,"type":"answer","body":"Try this: CREATE function [SplitWordList] ( @list varchar(8000) ) returns @t table ( Word varchar(50) not null, Position int identity(1,1) not null ) as begin declare @pos int, @lpos int, @item varchar(100), @ignore varchar(100), @dl int, @a1 int, @a2 int, @z1 int, @z2 int, @n1 int, @n2 int, @c varchar(1), @a smallint select @a1 = ascii('a'), @a2 = ascii('A'), @z1 = ascii('z'), @z2 = ascii('Z'), @n1 = ascii('0'), @n2 = ascii('9') set @ignore = '''\"' set @pos = 1 set @dl = datalength(@list) set @lpos = 1 set @item = '' while (@pos <= @dl) begin set @c = substring(@list, @pos, 1) if (@ignore not like '%' + @c + '%') begin set @a = ascii(@c) if ((@a >= @a1) and (@a <= @z1)) or ((@a >= @a2) and (@a <= @z2)) or ((@a >= @n1) and (@a <= @n2)) begin set @item = @item + @c end else if (@item > '') begin insert into @t values (@item) set @item = '' end end set @pos = @pos + 1 end if (@item > '') begin insert into @t values (@item) end return end Test it like this: select * from SplitWordList('Hello John Smith') "} {"user":"305","questionId":2658,"creationDate":"2008-08-05T18:41:38Z","answerId":2682,"type":"answer","body":" superjoe30 writes: Related question (perhaps answers can be edited to answer this question as well): What about using source control on your own computer, if you're the sole programmer? Is >>this good practice? Are there related tips or tricks? I use SVN for all of my personal projects. I started off with running svn on my home machine but eventually migrated over to Dreamhost. Their hosting packages that include Subversion are pretty reasonable. "} {"user":"434","questionId":2647,"creationDate":"2008-08-05T18:45:19Z","answerId":2685,"type":"answer","body":"I don't believe SQL Server has a built-in split function, so other than a UDF, the only other answer I know is to hijack the PARSENAME function: SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 2) PARSENAME takes a string and splits it on the period character. It takes a number as its second argument, and that number specifies which segment of the string to return (working from back to front). SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 3) --return Hello Obvious problem is when the string already contains a period. I still think using a UDF is the best way...any other suggestions? "} {"user":"327","questionId":2639,"creationDate":"2008-08-05T18:45:29Z","answerId":2687,"type":"answer","body":"I've also been investigating wiki software for use as a KB, but it is tricky to find something that is easy to use for non-technical people. There are many wikis that attempt to provide WYSIWYG editing, but most of the software I've found generates nasty inefficient html markup from the WYSIWYG editor. One notable exception to this is Confluence which generates wiki syntax from a WYSIWYG editor. This still isn't perfect (show me a WYSIWYG editor that is) but is a pretty good compromise between retaining simple wiki syntax for those who like it and allowing non-technical users to contribute content. The only problem is that Confluence isn't free ($1,200 for 25 user license). Edit: I also tried DekiWiki and while the UI is nice it doesn't seem to be quite ready for primetime (suffers terribly from the bad WYSIWYG output disease mentioned above). Also seems like they lack direction as there are so many different ways of accomplishing the same task. "} {"user":"432","tags":["mysql","oracle","security"],"questionId":2688,"creationDate":"2008-08-05T18:45:46Z","title":"What do I need to escape when sending a query?","acceptedAnswerId":2741,"type":"question","body":"When you execute a SQL query, you have to clean your strings or users can execute malicious SQL on your website. I usually just have a function escape_string(blah), which: Replaces escapes (\\) with double escapes (\\\\). Replaces single quotes (') with an escaped single quote (\\'). Is this adequate? Is there a hole in my code? Is there a library which can do this quickly and reliably for me? I'd like to see graceful solutions in Perl, Java, and PHP. "} {"user":"305","questionId":2688,"creationDate":"2008-08-05T18:46:41Z","answerId":2690,"type":"answer","body":"Which language are using? It seems like pretty much all of them have built-in SQL escape functions that would be better to use. For example, PHP has mysql_real_escape_string and addslashes. "} {"user":"383","questionId":2688,"creationDate":"2008-08-05T18:46:45Z","answerId":2691,"type":"answer","body":"I would also escape comments (double dash) -- "} {"user":"34","questionId":2688,"creationDate":"2008-08-05T18:48:23Z","answerId":2693,"type":"answer","body":"You're better off using prepared statements with placeholders. Are you using PHP, .NET...either way, prepared statements will provide more security, but I could provide a sample. "} {"user":"137","questionId":2556,"creationDate":"2008-08-05T18:49:46Z","answerId":2695,"type":"answer","body":"I've looked at WorldPay and SecPay in the past; you need to know your onions to use them competently, I think - if you want really nice integration, at any rate. "} {"user":"45","questionId":2688,"creationDate":"2008-08-05T18:49:58Z","answerId":2696,"type":"answer","body":"I am not sure if MySql supports parameterized queries, if so, you should make an effort to go this route. This will ensure the users input can't do anything malicious. Otherwise some \"bad\" characters in addition to what you mentioned would be semicolon (;) and comments (-- and /* */). "} {"user":"199","questionId":2540,"creationDate":"2008-08-05T18:50:09Z","answerId":2697,"type":"answer","body":"The Glib library used on the Gnome project may also be some use. Moreover it is pretty well tested. IBM developer works has a good tutorial on its use: Manage C data using the GLib collections "} {"user":"36","questionId":2630,"creationDate":"2008-08-05T18:53:44Z","answerId":2699,"type":"answer","body":"While semi-related to your question, it does not entirely fit the Powershell NetCmdlets motif. But I wanted to post it anyhow as I use it daily and it may help others. Simply making shift-control-c key combo into displaying the visual studio command prompt. "} {"user":"342","questionId":1131,"creationDate":"2008-08-05T18:55:00Z","answerId":2701,"type":"answer","body":" PDF has the disadvantage of requiring the Adobe Reader I use Foxit Reader on Windows at home and at work. A lot smaller and very quick to open. Very handy when you are wondering what exactly a80000326.pdf is and why it is clogging up your documents folder. "} {"user":"357","tags":["sql","sql-server","group-by"],"questionId":2702,"creationDate":"2008-08-05T18:55:35Z","title":"How do I use T-SQL Group By","acceptedAnswerId":2736,"type":"question","body":"I know I need to have (although I don't know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count, sum, avg, etc: SELECT count(userID), userName FROM users GROUP BY userName When else would GROUP BY be useful, and what are the performance ramifications? "} {"user":"224","questionId":2647,"creationDate":"2008-08-05T18:57:03Z","answerId":2703,"type":"answer","body":"First, create a function (using CTE, common table expression does away with the need for a temp table) create function dbo.SplitString ( @str nvarchar(4000), @separator char(1) ) returns table AS return ( with tokens(p, a, b) AS ( select 1, 1, charindex(@separator, @str) union all select p + 1, b + 1, charindex(@separator, @str, b + 1) from tokens where b > 0 ) select p-1 zeroBasedOccurance, substring( @str, a, case when b > 0 then b-a ELSE 4000 end) AS s from tokens ) GO Then, use it as any table (or modify it to fit within your existing stored proc) like this. select s from dbo.SplitString('Hello John Smith', ' ') where zeroBasedOccurance=1 Update Previous version would fail for input string longer than 4000 chars. This version takes care of the limitation: create function dbo.SplitString ( @str nvarchar(max), @separator char(1) ) returns table AS return ( with tokens(p, a, b) AS ( select cast(1 as bigint), cast(1 as bigint), charindex(@separator, @str) union all select p + 1, b + 1, charindex(@separator, @str, b + 1) from tokens where b > 0 ) select p-1 ItemIndex, substring( @str, a, case when b > 0 then b-a ELSE LEN(@str) end) AS s from tokens ); GO Usage remains the same. "} {"user":"383","questionId":2702,"creationDate":"2008-08-05T18:58:35Z","answerId":2704,"type":"answer","body":"Counting the number of times tags are used might be a google example: SELECT TagName, Count(*) AS TimesUsed FROM Tags GROUP BY TagName ORDER TimesUsed If you simply want a distinct value of tags, I would prefer to use the DISTINCT statement. SELECT DISTINCT TagName FROM Tags ORDER BY TagName ASC "} {"user":"71","questionId":2702,"creationDate":"2008-08-05T19:00:39Z","answerId":2706,"type":"answer","body":"GROUP BY also helps when you want to generate a report that will average or sum a bunch of data. You can GROUP By the Department ID and the SUM all the sales revenue or AVG the count of sales for each month. "} {"user":"414","questionId":2702,"creationDate":"2008-08-05T19:01:10Z","answerId":2707,"type":"answer","body":"Group By forces the entire set to be populated before records are returned (since it is an implicit sort). For that reason (and many others), never use a Group By in a subquery. "} {"user":"25","questionId":2658,"creationDate":"2008-08-05T19:01:55Z","answerId":2708,"type":"answer","body":"If you are on Mac OSX, I found http://www.versionsapp.com/\">Versions to be an incredible (free) GUI front-end to SVN. "} {"user":"434","tags":["language-agnostic"],"questionId":2709,"creationDate":"2008-08-05T19:06:40Z","title":"How can you tell when a user last pressed a key (or moved the mouse)?","type":"question","body":"In a Win32 environment, you can use the GetLastInputInfo API call see msdn doc. Basically, this method returns the last tick that corresponds with when the user last provided input, and you have to compare that to the current tick to determine how long ago that was. Xavi23cr has a good example for C# at codeproject. Any suggestions for other environments? "} {"user":"45","tags":["css","templates"],"questionId":2711,"creationDate":"2008-08-05T19:08:47Z","title":"What sites offer free, quality web site design templates?","acceptedAnswerId":2763,"type":"question","body":"Let's aggregate a list of free quality web site design templates. There are a million of these sites out there, but most are repetitive and boring. I'll start with freeCSStemplates.org I also think other sites should follow some sort of standards, for example here are freeCSStemplates standards Released for FREE under the Creative Commons Attribution 2.5 license Very lightweight in terms of images Tables-free (ie. they use no tables for layout purposes) W3C standards compliant and valid (XHTML Strict) Provided with public domain photos, generously provided by PDPhoto.org and Wikimedia Commons "} {"user":"350","questionId":2639,"creationDate":"2008-08-05T19:09:08Z","answerId":2712,"type":"answer","body":"I second Luke's answer. I can Recommend Confluence and here is why: I tested extensively many commercial and free Wiki based solutions. Not a single one is a winner on all accounts, including confluence. Let me try to make your quest a little shorter by summarizing what I have learned to be a pain and what is important: WYSIWYG is a most have feature for the Enterprise. A wiki without it, skip it Saying that, in reality, WYSIWYG doesn't work perfectly. It is more of a feature you must have to get the casual users not be afraid of the monster, and start using it. But you and anyone that wants to seriously create content, will very quickly get used to the wiki markup. it is faster and more reliable. You need good permissions controls (who can see, edit etc' a page). confluence has good, but I have my complaints (to complicated to be put here) You will want a good export feature. Most will give you a single page \"PDF\" export, but you need much more. For example, lets say you have an FAQ, you want to export the entire FAQ right? will that work? Macros: you want a community creating macros. You asked for example about the ability to rate pages, here is a link to a Macro for Confluence that lets you do that Structure: you want to be able to say that a page is a child of a different page, and be able to browse the data. The wikipedia model, of orphaned pages with no sturcture will not work in the Enterprise. (think FAQ, you want to have a hierarchy no?) Ability to easily attache picture to be embedded in the body of the page/article. In confluence, you need to upload the image and then can embed it, it could be a little better (CTR+V) but I guess this is easy enough for 80% of the users. At the end of the day, remember that a Wiki will be valuable to you the more flexible it is. It needs to be a \"blank\" canvas, and your imagination is then used to \"build\" the application. In Confluence, I found 3 different \"best practices\" on how to create a FAQ. That means I can implement MANY things. Some examples (I use my Wiki for) FAQ: any error, problem is logged. Used by PS and ENG. reduced internal support time dramatically Track account status: I implemetned sophisticated \"dashboard\" that you can see at a glance which customer is at what state, the software version they have, who in the company 'owns\" the custoemr etc' Product: all documentation, installation instructions, the \"what's new\" etc Technical documentation, DB structure and what the tables mean HR: contact list, Document repository My runner up (15 month ago) was free Deki_Wiki, time has passed, so I don't know if this would be still my runner up. good luck! "} {"user":"414","questionId":2711,"creationDate":"2008-08-05T19:10:49Z","answerId":2713,"type":"answer","body":"http://www.csszengarden.com/ The images are not Creative Commons, but the CSS is. "} {"user":"434","tags":["sql-server"],"questionId":2714,"creationDate":"2008-08-05T19:10:52Z","title":"I need to know how much disk space a table is using in SQL Server","acceptedAnswerId":2715,"type":"question","body":"I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks. "} {"user":"434","questionId":2714,"creationDate":"2008-08-05T19:11:11Z","answerId":2715,"type":"answer","body":" CREATE TABLE #tmpSizeChar ( table_name sysname , row_count int, reserved_size varchar(50), data_size varchar(50), index_size varchar(50), unused_size varchar(50)) CREATE TABLE #tmpSizeInt ( table_name sysname , row_count int, reserved_size_KB int, data_size_KB int, index_size_KB int, unused_size_KB int) SET NOCOUNT ON INSERT #tmpSizeChar EXEC sp_msforeachtable 'sp_spaceused ''?''' INSERT INTO #tmpSizeInt ( table_name, row_count, reserved_size_KB, data_size_KB, index_size_KB, unused_size_KB ) SELECT [table_name], row_count, CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size, CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size, CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size, CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_size FROM #tmpSizeChar /* DROP TABLE #tmpSizeChar DROP TABLE #tmpSizeInt */ SELECT * FROM #tmpSizeInt ORDER BY reserved_size_KB DESC "} {"user":"92","questionId":2711,"creationDate":"2008-08-05T19:11:45Z","answerId":2716,"type":"answer","body":"+1 for Zen garden. I like the resources at inobscuro.com "} {"user":"432","questionId":2709,"creationDate":"2008-08-05T19:14:47Z","answerId":2720,"type":"answer","body":"As for Linux, I know that Pidgin has to determine idle time to change your status to away after a certain amount of time. You might open the source and see if you can find the code that does what you need it to do. "} {"user":"225","questionId":2714,"creationDate":"2008-08-05T19:16:19Z","answerId":2721,"type":"answer","body":"Check out this, I know it works in 2005 (MSDN Doc): Here is is for the pubs DB select * from pubs.sys.database_files Returns the size and max_size. "} {"user":"30","questionId":2658,"creationDate":"2008-08-05T19:18:37Z","answerId":2723,"type":"answer","body":"At my current job, my predecessor did not use any kind of version control. There are just mountains of folders in at least 3 different places where he kept all of his projects. Any random project folder can be expected to find at least one folder name \"project (OLD)\" and one named \"project\" With version control, you never have to make copies of \"safe\" builds. You don't really have to worry about your IDE corrupting the file you're working on (I'm looking at you, REALBasic 5.5) because is so easy to commit (Read: Save) your work every day. Needless to say, I installed version control the day after I found out it existed. Also, TortoiseSVN makes committing to the database as easy as right clicking a folder. "} {"user":"423","questionId":2711,"creationDate":"2008-08-05T19:19:03Z","answerId":2724,"type":"answer","body":"The Open Design Community is a great resource. "} {"user":"435","questionId":2688,"creationDate":"2008-08-05T19:21:49Z","answerId":2727,"type":"answer","body":"In PHP, I'm using this one and I'll appreciate every comment about it : function quote_smart($valeur) { if (get_magic_quotes_gpc()) $valeur = stripslashes($valeur); if (!is_numeric($valeur)) $valeur = mysql_real_escape_string($valeur); return $valeur; } $IdS = quote_smart($_POST['theID']); $sql = \" SELECT * FROM Students WHERE IdStudent={$IdS}; \"; Needs one more verification if a field can be NULL : $picture = NULL; $theidyouwant = 7; $Name = 'WOOD'; if(is_null($picture)) $p = 'NULL'; else $p = \"'\".quote_smart($picture).\"'\"; $IdS = quote_smart($theidyouwant); $requete = \"SELECT * FROM Students WHERE IdStudent={$IdS} AND PictureStudent={$p} AND NameStudent='{$Name}'; \"; That's it enjoy ! (hope the post will correctly send underscores and not _ ;) "} {"user":"34","questionId":2711,"creationDate":"2008-08-05T19:25:06Z","answerId":2731,"type":"answer","body":"http://www.opensourcetemplates.org/ has nice designs, just not enough selection. "} {"user":"75","tags":["linux","bash","shell","ksh","dash"],"questionId":2732,"creationDate":"2008-08-05T19:26:00Z","title":"Shell scripting input redirection oddities","acceptedAnswerId":11668996,"type":"question","body":"Can anyone explain this behavior? Running: #!/bin/sh echo \"hello world\" | read var1 var2 echo $var1 echo $var2 results in nothing being ouput, while: #!/bin/sh echo \"hello world\" > test.file read var1 var2 < test.file echo $var1 echo $var2 produces the expected output: hello world Shouldn't the pipe do in one step what the redirection to test.file did in the second example? I tried the same code with both the dash and bash shells and got the same behavior from both of them. "} {"user":"58","questionId":2688,"creationDate":"2008-08-05T19:28:29Z","answerId":2734,"type":"answer","body":"A great thing to use in PHP is the PDO. It takes a lot of the guesswork out of dealing with securing your SQL (and all of your SQL stuff in general). It supports prepared statements, which go a long way towards thwarting SQL Injection Attacks. A great primer on PDO is included in the book The PHP Anthology 101 Essential Tips, Tricks & Hacks by Davey Shafik etc. 2nd Ed. Makes learning a breeze and is excellent as a reference. I don't even have to think about anything other than the actual SQL Query anymore. "} {"user":"404","questionId":2702,"creationDate":"2008-08-05T19:32:03Z","answerId":2736,"type":"answer","body":"To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this: SELECT WidgetCategory, count(*) FROM Widgets GROUP BY WidgetCategory HAVING count(*) > 5 The \"having\" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there. "} {"user":"434","questionId":2563,"creationDate":"2008-08-05T19:32:40Z","answerId":2737,"type":"answer","body":"I was wrestling with this problem several years ago (2004 I think). We ran into the problem that Firefox doesn't allow scripts to read the clipboard by default (but you can grant access to the clipboard). There's other ways of reading the clipboard data as well...Flash, for instance, can read the clipboard. There's a good article on ajaxian to explain how do to this behind the scenes. In the end, we couldn't find a web-based Grid that fit the bill, so we had to create our own in a mixture of Actionscript and Javascript. "} {"user":"116","questionId":2688,"creationDate":"2008-08-05T19:38:51Z","answerId":2741,"type":"answer","body":"For maximum security, performance, and correctness use prepared statements. Here's how to do this with lots of examples in different languages, including PHP: https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks "} {"user":"304","tags":["ide","erlang"],"questionId":2742,"creationDate":"2008-08-05T19:39:19Z","title":"Setting up an Erlang development environment","type":"question","body":"I'm interested in looking at Erlang and want to follow the path of least resistance in getting up and running. At present, I'm planning on installing Erlang R12B-3 and Erlide (Eclipse plugin). This is largely a Google-result-based decision. Initially this will be on a Windows XP system, though I am likely to reproduce the environment on Ubuntu shortly after. Is there a significantly better choice? Even if it is tied to one platform. Please share your experiences. "} {"user":"435","tags":["optimization","setter","getter","verification"],"questionId":2750,"creationDate":"2008-08-05T19:51:29Z","title":"Data verifications in Getter/Setter or elsewhere?","acceptedAnswerId":2761,"type":"question","body":"I'm wondering if it's a good idea to make verifications in getters and setters, or elsewhere in the code. This might surprise you be when it comes to optimizations and speeding up the code, I think you should not make verifications in getters and setters, but in the code where you're updating your files or database. Am I wrong? "} {"user":"415","questionId":2688,"creationDate":"2008-08-05T19:55:12Z","answerId":2752,"type":"answer","body":"Use Prepared/Parameterized queries! "} {"user":"383","questionId":622,"creationDate":"2008-08-05T19:55:17Z","answerId":2753,"type":"answer","body":"I have adapted code found on the CodeProject to create the following: ArrayList primeNumbers = new ArrayList(); for(int i = 2; primeNumbers.Count < 10000; i++) { bool divisible = false; foreach(int number in primeNumbers) { if(i % number == 0) { divisible = true; } } if(divisible == false) { primeNumbers.Add(i); Console.Write(i + \" \"); } } Testing this on my ASP.NET Server took the rountine about 1 minute to run. "} {"user":"92","questionId":2750,"creationDate":"2008-08-05T19:55:52Z","answerId":2754,"type":"answer","body":"Validation should be captured separately from getters or setters in a validation method. That way if the validation needs to be reused across multiple components, it is available. When the setter is called, such a validation service should be utilized to sanitize input into the object. That way you know all information stored in an object is valid at all times. You don't need any kind of validation for the getter, because information on the object is already trusted to be valid. Don't save your validation until a database update!! It is better to fail fast. "} {"user":"423","questionId":1607,"creationDate":"2008-08-05T19:56:43Z","answerId":2755,"type":"answer","body":"My team scripts out all database changes, and commits those scripts to SVN, along with each release of the application. This allows for incremental changes of the database, without losing any data. To go from one release to the next, you just need to run the set of change scripts, and your database is up-to-date, and you've still got all your data. It may not be the easiest method, but it definitely is effective. "} {"user":"431","tags":["php","c++","linux","ide","freeware"],"questionId":2756,"creationDate":"2008-08-05T19:57:11Z","title":"Lightweight IDE for Linux","acceptedAnswerId":2762,"type":"question","body":"Even though I have a robust and fast computer (Pentium Dual Core 2.0 with 2Gb RAM), I'm always searching for lightweight software to have on it, so it runs fast even when many apps are up and running simultaneously. On the last few weeks I've been migrating gradually to Linux and want to install a free lightweight yet useful IDE to program on C++ and PHP. Sintax highlighting and code completition tips are must-haves. So, I'd like to receive some suggestions from you, guys. "} {"user":"357","questionId":2750,"creationDate":"2008-08-05T19:59:05Z","answerId":2757,"type":"answer","body":"From the perspective of having the most maintainable code, I think you should do as much validation as you can in the setter of a property. This way you won't be caching or otherwise dealing with invalid data. After all, this is what properties are meant for. If all you have is a bunch of properties like... public string Name { get { return _name; } set { _name = value; } } ... they might as well be fields "} {"user":"304","questionId":2750,"creationDate":"2008-08-05T19:59:13Z","answerId":2760,"type":"answer","body":"It depends. Generally, code should fail fast. If the value can be set by multiple points in the code and you validate only on after retrieving the value, the bug appears to be in the code that does the update. If the setters validate the input, you know what code is trying to set invalid values. "} {"user":"91","questionId":2750,"creationDate":"2008-08-05T19:59:39Z","answerId":2761,"type":"answer","body":"Well, one of the reaons why classes usually contain private members with public getters/setters is exactly because they can verify data. If you have a Number than can be between 1 and 100, i would definitely put something in the setter that validates that and then maybe throw an exception that is being caught by the code. The reason is simple: If you don't do it in the setter, you have to remember that 1 to 100 limitation every time you set it, which leads to duplicated code or when you forget it, it leads to an invalid state. As for performance, i'm with Knuth here: \"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.\" "} {"user":"432","questionId":2756,"creationDate":"2008-08-05T19:59:59Z","answerId":2762,"type":"answer","body":"gedit Syntax highlighting Fast, lightweight Tabs GUI "} {"user":"415","questionId":2711,"creationDate":"2008-08-05T20:00:14Z","answerId":2763,"type":"answer","body":"Check out: Open Source Web Designs CSS Remix Best Web Gallery CSS Based CSS Beauty CSS Genius "} {"user":"116","questionId":2732,"creationDate":"2008-08-05T20:00:43Z","answerId":2764,"type":"answer","body":"It's because the pipe version is creating a subshell, which reads the variable into its local space which then is destroyed when the subshell exits. Execute this command $ echo $$;cat | read a 10637 and use pstree -p to look at the running processes, you will see an extra shell hanging off of your main shell. | |-bash(10637)-+-bash(10786) | | `-cat(10785) "} {"user":"443","tags":["visual-studio","keyboard","shortcuts"],"questionId":2765,"creationDate":"2008-08-05T20:01:31Z","title":"Is there a keyboard shortcut to view all open documents in Visual Studio 2008","acceptedAnswerId":2774,"type":"question","body":"I am trying to learn the keyboard shortcuts in Visual Studio in order to be more productive. So I downloaded a document showing many of the default keybindings in Visual Basic when using the VS 2008 IDE from Microsoft. When I tried what they say is the keyboard shortcut to view all open documents (CTRL + ALT + DOWN ARROW), I got a completely unexpected result on my XP machine; my entire screen display was flipped upside down! Was this a prank by someone at Microsoft? I can't imagine what practical value this flipping of the screen would have. Does anyone know what the correct keyboard shortcut is to view all open documents in VS 2008? Oh and if you try the above shortcut and it flips your display the way it did mine, do a CTRL + ALT + UP ARROW to switch it back. "} {"user":"396","tags":["visual-studio","plugins"],"questionId":2767,"creationDate":"2008-08-05T20:02:33Z","title":"Recommended add-ons/plugins for Microsoft Visual Studio","acceptedAnswerId":75338,"type":"question","body":"Can anyone recommend any good add-ons/plugins for Microsoft Visual Studio? Freebies are preferred, but if it is worth the cost then that's fine. "} {"user":"198","questionId":2750,"creationDate":"2008-08-05T20:03:46Z","answerId":2768,"type":"answer","body":"You might wanna check out Domain Driven Design, by Eric Evans. DDD has this notion of a Specification: ... explicit predicate-like VALUE OBJECTS for specialized purposes. A SPECIFICATION is a predicate that determines if an object does or does not satisfy some criteria. I think failing fast is one thing, the other is where to keep the logic for validation. The domain is the right place to keep the logic and I think a Specification Object or a validate method on your Domain objects would be a good place. "} {"user":"25","questionId":2767,"creationDate":"2008-08-05T20:04:25Z","answerId":2769,"type":"answer","body":"http://trolltech.com/products/qt/\">Qt Cross-Platform Application Framework Qt is a cross-platform application framework for desktop and embedded development. It includes an intuitive API and a rich C++ class library, integrated tools for GUI development and internationalization, and support for Java™ and C++ development They have a plug-in for Visual Studio that costs a bit of money, but it is worth every penny. "} {"user":"447","tags":["winforms","error-handling","user-controls"],"questionId":2770,"creationDate":"2008-08-05T20:05:22Z","title":"Global Exception Handling for winforms control","acceptedAnswerId":2779,"type":"question","body":"When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I'm looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this? "} {"user":"91","questionId":2767,"creationDate":"2008-08-05T20:05:27Z","answerId":2771,"type":"answer","body":"Not free, but ReSharper is definitely one recommendation. "} {"user":"36","questionId":2767,"creationDate":"2008-08-05T20:05:49Z","answerId":2772,"type":"answer","body":"Clipboard Manager Maintains your clipboard data through removal of lines, a few other nice items but that one alone makes me happy. Regionerate While some have problems with regions I think if you use them, this tool is for you. Automatically region'izes your code into appropriate region blocks. Fully configurable for custom items etc. "} {"user":"422","tags":["ubuntu","virtualization","xen"],"questionId":2773,"creationDate":"2008-08-05T20:06:18Z","title":"Can't get a Console to VMs","acceptedAnswerId":2883,"type":"question","body":"I've followed this otherwise excellent tutorial on getting Xen working with Ubuntu but am not able to get a console into my virtual machine (domU). I've got the extra = '2 console=xvc0' line in my /etc/xen/hostname_here.cfg file like they say, but am not able to get a console on it. If I statically assign an IP to the VM I can SSH to it, but for now I need to be able to use DHCP to give it an address (and since that's what I'm trying to debug, there's the problem). I know I've got a free DHCP address (although I'm getting more at the moment), so I don't think that's the problem. I've looked on Google and the Xen forums to no avail as well. Any ideas? "} {"user":"432","questionId":2765,"creationDate":"2008-08-05T20:08:23Z","answerId":2774,"type":"answer","body":"This is a conflict between your graphics driver and Visual Studio. Go to your driver settings page (Control panel) and disable the display rotation shortcuts. With this conflict removed, the shortcut will work in Visual Studio. "} {"user":"434","tags":["sql-server","datetime","date-conversion"],"questionId":2775,"creationDate":"2008-08-05T20:08:38Z","title":"How to remove the time portion of a datetime value (SQL Server)?","acceptedAnswerId":3696991,"type":"question","body":"Here's what I use: SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME) I'm thinking there may be a better and more elegant way. Requirements: It has to be as fast as possible (the less casting, the better). The final result has to be a datetime type, not a string. "} {"user":"404","questionId":2767,"creationDate":"2008-08-05T20:09:00Z","answerId":2776,"type":"answer","body":"If you use SVN for source control, definitely get VisualSVN. It enables TortoiseSVN interactions from within the Visual Studio IDE. I also echo the Resharper comment. Retail price is a little steep, but if you're a student or otherwise educationally affiliated, it's actually pretty cheap. "} {"user":"306","questionId":2732,"creationDate":"2008-08-05T20:09:15Z","answerId":2777,"type":"answer","body":"Allright, I figured it out! This is a hard bug to catch, but results from the way pipes are handled by the shell. Every element of a pipeline runs in a separate process. When the read command sets var1 and var2, is sets them it its own subshell, not the parent shell. So when the subshell exits, the values of var1 and var2 are lost. You can, however, try doing var1=$(echo \"Hello\") echo var1 which returns the expected answer. Unfortunately this only works for single variables, you can't set many at a time. In order to set multiple variables at a time you must either read into one variable and chop it up into multiple variables or use something like this: set -- $(echo \"Hello World\") var1=\"$1\" var2=\"$2\" echo $var1 echo $var2 While I admit it's not as elegant as using a pipe, it works. Of course you should keep in mind that read was meant to read from files into variables, so making it read from standard input should be a little harder. "} {"user":"415","tags":["database","asp.net-mvc","ado.net"],"questionId":2778,"creationDate":"2008-08-05T20:10:43Z","title":"Is it better to create Model classes or stick with generic database utility class?","acceptedAnswerId":2805,"type":"question","body":"We have a simple utility class in-house for our database calls (a light wrapper around ADO.NET), but I am thinking of creating classes for each database/object. Would it be smart thing to do so, or would it only benefit if we were using the full MVC framework for ASP.NET? So we have this: SQLWrapper.GetRecordset(connstr-alias, sql-statement, parameters); SQLWrapper.GetDataset(connstr-alias, sql-statement, parameters); SQLWrapper.Execute(connstr-alias, sql-statement, parameters); Thinking of doing this: Person p = Person.get(id); p.fname = \"jon\"; p.lname = \"smith\"; p.Save(); or for a new record - Person p = new Person(); p.fname = \"Jon\"; p.lname = \"Smith\"; p.Save(); p.Delete(); Would this be smart, or would it be overkill? I can see the benefit for reuse, changing database, and maintenance/readability. "} {"user":"289","questionId":2770,"creationDate":"2008-08-05T20:11:45Z","answerId":2779,"type":"answer","body":"You need to handle the System.Windows.Forms.Application.ThreadException event for Windows Forms. This article really helped me: http://bytes.com/forum/thread236199.html. "} {"user":"45","tags":["c#","colors"],"questionId":2780,"creationDate":"2008-08-05T20:12:20Z","title":"Converting ARBG to RGB with alpha blending","acceptedAnswerId":2789,"type":"question","body":"Let's say that we have an ARGB color: Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is Color.FromARGB(255, 162, 133, 255); The solution should work like this: Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); What is ToRGB's implementation? "} {"user":"91","questionId":2775,"creationDate":"2008-08-05T20:12:29Z","answerId":2781,"type":"answer","body":"Your CAST-FLOOR-CAST already seems to be the optimum way, at least on MS SQL Server 2005. Some other solutions I've seen have a string-conversion, like Select Convert(varchar(11), getdate(),101) in them, which is slower by a factor of 10. "} {"user":"306","questionId":2756,"creationDate":"2008-08-05T20:13:16Z","answerId":2783,"type":"answer","body":"emacs has been used by linux programmers for decades. It features syntax highlighting, it's fast, and there are a million tutorials out there you can find. "} {"user":"444","questionId":2778,"creationDate":"2008-08-05T20:13:32Z","answerId":2784,"type":"answer","body":"By no means is MVC the only design pattern for the web, but it is a useful one. Adopting just the 'M' will pay dividends, in my opinion, even if you can't/won't adopt the 'V' or 'C'. "} {"user":"33","tags":["c#",".net","vb.net","memory","memory-management"],"questionId":2785,"creationDate":"2008-08-05T20:14:10Z","title":"Setting Objects to Null/Nothing after use in .NET","acceptedAnswerId":2839,"type":"question","body":"Should you set all the objects to null (Nothing in VB.NET) once you have finished with them? I understand that in .NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in memory or at least in part? I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time). So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects? MSDN articles never do this in examples and currently I do this as I cannot see the harm. However I have come across a mixture of opinions so any comments are useful. "} {"user":"404","tags":["windows","mono"],"questionId":2786,"creationDate":"2008-08-05T20:15:22Z","title":"What's the best setup for Mono development on Windows?","acceptedAnswerId":2944,"type":"question","body":"I started trying to play with Mono, mostly for fun at the moment. I first tried to use the Visual Studio plugin that will convert a csproj into a makefile, but there seemed to be no version available for Visual Studio 2005. I also read about the MonoDevelop IDE, which sounded nice. Unfortunately, there's no pre-fab Windows package for it. I tried to follow some instructions to build it by combining dependencies from other semi-related installs. It didn't work, but that's probably because I'm a Windows-oriented guy and can barely spell \"makefile\". So, my question is this: What's the lowest-energy way to get up and running to try some Mono-based development on Windows? "} {"user":"269","questionId":2756,"creationDate":"2008-08-05T20:15:40Z","answerId":2787,"type":"answer","body":"any of the popular editors can be turned into an ide. I use Vi on the console and have used various gui editors over the years. This doesn't just go for linux I use Crimson Editor on windows as a C/python/z80asm ide. "} {"user":"2089740","questionId":2780,"creationDate":"2008-08-05T20:16:03Z","answerId":2789,"type":"answer","body":"It's called alpha blending. In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255. alpha=argb.alpha() r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r() g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g() b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b() note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly Edited to add: If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :). In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A). "} {"user":"308","questionId":2770,"creationDate":"2008-08-05T20:16:26Z","answerId":2790,"type":"answer","body":"If you're using VB.NET, you can tap into the very convenient ApplicationEvents.vb. This file comes for free with a VB.NET WinForms project and contains a method for handling unhandled exceptions. To get to this nifty file, it's \"Project Properties >> Application >> Application Events\" If you're not using VB.NET, then yeah, it's handling Application.ThreadException. "} {"user":"446","questionId":4,"creationDate":"2008-08-05T20:18:30Z","answerId":2791,"type":"answer","body":"In my opinion, it is desirable to be as explicit as possible. This adds clarity to the code and aids your fellow programmers who may eventually read it. In addition to (or instead of) appending a .0 to the number, you can use decimal.ToDouble(). Here are some examples: // Example 1 double transperancy = trackBar1.Value/5000; this.Opacity = decimal.ToDouble(transperancy); // Example 2 - with inline temp this.Opacity = decimal.ToDouble(trackBar1.Value/5000); "} {"user":"383","questionId":2785,"creationDate":"2008-08-05T20:21:17Z","answerId":2794,"type":"answer","body":"Some object suppose the .dispose() method which forces the resource to be removed from memory. "} {"user":"34","questionId":2785,"creationDate":"2008-08-05T20:23:33Z","answerId":2797,"type":"answer","body":"No don't null objects. You can check out http://codebetter.com/blogs/karlseguin/archive/2008/04/27/foundations-of-programming-pt-7-back-to-basics-memory.aspx for more information, but setting things to null won't do anything, except dirty your code. "} {"user":"116","tags":["google-maps","google-maps-api-3","mapping","gis"],"questionId":2798,"creationDate":"2008-08-05T20:24:42Z","title":"Map Routing, a la Google Maps?","acceptedAnswerId":2803,"type":"question","body":"I've always been intrigued by Map Routing, but I've never found any good introductory (or even advanced!) level tutorials on it. Does anybody have any pointers, hints, etc? Update: I'm primarily looking for pointers as to how a map system is implemented (data structures, algorithms, etc). "} {"user":"308","questionId":2767,"creationDate":"2008-08-05T20:26:08Z","answerId":2799,"type":"answer","body":"PowerCommands is a Microsoft-created plugin that offers a variety of new features that one would think probably should have been in Visual Studio in the first place. These include Copying/Pasting project references! \"Open Containing Folder\" to jump straight to the hard-drive location of a file or project Automatic reorganizig and sorting of using statements \"Open Command Prompt Here\" to open a command prompt in any of your project folders. Collapse Projects "} {"user":"342","questionId":2767,"creationDate":"2008-08-05T20:26:26Z","answerId":2800,"type":"answer","body":"Whole Tomato's Visual Assist X. I absolutely swear by it. I would like to see a better plug in for Lint than Visual Lint by Riverblade, but since that will eventually be moved onto the build server I don't mind running it every couple of days manually. "} {"user":"237","questionId":2563,"creationDate":"2008-08-05T20:27:23Z","answerId":2801,"type":"answer","body":"I'm currently using dhtmlxGrid and we have the Excel copy/paste functionality working. dhtmlXGrid is the most full featured javascript grid package that I've found. On their website, dhtmlXGrid claims to support Clipboard functionality in the Professional version. (However, I noticed the Sample on their site isn't working on my Firefox. EDIT: It's probably the permissions issue that Nathan mentioned.) In any case, we had to do some extra work to get the exact Excel copy and paste functionality we wanted. We essentially had to override some of their functionality to get the desired behavior. Their support was pretty good in helping us come up with a solution. So to answer your question, you should be able to get them to support copy and paste if you purchase the Professional version. I'm just warning you that it may take some additional work to fine tune that behavior. Overall, I'm happy with dhtmlXGrid. We use a lot of their features. Their support is pretty good. They usually take one day to respond since they are in Europe (I think). And Javascript is by its very nature open source so I can always dive in when I need to. "} {"user":"269","questionId":2798,"creationDate":"2008-08-05T20:27:36Z","answerId":2803,"type":"answer","body":"Take a look at the open street map project to see how this sort of thing is being tackled in a truely free software project using only user supplied and licensed data and have a wiki containing stuff you might find interesting. A few years back the guys involved where pretty easy going and answered lots of questions I had so I see no reason why they still aren't a nice bunch. "} {"user":"328","tags":["c#","winforms","picturebox"],"questionId":2804,"creationDate":"2008-08-05T20:28:30Z","title":"How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?","acceptedAnswerId":2808,"type":"question","body":"I have an application that displays an image inside of a Windows Forms PictureBox control. The SizeMode of the control is set to Zoom so that the image contained in the PictureBox will be displayed in an aspect-correct way regardless of the dimensions of the PictureBox. This is great for the visual appearance of the application because you can size the window however you want and the image will always be displayed using its best fit. Unfortunately, I also need to handle mouse click events on the picture box and need to be able to translate from screen-space coordinates to image-space coordinates. It looks like it's easy to translate from screen space to control space, but I don't see any obvious way to translate from control space to image space (i.e. the pixel coordinate in the source image that has been scaled in the picture box). Is there an easy way to do this, or should I just duplicate the scaling math that they're using internally to position the image and do the translation myself? "} {"user":"34","questionId":2778,"creationDate":"2008-08-05T20:28:30Z","answerId":2805,"type":"answer","body":"This question is loaded, data driven design vs domain driven design. For any application that has a good amount of behavior, then domain driven design should be preferred. Reporting, or utility applications tend to work better (or are quicker to develop) with data driven design. What you're asking is \"should my company make a fundamental shift in how we design our code\". As a domain-freak, my gut reaction is to scream yes. However, by the simple nature of your question, I'm not sure you fully understand the scope of the change you are proposing. I think you should talk more to your team about it. Get some literature, such as Evan's DDD book, or the free foundations ebook, and then you'll be in a better position to judge which direction you should go. "} {"user":"307","questionId":2767,"creationDate":"2008-08-05T20:31:21Z","answerId":2806,"type":"answer","body":" Resharper Resharper MbUnit Test Runner Add-On SQL Prompt for Database Projects (works inside your SQL Management Studio as well) Ankh SVN 2.0+ for free SVN support (v1.x pales in comparison) TeamCity plug-in to monitor your builds, personal builds, and bug tracking "} {"user":"45","questionId":2785,"creationDate":"2008-08-05T20:32:48Z","answerId":2807,"type":"answer","body":"The only time you should set a variable to null is when the variable does not go out of scope and you no longer need the data associated with it. Otherwise there is no need. "} {"user":"192","questionId":2804,"creationDate":"2008-08-05T20:33:01Z","answerId":2808,"type":"answer","body":"Depending on the scaling, the relative image pixel could be anywhere in a number of pixels. For example, if the image is scaled down significantly, pixel 2, 10 could represent 2, 10 all the way up to 20, 100), so you'll have to do the math yourself and take full responsibility for any inaccuracies! :-) "} {"user":"437","tags":["sql-server"],"questionId":2809,"creationDate":"2008-08-05T20:33:21Z","title":"SQL Server 2000: Is there a way to tell when a record was last modified?","acceptedAnswerId":2842,"type":"question","body":"The table doesn't have a last updated field and I need to know when existing data was updated. So adding a last updated field won't help (as far as I know). "} {"user":"39","questionId":2809,"creationDate":"2008-08-05T20:34:41Z","answerId":2810,"type":"answer","body":"You can add a timestamp field to that table and update that timestamp value with an update trigger. "} {"user":"448","tags":["sql","xml","sql-server-2005","formatting","for-xml"],"questionId":2811,"creationDate":"2008-08-05T20:35:56Z","title":"SQL Server 2005 For XML Explicit - Need help formatting","acceptedAnswerId":2825,"type":"question","body":"I have a table with a structure like the following: ------------------------------ LocationID | AccountNumber ------------------------------ long-guid-here | 12345 long-guid-here | 54321 To pass into another stored procedure, I need the XML to look like this: 12345 54321 The best I've been able to do so far was getting it like this: I'm using this SQL statement: SELECT 1 as tag, null as parent, AccountNumber as 'root!1!clientID' FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML EXPLICIT So far, I've looked at the documentation on the MSDN page, but I've not come out with the desired results. @KG, Yours gave me this output actually: 10705 I'm going to stick with the FOR XML EXPLICIT from Chris Leon for now. "} {"user":"415","questionId":2785,"creationDate":"2008-08-05T20:37:30Z","answerId":2813,"type":"answer","body":"Also: using(SomeObject object = new SomeObject()) { // do stuff with the object } // the object will be disposed of "} {"user":"116","tags":["http","curl"],"questionId":2815,"creationDate":"2008-08-05T20:38:59Z","title":"How to curl or wget a web page?","acceptedAnswerId":2819,"type":"question","body":"I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc. Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas? Also, when the beta is finished, will my status page be accessible without logging in? "} {"user":"234","questionId":2770,"creationDate":"2008-08-05T20:42:31Z","answerId":2817,"type":"answer","body":"Currently in my winforms app I have handlers for Application.ThreadException, as above, but also AppDomain.CurrentDomain.UnhandledException Most exceptions arrive via the ThreadException handler, but the AppDomain one has also caught a few in my experience "} {"user":"269","questionId":2815,"creationDate":"2008-08-05T20:43:31Z","answerId":2818,"type":"answer","body":"Nice idea :) I presume you've used wget's --load-cookies (filename) might help a little but it might be easier to use something like Mechanize (in Perl or python) to mimic a browser more fully to get a good spider. "} {"user":"30","questionId":2815,"creationDate":"2008-08-05T20:43:52Z","answerId":2819,"type":"answer","body":"Your status page is available now without logging in (click logout and try it). When the beta-cookie is disabled, there will be nothing between you and your status page. For wget: wget --no-cookies --header \"Cookie: soba=(LookItUpYourself)\" https://stackoverflow.com/users/30/myProfile.html "} {"user":"429","questionId":2785,"creationDate":"2008-08-05T20:46:08Z","answerId":2821,"type":"answer","body":"There are some cases where it makes sense to null references. For instance, when you're writing a collection--like a priority queue--and by your contract, you shouldn't be keeping those objects alive for the client after the client has removed them from the queue. But this sort of thing only matters in long lived collections. If the queue's not going to survive the end of the function it was created in, then it matters a whole lot less. On a whole, you really shouldn't bother. Let the compiler and GC do their jobs so you can do yours. "} {"user":"75","questionId":2815,"creationDate":"2008-08-05T20:46:22Z","answerId":2822,"type":"answer","body":"I couldn't figure out how to get the cookies to work either, but I was able to get to my status page in my browser while I was logged out, so I assume this will work once stackoverflow goes public. This is an interesting idea, but won't you also pick up diffs of the underlying html code? Do you have a strategy to avoid ending up with a diff of the html and not the actual content? "} {"user":"446","questionId":564,"creationDate":"2008-08-05T20:49:13Z","answerId":2823,"type":"answer","body":"Regarding Java 1.5 and autoboxing there is an important \"quirk\" that comes to play when comparing Integer objects. In Java, Integer objects with the values -128 to 127 are immutable (that is, for one particular integer value, say 23, all Integer objects instantiated through your program with the value 23 points to the exact same object). Example, this returns true: Integer i1 = new Integer(127); Integer i2 = new Integer(127); System.out.println(i1 == i2); // true While this returns false: Integer i1 = new Integer(128); Integer i2 = new Integer(128); System.out.println(i1 == i2); // false The == compares by reference (does the variables point to the same object). This result may or may not differ depending on what JVM you are using. The specification autoboxing for Java 1.5 requires that integers (-128 to 127) always box to the same wrapper object. A solution? =) One should always use the Integer.equals() method when comparing Integer objects. System.out.println(i1.equals(i2)); // true More info at java.net Example at bexhuff.com "} {"user":"289","questionId":2811,"creationDate":"2008-08-05T20:51:03Z","answerId":2825,"type":"answer","body":"try SELECT 1 AS Tag, 0 AS Parent, AccountNumber AS [Root!1!AccountNumber!element] FROM Location.LocationMDAccount WHERE LocationID = 'long-guid-here' FOR XML EXPLICIT "} {"user":"234","questionId":1760,"creationDate":"2008-08-05T20:53:00Z","answerId":2831,"type":"answer","body":"xUnit.net looks like it provides a slightly different approach to N/MB/MS/Unit, which is interesting. In my search for an rspec-like solution (because I LOVE the rspec), I also came across NSpec, which looks a bit wordy, but combined with the NSpec Extensions addon to use C#3 extension methods, it looks pretty nice. "} {"user":"318","questionId":2811,"creationDate":"2008-08-05T20:53:13Z","answerId":2832,"type":"answer","body":"Try this, Chris: SELECT AccountNumber as [clientId] FROM Location.Location root WHERE LocationId = 'long-guid-here' FOR XML AUTO, ELEMENTS TERRIBLY SORRY! I mixed up what you were asking for. I prefer the XML AUTO just for ease of maintainance, but I believe either one is effective. My apologies for the oversight ;-) "} {"user":"448","questionId":2811,"creationDate":"2008-08-05T20:53:19Z","answerId":2834,"type":"answer","body":"I got it with: select 1 as tag, null as parent, AccountNumber as 'root!1!clientID!element' from Location.LocationMDAccount where locationid = 'long-guid-here' for xml explicit "} {"user":"271","questionId":2742,"creationDate":"2008-08-05T20:54:06Z","answerId":2835,"type":"answer","body":"I've only done a small bit of coding in Erlang but I found the most useful method was just to write the code in a text editor and have a terminal open ready to build my code as I need to (this was in Linux, but a similar idea would work in Windows, I'm sure). Your question didn't mention it, but if you're looking for a good book on Erlang, try this one by O'Reilly. "} {"user":"419","questionId":2785,"creationDate":"2008-08-05T20:56:28Z","answerId":2839,"type":"answer","body":"Karl is absolutely correct, there is no need to set objects to null after use. If an object implements IDisposable, just make sure you call IDisposable.Dispose() when you're done with that object (wrapped in a try..finally, or, a using() block). But even if you don't remember to call Dispose(), the finaliser method on the object should be calling Dispose() for you. I thought this was a good treatment: Digging into IDisposable and this Understanding IDisposable There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: Jeffrey Richter on the Windows Memory Model and Richters book CLR via C# chapter 20 has a great treatment: "} {"user":"383","tags":["sql","sql-server-2005","paging"],"questionId":2840,"creationDate":"2008-08-05T20:57:00Z","title":"Paging SQL Server 2005 Results","acceptedAnswerId":2843,"type":"question","body":"How do I page results in SQL Server 2005? I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method? What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on. Any help would be much appreciated. "} {"user":"449","questionId":2809,"creationDate":"2008-08-05T20:58:17Z","answerId":2842,"type":"answer","body":"SQL Server 2000 does not keep track of this information for you. There may be creative / fuzzy ways to guess what this date was depending on your database model. But, if you are talking about 1 table with no relation to other data, then you are out of luck. "} {"user":"36","questionId":2840,"creationDate":"2008-08-05T20:59:21Z","answerId":2843,"type":"answer","body":"You can use the Row_Number() function. Its used as follows: SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users From which it will yield a result set with a RowID field which you can use to page between. SELECT * FROM ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ) As RowResults WHERE RowID Between 5 AND 10 etc "} {"user":"432","tags":["c","syntax","printf","format-specifiers","long-long"],"questionId":2844,"creationDate":"2008-08-05T20:59:29Z","title":"How do you printf an unsigned long long int(the format specifier for unsigned long long int)?","acceptedAnswerId":2850,"type":"question","body":"#include int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; printf(\"My number is %d bytes wide and its value is %ul. A normal number is %d.\\n\", sizeof(num), num, normalInt); return 0; } Output: My number is 8 bytes wide and its value is 285212672l. A normal number is 0. I assume this unexpected result is from printing the unsigned long long int. How do you printf() an unsigned long long int? "} {"user":"200","questionId":2844,"creationDate":"2008-08-05T21:02:35Z","answerId":2850,"type":"answer","body":"Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU). printf(\"%llu\", 285212672); "} {"user":"269","questionId":2844,"creationDate":"2008-08-05T21:03:07Z","answerId":2851,"type":"answer","body":"Non-standard things are always strange :) for the long long portion under GNU it's L, ll or q and under windows I believe it's ll only "} {"user":"383","questionId":2809,"creationDate":"2008-08-05T21:04:47Z","answerId":2854,"type":"answer","body":"OmniAudit is a commercial package which implments auditng across an entire database. A free method would be to write a trigger for each table which addes entries to an audit table when fired. "} {"user":"36","questionId":2840,"creationDate":"2008-08-05T21:05:10Z","answerId":2855,"type":"answer","body":"I believe you'd need to perform a separate query to accomplish that unfortionately. I was able to accomplish this at my previous position using some help from this page: Paging in DotNet 2.0 They also have it pulling a row count seperately. "} {"user":"116","tags":["html","screen-scraping","html-parsing","web-scraping","html-content-extraction"],"questionId":2861,"creationDate":"2008-08-05T21:09:11Z","title":"Options for HTML scraping?","acceptedAnswerId":2866,"type":"question","body":"I'm thinking of trying Beautiful Soup, a Python package for HTML scraping. Are there any other HTML scraping packages I should be looking at? Python is not a requirement, I'm actually interested in hearing about other languages as well. The story so far: Python Beautiful Soup lxml HTQL Scrapy Mechanize Ruby Nokogiri Hpricot Mechanize scrAPI scRUBYt! wombat Watir .NET Html Agility Pack WatiN Perl WWW::Mechanize Web-Scraper Java Tag Soup HtmlUnit Web-Harvest jARVEST jsoup Jericho HTML Parser JavaScript request cheerio artoo node-horseman phantomjs PHP Goutte htmlSQL PHP Simple HTML DOM Parser PHP Scraping with CURL Most of them Screen-Scraper "} {"user":"216","questionId":2756,"creationDate":"2008-08-05T21:10:30Z","answerId":2862,"type":"answer","body":"I bounce about between Mac, Windows and Ubuntu and while Emacs used to be my editor of choice, I'm finding that in my old age I prefer to something GUI-based (using command-line for the shell is still fine by me). My preferred editor is Komodo Edit, which the advantages of: Being free (as in beer) Available for Mac, Windows and Linux Syntax highlighting for a boatload of languages, including C++ and PHP (I'm using it for Ruby, Python and PHP myself) Code completion, even for classes I defined myself Ability to \"remote save\" via FTP, SFTP or SCP Support for organizing your files into projects Tabs and other interface niceties I'm not sure how lightweight it is, but it certainly feels snappier than Eclipse! "} {"user":"383","questionId":2861,"creationDate":"2008-08-05T21:11:29Z","answerId":2865,"type":"answer","body":"I would first find out if the site(s) in question provide an API server or RSS Feeds for access the data you require. "} {"user":"216","questionId":2861,"creationDate":"2008-08-05T21:13:32Z","answerId":2866,"type":"answer","body":"The Ruby world's equivalent to Beautiful Soup is why_the_lucky_stiff's Hpricot. "} {"user":"274","questionId":805,"creationDate":"2008-08-05T21:13:47Z","answerId":2867,"type":"answer","body":"The way I have done this is to create a command script file and pass this on the command line via the /b command to psftp.exe. I have also tried this in Perl and have yet to find a neater way of doing it. There is an issue with this method, in that you already have to have accepted the RSA finger-print. If not, then the script will either wait for user input to accept it or will skip over it if you are running in full batch mode, with a failure. Also, if the server changes so that it's RSA finger-print changes (e.g. a cluster) then you need to re-accept the finger-print again. Not an ideal method, but the only one I know. I shall be watching this question incase anyone knows another way. "} {"user":"206","tags":["c#",".net","data-structures","marshalling"],"questionId":2871,"creationDate":"2008-08-05T21:19:03Z","title":"Reading a C/C++ data structure in C# from a byte array","acceptedAnswerId":2887,"type":"question","body":"What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12]; } And would fill something like this: [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking; } What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. GCHandle handle; NewStuff MyStuff; int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize]; Array.Copy(SomeByteArray, 0, buff, 0, BufferSize); handle = GCHandle.Alloc(buff, GCHandleType.Pinned); MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free(); Is there better way to accomplish this? Would using the BinaryReader class offer any performance gains over pinning the memory and using Marshal.PtrStructure? "} {"user":"446","tags":["c#",".net","winforms"],"questionId":2872,"creationDate":"2008-08-05T21:19:37Z","title":"Possible to \"spin off\" several GUI threads? (Not halting the system at Application.Run)","acceptedAnswerId":2901,"type":"question","body":"My Goal I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?) Background I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common IComponent interface with a single method DoStuff(). Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of IComponent. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component. The lifetime of the complete system looks like this Application starts. Check configuration file for components to load. Load them. For each component, run DoStuff() to initialize it and make it live its own life in their own threads. Continue to do main application-thingy king of work, forever. I have not yet been able to successfully perform point 3 if the component fires up a GUI in DoStuff(). It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4. It would be great if these components were allowed to start up their own Windows Forms GUIs. Problem When a component tries to fire up a GUI in DoStuff() (the exact line of code is when the component runs Application.Run(theForm)), the component and hence our system \"hangs\" at the Application.Run() line until the GUI is closed. Well, the just fired up GUI works fine, as expected. Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them. public class MyComponent1: IComponent { public string DoStuff(...) { // write something to the database } } public class MyComponent2: IComponent { public void DoStuff() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); // I want the thread to immediately return after the GUI // is fired up, so that my main thread can continue to work. } } I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed. public void DoStuff() { new Thread(ThreadedInitialize).Start() } private void ThreadedInitialize() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); } Is it possible to spin off a GUI and return after Application.Run()? "} {"user":"381","tags":["c","unix","testing"],"questionId":2873,"creationDate":"2008-08-05T21:19:40Z","title":"Choosing a static code analysis tool","acceptedAnswerId":2927,"type":"question","body":"I'm working on a project where I'm coding in C in a UNIX environment. I've been using the lint tool to check my source code. Lint has been around a long time (since 1979), can anyone suggest a more recent code analysis tool I could use ? Preferably a tool that is free. "} {"user":"441","tags":["c#",".net","winforms"],"questionId":2874,"creationDate":"2008-08-05T21:19:57Z","title":"How to render a control to look like ComboBox with Visual Styles enabled?","type":"question","body":"I have a control that is modelled on a ComboBox. I want to render the control so that the control border looks like that of a standard Windows ComboBox. Specifically, I have followed the MSDN documentation and all the rendering of the control is correct except for rendering when the control is disabled. Just to be clear, this is for a system with Visual Styles enabled. Also, all parts of the control render properly except the border around a disabled control, which does not match the disabled ComboBox border colour. I am using the VisualStyleRenderer class. MSDN suggests using the VisualStyleElement.TextBox element for the TextBox part of the ComboBox control but a standard disabled TextBox and a standard disabled ComboBox draw slightly differently (one has a light grey border, the other a light blue border). How can I get correct rendering of the control in a disabled state? "} {"user":"233","questionId":2767,"creationDate":"2008-08-05T21:22:06Z","answerId":2877,"type":"answer","body":"I find Ghost Doc to be very useful. GhostDoc is a free add-in for Visual Studio that automatically generates XML documentation comments for C#. Either by using existing documentation inherited from base classes or implemented interfaces, or by deducing comments from name and type of e.g. methods, properties or parameters. "} {"user":"116","questionId":2815,"creationDate":"2008-08-05T21:22:42Z","answerId":2878,"type":"answer","body":"And here's what works... curl -s --cookie soba=. http://stackoverflow.com/users "} {"user":"327","questionId":2786,"creationDate":"2008-08-05T21:23:45Z","answerId":2880,"type":"answer","body":"@Chris I have found that Visual Studio is the best IDE for developing against .NET -- I think the best way to target Mono is really just to develop and build in Visual Studio under Windows then just run those binaries directly on Linux (or whatever other Mono platform you are using). There are free versions of Visual Studio if licensing is a concern. If you are developing under Linux, the best software is probably Eclipse with a Mono plugin (see The Mono Handbook - Eclipse for installation instructions) but keep in mind it doesn't have near the amount of features or language integration Visual Studio has. @modesty Mono is a 3rd party open source implementation of the .NET framework which allows you to run .NET applications on platforms other than Windows. "} {"user":"449","questionId":2871,"creationDate":"2008-08-05T21:24:27Z","answerId":2881,"type":"answer","body":"If you have a byte[] you should be able to use the BinaryReader class and set values on NewStuff using the available ReadX methods. "} {"user":"360","questionId":2773,"creationDate":"2008-08-05T21:27:45Z","answerId":2883,"type":"answer","body":"I had followed a different tutorial on setting up my xen on ubuntu before 8.04 but now upgraded to 8.04. I used the extra line in my cfg as folows: extra = ' TERM=xterm xencons=tty console=tty1' It allows me to \"xm console hostname\" from dom0. I think this was from a problem with the xen setup in the version prior to 8.04 (I'm not sure which version that was). I'm not sure if the same change is necessary in 8.04 as I'm an upgrade and didn't change any of my domU configs after the upgrade. "} {"user":"170","questionId":2786,"creationDate":"2008-08-05T21:27:58Z","answerId":2884,"type":"answer","body":"My first instinct would be the rather unhelpful \"Install Linux\". You are somewhat swimming against the current to try and develop in mono under windows. Installing GTK and everything is a bit of a bother in my experience. If you do feel like using linux, then you could Try Ubuntu Otherwise: There's some information here: http://www.mono-project.com/Mono:Windows and it seems the cygwin toolchain might be your best bet. I don't think you're going to be able to avoid makefiles, sadly. I found a slightly more explicit tutorial from O'Reilly. @modesty: Mono provides the necessary software to develop and run .NET client and server applications on Linux, Solaris, Mac OS X, Windows, and Unix. Sponsored by Novell (http://www.novell.com), the Mono open source project has an active and enthusiastic contributing community and is positioned to become the leading choice for development of Linux applications. -- From the Mono site. "} {"user":"42","questionId":2871,"creationDate":"2008-08-05T21:29:39Z","answerId":2887,"type":"answer","body":"From what I can see in that context, you don't need to copy SomeByteArray into a buffer. You simply need to get the handle from SomeByteArray, pin it, copy the IntPtr data using PtrToStructure and then release. No need for a copy. That would be: NewStuff ByteArrayToNewStuff(byte[] bytes) { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free(); return stuff; } Generic version: T ByteArrayToStructure(byte[] bytes) where T: struct { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); return stuff; } ... "} {"user":"72","questionId":2861,"creationDate":"2008-08-05T21:29:51Z","answerId":2888,"type":"answer","body":"Regular expressions work pretty well for HTML scraping as well ;-) Though after looking at Beautiful Soup, I can see why this would be a valuable tool. "} {"user":"206","questionId":2809,"creationDate":"2008-08-05T21:32:01Z","answerId":2890,"type":"answer","body":"You can't check for changes without some sort of audit mechanism. You are looking to extract information that ha not been collected. If you just need to know when a record was added or edited, adding a datetime field that gets updated via a trigger when the record is updated would be the simplest choice. If you also need to track when a record has been deleted, then you'll want to use an audit table and populate it from triggers with a row when a record has been added, edited, or deleted. "} {"user":"224","questionId":2844,"creationDate":"2008-08-05T21:40:24Z","answerId":2895,"type":"answer","body":"Well, one way is to compile it as x64 with VS2008 This runs as you would expect: int normalInt = 5; unsigned long long int num=285212672; printf( \"My number is %d bytes wide and its value is %ul. A normal number is %d \\n\", sizeof(num), num, normalInt); For 32 bit code, we need to use the correct __int64 format specifier %I64u. So it becomes. int normalInt = 5; unsigned __int64 num=285212672; printf( \"My number is %d bytes wide and its value is %I64u. A normal number is %d\", sizeof(num), num, normalInt); This code works for both 32 and 64 bit VS compiler. "} {"user":"116","questionId":2873,"creationDate":"2008-08-05T21:42:22Z","answerId":2897,"type":"answer","body":"For C code, you definitely should definitely use Flexelint. I used it for nearly 15 years and swear by it. One of the really great features it has is that warnings can be selectively turned off and on via comments in the code (\"/* lint -e123*/\"). This turned out to be a powerful documentation tool when you wanted to something out of the ordinary. \"I am turning off warning X, therefore, there is some good reason I'm doing X.\" For anybody into interesting C/C++ questions, look at some of their examples on their site and see if you can figure out the bugs without looking at the hints. "} {"user":"25","tags":["linux","editor"],"questionId":2898,"creationDate":"2008-08-05T21:42:37Z","title":"Text Editor For Linux (Besides Vi)?","acceptedAnswerId":2905,"type":"question","body":"Let me preface this question by saying I use TextMate on Mac OSX for my text needs and I am in love with it. Anything comparable on the Linux platform? I'll mostly use it for coding python/ruby. Doing a google search yielded outdated answers. Edit: Since there has been some concern about the 'merit' of this question. I am about to start a new Ruby Programming Project in Linux and before I got started I wanted to make sure I had the right tools to do the job. Edit #2: I use VIM on a daily basis -- all . the . time. I enjoy using it. I was just looking for some alternatives. "} {"user":"454","tags":["php","mysql"],"questionId":2900,"creationDate":"2008-08-05T21:45:11Z","title":"MySQL/Apache Error in PHP MySQL query","acceptedAnswerId":2975,"type":"question","body":"I am getting the following error: Access denied for user 'apache'@'localhost' (using password: NO) When using the following code: Delete Story\"; if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_row($result)){ echo ''.$row[1].'Delete'; echo '
'.$row[2].''; } } else { echo \"No stories available.\"; } ?> The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if. I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions. "} {"user":"227","questionId":2872,"creationDate":"2008-08-05T21:45:17Z","answerId":2901,"type":"answer","body":"Application.Run method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown. You can, however, pass an ApplicationContext (instad of a new Form()) to Application.Run method and ApplicationContext can be used to launch several forms at once. Your application will only end when all of those are closed. See here: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx Also, any forms that you Show non-modally will continue to run alongside your main form, which will enable you to have more than one windows that do not block each other. I believe this is actually what you are trying to accomplish. "} {"user":"455","questionId":2898,"creationDate":"2008-08-05T21:46:29Z","answerId":2903,"type":"answer","body":"SciTE http://www.scintilla.org/SciTE.html "} {"user":"122","questionId":2898,"creationDate":"2008-08-05T21:49:12Z","answerId":2905,"type":"answer","body":"Emacs is a wonderful text editor. It has huge power once you become a power user. You can access a shell, have as many files open as you want in as many sub-windows and an extremely powerful scripting support that lets you add all kinds of neat features. I have been using a ruby-mode which adds syntax highlighting and whatnot to ruby, and the same exists for every major language. If you keep at it, you can use exclusively the keyboard and never touch the mouse, which increases your editing speed by a significant margin. If you want to start with something a lot more basic though, gedit is nice... it has built in syntax highlighting as well for most languages based on the filename extension. It comes with the OS as well (though emacs you can easily install with apt-get or some similar package finder utility). UPDATE: I think gedit is exclusively GUI based though, so it would be useful to learn emacs in case you are stuck with just a shell (it is fully featured in both shell and graphical mode). FURTHER UPDATE: Just FYI, I am not trying to push Emacs over Vim, it's just what I use, and it's a great editor (as I'm sure Vim is too). It is daunting at first (as I'm sure Vim is too), but the question was about text editors on Linux besides vi... Emacs seems the logical choice to me, but gedit is a great simple text editor with some nice features if that's all you are looking for. "} {"user":"1384652","questionId":2900,"creationDate":"2008-08-05T21:52:44Z","answerId":2908,"type":"answer","body":"Just to check, if you use just this part you get an error? personally. "} {"user":"103","questionId":2873,"creationDate":"2008-08-05T22:17:24Z","answerId":2927,"type":"answer","body":"Don't overlook the compiler itself. Read the compiler's documentation and find all the warnings and errors it can provide, and then enable as many as make sense for you. Also make sure to tell your compiler to treat warnings like errors so you're forced to fix them right away. (\"-Werror\" on gcc) Also: \"-Wall\" on gcc does not enable all warnings, don't be fooled. Also also: check out valgrind (free!) - it \"automatically detect[s] many memory management and threading bugs, and profile[s] your programs in detail.\" Valgrind isn't a static checker, but it's a great tool! http://valgrind.org "} {"user":"446","questionId":2155,"creationDate":"2008-08-05T22:17:29Z","answerId":2928,"type":"answer","body":"Using attributes, child config sections and constraints There is also the possibility to use attributes which automatically takes care of the plumbing, as well as providing the ability to easily add constraints. I here present an example from code I use myself in one of my sites. With a constraint I dictate the maximum amount of disk space any one user is allowed to use. MailCenterConfiguration.cs: namespace Ani { public sealed class MailCenterConfiguration : ConfigurationSection { [ConfigurationProperty(\"userDiskSpace\", IsRequired = true)] [IntegerValidator(MinValue = 0, MaxValue = 1000000)] public int UserDiskSpace { get { return (int)base[\"userDiskSpace\"]; } set { base[\"userDiskSpace\"] = value; } } } } This is set up in web.config like so
... Child elements The child xml element mail is created in the same .cs file as the one above. Here I've added constraints on the port. If the port is assigned a value not in this range the runtime will complain when the config is loaded. MailCenterConfiguration.cs: public sealed class MailCenterConfiguration : ConfigurationSection { [ConfigurationProperty(\"mail\", IsRequired=true)] public MailElement Mail { get { return (MailElement)base[\"mail\"]; } set { base[\"mail\"] = value; } } public class MailElement : ConfigurationElement { [ConfigurationProperty(\"host\", IsRequired = true)] public string Host { get { return (string)base[\"host\"]; } set { base[\"host\"] = value; } } [ConfigurationProperty(\"port\", IsRequired = true)] [IntegerValidator(MinValue = 0, MaxValue = 65535)] public int Port { get { return (int)base[\"port\"]; } set { base[\"port\"] = value; } } Use To then use it practically in code, all you have to do is instantiate the MailCenterConfigurationObject, this will automatically read the relevant sections from web.config. MailCenterConfiguration.cs private static MailCenterConfiguration instance = null; public static MailCenterConfiguration Instance { get { if (instance == null) { instance = (MailCenterConfiguration)WebConfigurationManager.GetSection(\"mailCenter\"); } return instance; } } AnotherFile.cs public void SendMail() { MailCenterConfiguration conf = MailCenterConfiguration.Instance; SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port); } Check for validity I previously mentioned that the runtime will complain when the configuration is loaded and some data does not comply to the rules you have set up (e.g. in MailCenterConfiguration.cs). I tend to want to know these things as soon as possible when my site fires up. One way to solve this is load the configuration in _Global.asax.cx.Application_Start_ , if the configuration is invalid you will be notified of this with the means of an exception. Your site won't start and instead you will be presented detailed exception information in the Yellow screen of death. Global.asax.cs protected void Application_ Start(object sender, EventArgs e) { MailCenterConfiguration.Instance; } "} {"user":"306","questionId":1005,"creationDate":"2008-08-05T22:20:58Z","answerId":2930,"type":"answer","body":"A quick hack you can consider is doing a chmod on the file you're editing, save with vim, and then chmod back to what the file was originally. ls -l test.file (to see the permissions of the file) chmod 777 test.file [This is where you save in vim] chmod xxx test.file (restore the permissions you found in the first step) Of course I don't recommend this approach in a system where you're worried about security, as for a few seconds anyone can read/change the file without you realizing. "} {"user":"360","tags":["java","p2p","jxta"],"questionId":2931,"creationDate":"2008-08-05T22:23:16Z","title":"Getting started with a custom JXTA PeerGroup","type":"question","body":"I have been working with JXTA 2.3 for the last year or so for a peer-to-peer computing platform I am developing. I am migrating to JXTA 2.5 and in the process I am trying to clean up a lot of my use of JXTA. For the most part, I approached JXTA with a just make it work attitude. I used it to jumpstart creating and managing my peer-to-peer overlay network and providing basic communication services. I would like to use it in a more JXTA way since I am making changes to move to 2.5 anyway. My first step would be a basic creation of a custom PeerGroup. I see some new new mechanisms that are using the META-INF.services infrastructure of Java. Should I be listing a related PeerGroup implementing object here with a GUID in net.jxta.platform.Module? As I understand it, if I do this, when a group with a spec ID matching the GUID is encountered and joined or created it should automatically use the matching object. I should be able to just manually tie a PeerGroup object to the group but this new method using META-INF seems to be a lot easier to manage. Does anyone have any pointers or examples of using this infrastructure for PeerGroup implementation? Also, some general information on the META-INF.services mechanism in Java would be helpful. "} {"user":"1384652","tags":["python","user-interface","deployment","tkinter","release-management"],"questionId":2933,"creationDate":"2008-08-05T22:26:00Z","title":"How can I create a directly-executable cross-platform GUI app using Python?","acceptedAnswerId":2937,"type":"question","body":"Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please? "} {"user":"275","questionId":2933,"creationDate":"2008-08-05T22:34:25Z","answerId":2937,"type":"answer","body":"First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac) Of course, there are many, but the most popular that I've seen in wild are: Tkinter - based on Tk GUI toolkit (de-facto standard GUI library for python, free for commercial projects) WxPython - based on WxWidgets (very popular, free for commercial projects) PyQt - based on Qt (also very popular and more stable than WxWidgets but costly license for commercial projects) Complete list is at http://wiki.python.org/moin/GuiProgramming Single executable (Windows) py2exe - Probably the most popular out there (PyInstaller is also gaining in popularity) Single executable (Linux) Freeze - works the same way like py2exe but targets Linux platform Single executable (Mac) py2app - again, works like py2exe but targets Mac OS "} {"user":"431","questionId":2756,"creationDate":"2008-08-05T22:34:56Z","answerId":2938,"type":"answer","body":"Joey, I believe anything is lighter than Eclipse! :o) "} {"user":"404","questionId":2786,"creationDate":"2008-08-05T22:37:07Z","answerId":2940,"type":"answer","body":"I liked the idea of trying to use MonoDevelop mostly just to make sure my stuff would work against the Mono runtimes. I guess it would also be possible to get crazy with msbuild and write some custom targets that tried to build against Mono, but that's basically emulating the now-defunct plug-in's functionality which I assume was non-trivial to build. I do have minor experience with cygwin, and I am happy typing \"configure\" and \"make\" all day long, but when a problem occurs in that process, I'm virtually screwed. I'll probably try to play with all this again, but if it takes me more than a couple hours to come up with a way to build comfortably against the Mono runtimes, I'll probably just bail. I will try the Eclipse idea. I use that for Java, so I might be able to get the c# stuff to work. We shall see... "} {"user":"92","questionId":2933,"creationDate":"2008-08-05T22:40:17Z","answerId":2941,"type":"answer","body":"You don't need to compile python for Mac/Windows/Linux. It is an interpreted language, so you simply need to have the Python interpreter installed on the system of your choice (it is available for all three platforms). As for a GUI library that works cross platform, Python's Tk/Tcl widget library works very well, and I believe is sufficiently cross platform. Tkinter is the python interface to Tk/Tcl From the python project webpage: Tkinter is not the only GuiProgramming toolkit for Python. It is however the most commonly used one, and almost the only one that is portable between Unix, Mac and Windows "} {"user":"100","tags":[".net","colors","rgb","hsl"],"questionId":2942,"creationDate":"2008-08-05T22:40:25Z","title":"how to use HSL in Asp.net","acceptedAnswerId":3011,"type":"question","body":"What tools are used for working with HSL colors in .net? "} {"user":"454","questionId":2900,"creationDate":"2008-08-05T22:40:40Z","answerId":2943,"type":"answer","body":" Just to check, if you use just this part you get an error? If so, do you still get an error if you copy and paste one of those Inserts into this >page, I am trying to see if it's local to the page or that actual line. Also, can you post a copy of the connection calls (minus passwords), unless the inserts >use exactly the same syntax as this example. Here is what is in the connection.php file. I linked to the file through an include in the same fashion as where I execute the INSERT queries elsewhere in the code. $conn = mysql_connect(\"localhost\", ******, ******) or die(\"Could not connect\"); mysql_select_db(\"adbay_com_-_cms\") or die(\"Could not select database\"); I will try the working INSERT query in this area to check that out. As to the others posting about the password access. I did, as stated in my first posting, check permissions. I used phpMyAdmin to verify that the permissions for the user account I was using were correct. And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter. "} {"user":"71","questionId":2786,"creationDate":"2008-08-05T22:43:57Z","answerId":2944,"type":"answer","body":"I'd recommend getting VMWare Player and using the free Mono development platform image that is provided on the website. Download Mono Setup time for this will be minimal, and it will also allow you to get your code working in .NET and then focus on porting issues without a massive hassle of switching machines and the like. the VMWare Player tools will allow you to simply drag and drop the files over to copy them. I'm looking to take a couple of my .NET apps and make them Mono compliant, and this is the path I'm going to take here shortly. "} {"user":"357","questionId":104,"creationDate":"2008-08-05T22:47:49Z","answerId":2947,"type":"answer","body":" I guess in a managed environment, a leak would be you keeping an unnecessary reference to a large chunk of memory around. Absolutely. Also, not using the .Dispose() method on disposable objects when appropriate can cause mem leaks. The easiest way to do it is with a using block because it automatically executes .Dispose() at the end: StreamReader sr; using(sr = new StreamReader(\"somefile.txt\")) { //do some stuff } And if you create a class that is using unmanaged objects, if you're not implementing IDisposable correctly, you could be causing memory leaks for your class's users. "} {"user":"419","questionId":1949,"creationDate":"2008-08-05T22:51:08Z","answerId":2950,"type":"answer","body":"I'd been wrangling over the same question whilst retro fitting LINQ to SQL over a legacy DB. Our database is a bit of a whopper (150 tables) and after some thought and experimentation I elected to use multiple DataContexts. Whether this is considered an anti-pattern remains to be seen, but for now it makes life manageable. "} {"user":"30","questionId":2861,"creationDate":"2008-08-05T22:58:06Z","answerId":2952,"type":"answer","body":"You probably have as much already, but I think this is what you are trying to do: from __future__ import with_statement import re, os profile = \"\" os.system('wget --no-cookies --header \"Cookie: soba=(SeCreTCODe)\" http://stackoverflow.com/users/30/myProfile.html') with open(\"myProfile.html\") as f: for line in f: profile = profile + line f.close() p = re.compile('summarycount\">(\\d+)') #Rep is found here print p m = p.search(profile) print m print m.group(1) os.system(\"espeak \\\"Rep is at \" + m.group(1) + \" points\\\"\" os.remove(\"myProfile.html\") "} {"user":"227","tags":["ms-office","ocr","modi","indexing-service"],"questionId":2959,"creationDate":"2008-08-05T23:16:30Z","title":"Indexing Service + MODI = Full-text over OCR? You wish","type":"question","body":"I have configured Indexing Service to index my files, which also include scanned images saved as hi-res TIFF files. I also installed MS Office 2003+ and configured MS Office Document Imaging (MODI) correctly, so I can perform OCR on your images and even embed the OCR'd text into TIFFs. Indexing Service is able to index and find those TIFFs that you manually OCR'd and re-saved with text data (using MS Document Imaging tool). Whatever I do, I can't make the Indexing Service OCR and index the TIFF files without text data. You scour the web, find out how to turn on MODI debugging, and see that CISVC is calling MODI but somehow nothing seems to happen. Turns out, Data Execution Prevention (DEP) which is deployed with Windows XP SP2 thinks MODI is malicious and refuses to let it do its magic. I have been able to remove the Suck(TM) by turning DEP off completely, but (even though DEP hasn't yet saved my posterior that I can remember) I found this solution to be inelegant (read: the customer's IT manager's gonna fry you, if he hears about it). I'll share a better solution here, if I can come across it. "} {"user":"332","questionId":2658,"creationDate":"2008-08-05T23:20:03Z","answerId":2961,"type":"answer","body":"It's not that difficult to switch between version control systems. As others have mentioned the important thing is to start using anything as soon as possible. The benefits of using source control over not using source control vastly outweigh the differential benefits between different types of source control. Remember that no matter what version of source control you are using you will always be able to do a brute force conversion to another system by laying down the files from your old system onto disk and then importing those raw files into the new system. Moreover, being familiar with source control fundamentals is a very, very important skill to have as a software developer. "} {"user":"234","questionId":2872,"creationDate":"2008-08-05T23:22:00Z","answerId":2962,"type":"answer","body":"I'm sure this is possible if you hack at it hard enough, but I'd suggest it is not a good idea. 'Windows' (that you see on the screen) are highly coupled to processes. That is, each process which displays any GUI is expected to have a Message Loop, which processes all of the messages which are involved with creating and managing windows (things like 'clicked the button', 'closed the app', 'redraw the screen' and so on. Because of this, it is more or less assumed that if you have any message loop, it must be available for the lifetime of your process. For example windows might send you a 'quit' message, and you need to have a message loop available to handle that, even if you've got nothing on the screen. Your best bet is do it like this: Make a fake form which is never shown which is your 'main app' Start up Call Application.Run and pass in this fake form. Do your work in another thread, and fire events at the main thread when you need to do Gui stuff. "} {"user":"432","questionId":2861,"creationDate":"2008-08-05T23:37:44Z","answerId":2965,"type":"answer","body":"For Perl, there's WWW::Mechanize. "} {"user":"306","questionId":622,"creationDate":"2008-08-05T23:49:43Z","answerId":2967,"type":"answer","body":"I recommend a sieve, either the Sieve of Eratosthenes or the Sieve of Atkin. The sieve or Eratosthenes is probably the most intuitive method of finding a list of primes. Basically you: Write down a list of numbers from 2 to whatever limit you want, let's say 1000. Take the first number that isn't crossed off (for the first iteration this is 2) and cross off all multiples of that number from the list. Repeat step 2 until you reach the end of the list. All the numbers that aren't crossed off are prime. Obviously there are quite a few optimizations that can be done to make this algorithm work faster, but this is the basic idea. The sieve of Atkin uses a similar approach, but unfortunately I don't know enough about it to explain it to you. But I do know that the algorithm I linked takes 8 seconds to figure out all the primes up to 1000000000 on an ancient Pentium II-350 Sieve of Eratosthenes Source Code: http://web.archive.org/web/20140705111241/http://primes.utm.edu/links/programs/sieves/Eratosthenes/C_source_code/ Sieve of Atkin Source Code: http://cr.yp.to/primegen.html "} {"user":"362","tags":["java","string","parsing"],"questionId":2968,"creationDate":"2008-08-05T23:49:53Z","title":"What are the different methods to parse strings in Java?","acceptedAnswerId":2985,"type":"question","body":"For parsing player commands, I've most often used the split method to split a string by delimiters and then to then just figure out the rest by a series of ifs or switches. What are some different ways of parsing strings in Java? "} {"user":"124","questionId":2968,"creationDate":"2008-08-05T23:54:05Z","answerId":2969,"type":"answer","body":"I really like regular expressions. As long as the command strings are fairly simple, you can write a few regexes that could take a few pages of code to manually parse. I would suggest you check out http://www.regular-expressions.info for a good intro to regexes, as well as specific examples for Java. "} {"user":"58","tags":["security","cracking"],"questionId":2970,"creationDate":"2008-08-05T23:55:25Z","title":"My website got hacked... What should I do?","acceptedAnswerId":2976,"type":"question","body":"My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor. I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): http://www.98hs.ru/js.js <-- TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL. So I commented it out for now. It turns out his ftp password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer). I did a whois on 98hs.ru and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked... I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions? He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to do sftp on their site. I'm thinking his username and password got intercepted? So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked? For the record, here is the line of code that \"magically\" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this): "} {"user":"122","questionId":2968,"creationDate":"2008-08-05T23:57:02Z","answerId":2971,"type":"answer","body":"A simple string tokenizer on spaces should work, but there are really many ways you could do this. Here is an example using a tokenizer: String command = \"kick person\"; StringTokenizer tokens = new StringTokenizer(command); String action = null; if (tokens.hasMoreTokens()) { action = tokens.nextToken(); } if (action != null) { doCommand(action, tokens); } Then tokens can be further used for the arguments. This all assumes no spaces are used in the arguments... so you might want to roll your own simple parsing mechanism (like getting the first whitespace and using text before as the action, or using a regular expression if you don't mind the speed hit), just abstract it out so it can be used anywhere. "} {"user":"92","questionId":2970,"creationDate":"2008-08-06T00:00:22Z","answerId":2973,"type":"answer","body":"With a six word character password, he may have been brute forced. That is more likely than his ftp being intercepted, but it could be that too. Start with a stronger password. (8 characters is still fairly weak) See if this link to an internet security blog is helpful. "} {"user":"204","questionId":2900,"creationDate":"2008-08-06T00:05:34Z","answerId":2975,"type":"answer","body":" And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter. If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection. If you do the connection right in your script, not in a called file, do you get the same error? "} {"user":"204","questionId":2970,"creationDate":"2008-08-06T00:16:07Z","answerId":2976,"type":"answer","body":"Try and gather as much information as you can. See if the host can give you a log showing all the FTP connections that were made to your account. You can use those to see if it was even an FTP connection that was used to make the change and possibly get an IP address. If you're using a prepacked software like Wordpress, Drupal, or anything else that you didn't code there may be vulnerabilities in upload code that allows for this sort of modification. If it is custom built, double check any places where you allow users to upload files or modify existing files. The second thing would be to take a dump of the site as-is and check everything for other modifications. It may just be one single modification they made, but if they got in via FTP who knows what else is up there. Revert your site back to a known good status and, if need be, upgrade to the latest version. There is a level of return you have to take into account too. Is the damage worth trying to track the person down or is this something where you just live and learn and use stronger passwords? "} {"user":"user2189331","questionId":2968,"creationDate":"2008-08-06T00:16:25Z","answerId":2977,"type":"answer","body":"I would look at Java migrations of Zork, and lean towards a simple Natural Language Processor (driven either by tokenizing or regex) such as the following (from this link): public static boolean simpleNLP( String inputline, String keywords[]) { int i; int maxToken = keywords.length; int to,from; if( inputline.length() = inputline.length()) return false; // check for blank and empty lines while( to >=0 ) { to = inputline.indexOf(' ',from); if( to > 0){ lexed.addElement(inputline.substring(from,to)); from = to; while( inputline.charAt(from) == ' ' && from = keywords.length) { status = true; break;} } } return status; } ... Anything which gives a programmer a reason to look at Zork again is good in my book, just watch out for Grues. ... "} {"user":"419","questionId":2970,"creationDate":"2008-08-06T00:24:23Z","answerId":2978,"type":"answer","body":"Is the site just plain static HTML? i.e. he hasn't managed to code himself an upload page that permits anyone driving by to upload compromised scripts/pages? Why not ask webhost4life if they have any FTP logs available and report the issue to them. You never know, they may be quite receptive and find out for you exactly what happened? I work for a shared hoster and we always welcome reports such as these and can usually pinpoint the exact vector of attack based and advise as to where the customer went wrong. "} {"user":"188","questionId":2898,"creationDate":"2008-08-06T00:26:27Z","answerId":2979,"type":"answer","body":"I use pico or nano as my \"casual\" text editor in Linux/Solaris/etc. It's easy to come to grips with, and whilst you lose a couple of rows of text to the menu, at least it's easy to see how to exit, etc. You can even extend nano, I think, and add syntax highlighting. "} {"user":"188","questionId":2933,"creationDate":"2008-08-06T00:29:36Z","answerId":2980,"type":"answer","body":"Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed. Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however. MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X. "} {"user":"99","questionId":972,"creationDate":"2008-08-06T00:33:35Z","answerId":2982,"type":"answer","body":"In Python, there is a difference between functions and bound methods. >>> def foo(): ... print \"foo\" ... >>> class A: ... def bar( self ): ... print \"bar\" ... >>> a = A() >>> foo >>> a.bar > >>> Bound methods have been \"bound\" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called. Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want: >>> def fooFighters( self ): ... print \"fooFighters\" ... >>> A.fooFighters = fooFighters >>> a2 = A() >>> a2.fooFighters > >>> a2.fooFighters() fooFighters Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves): >>> a.fooFighters() fooFighters The problem comes when you want to attach a method to a single instance: >>> def barFighters( self ): ... print \"barFighters\" ... >>> a.barFighters = barFighters >>> a.barFighters() Traceback (most recent call last): File \"\", line 1, in TypeError: barFighters() takes exactly 1 argument (0 given) The function is not automatically bound when it's attached directly to an instance: >>> a.barFighters To bind it, we can use the MethodType function in the types module: >>> import types >>> a.barFighters = types.MethodType( barFighters, a ) >>> a.barFighters > >>> a.barFighters() barFighters This time other instances of the class have not been affected: >>> a2.barFighters() Traceback (most recent call last): File \"\", line 1, in AttributeError: A instance has no attribute 'barFighters' More information can be found by reading about descriptors and metaclass programming. "} {"user":"188","questionId":2873,"creationDate":"2008-08-06T00:40:03Z","answerId":2984,"type":"answer","body":"I've heard good things about clang static analyzer, which IIRC uses LLVM as it's backend. If that's implemented on your platform, that might be a good choice. From what I understand, it does a bit more than just syntax analysis. \"Automatic Bug Finding\", for instance. "} {"user":"432","questionId":2968,"creationDate":"2008-08-06T00:42:00Z","answerId":2985,"type":"answer","body":"I assume you're trying to make the command interface as forgiving as possible. If this is the case, I suggest you use an algorithm similar to this: Read in the string Split the string into tokens Use a dictionary to convert synonyms to a common form For example, convert \"hit\", \"punch\", \"strike\", and \"kick\" all to \"hit\" Perform actions on an unordered, inclusive base Unordered - \"punch the monkey in the face\" is the same thing as \"the face in the monkey punch\" Inclusive - If the command is supposed to be \"punch the monkey in the face\" and they supply \"punch monkey\", you should check how many commands this matches. If only one command, do this action. It might even be a good idea to have command priorities, and even if there were even matches, it would perform the top action. "} {"user":"188","questionId":2742,"creationDate":"2008-08-06T00:46:01Z","answerId":2986,"type":"answer","body":"I like Justin's suggestion, but I'll add to it: this solution is great for learning a language. If you don't rely on something like code-completion, then it forces you to learn the language better. (If you are working with something with a huge API, like Java or Cocoa, then you'll want the code completion, however!) It's also language-agnostic, and in the case of an interpreted language, particularly one that has an interactive interpreter, you'll probably spend just as much time in the shell/interpreter typing in commands. Even in a large-ish python project, I still work in an editor and 4 or 5 terminal windows. So, the trick is more about getting an editor which works for you. I'm not about to suggest one, as that's heading towards evangelism! "} {"user":"324","tags":["c#","winapi"],"questionId":2987,"creationDate":"2008-08-06T00:55:48Z","title":"Bringing Window to the Front in C# using Win32 API","acceptedAnswerId":2992,"type":"question","body":"I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus). What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work. What is the best way to go about this? Any thoughts? "} {"user":"861","tags":["algorithm","data-structures","tree","computer-science","graph-theory"],"questionId":2988,"creationDate":"2008-08-06T00:56:05Z","title":"What problems can be solved, or tackled more easily, using graphs and trees?","acceptedAnswerId":2999,"type":"question","body":"What are the most common problems that can be solved with both these data structures? It would be good for me to have also recommendations on books that: Implement the structures Implement and explain the reasoning of the algorithms that use them "} {"user":"user2189331","questionId":2987,"creationDate":"2008-08-06T01:06:45Z","answerId":2992,"type":"answer","body":"SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail. The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window Try capturing the focus with SetCapture prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this. "} {"user":"155","tags":["ruby","sockets","dns","nslookup"],"questionId":2993,"creationDate":"2008-08-06T01:07:52Z","title":"Reverse DNS in Ruby?","acceptedAnswerId":3012,"type":"question","body":"I'm in an environment with a lot of computers that haven't been properly inventoried. Basically, no one knows which IP goes with which mac address and which hostname. So I wrote the following: # This script goes down the entire IP range and attempts to # retrieve the Hostname and mac address and outputs them # into a file. Yay! require \"socket\" TwoOctets = \"10.26\" def computer_exists?(computerip) system(\"ping -c 1 -W 1 #{computerip}\") end def append_to_file(line) file = File.open(\"output.txt\", \"a\") file.puts(line) file.close end def getInfo(current_ip) begin if computer_exists?(current_ip) arp_output = `arp -v #{current_ip}` mac_addr = arp_output.to_s.match(/..:..:..:..:..:../) host_name = Socket.gethostbyname(current_ip) append_to_file(\"#{host_name[0]} - #{current_ip} - #{mac_addr}\\n\") end rescue SocketError => mySocketError append_to_file(\"unknown - #{current_ip} - #{mac_addr}\") end end (6..8).each do |i| case i when 6 for j in (1..190) current_ip = \"#{TwoOctets}.#{i}.#{j}\" getInfo(current_ip) end when 7 for j in (1..255) current_ip = \"#{TwoOctets}.#{i}.#{j}\" getInfo(current_ip) end when 8 for j in (1..52) current_ip = \"#{TwoOctets}.#{i}.#{j}\" getInfo(current_ip) end end end Everything works except it does not find a Reverse DNS. Sample output that I'm getting is this: - - 00:11:11:9B:13:9F - - 08:00:69:9A:97:C3 - - 08:00:69:93:2C:E2 If I do nslookup then I get the correct reverse DNS so that shows that my machine is seeing the DNS server. I have tried Socket.gethostbyname, gethostbyaddr, but it doesn't work. Any guidance will be much appreciated. "} {"user":"429","questionId":2988,"creationDate":"2008-08-06T01:18:12Z","answerId":2996,"type":"answer","body":"There's a course for such things at my university: CSE 326. I didn't think the book was too useful, but the projects are fun and teach you a fair bit about implementing some of the simpler structures. As for examples, one of the most common problems (by number of people using it) that's solved with trees is that of cell phone text entry. You can use trees, not necessarily binary, to represent the space of possible words that can come out of any given list of numbers that a user punches in very quickly. "} {"user":"402","questionId":2988,"creationDate":"2008-08-06T01:28:13Z","answerId":2999,"type":"answer","body":"The first thing I think about when I read this question is: what types of things use graphs/trees? and then I think backwards to how I could use them. For example, take two common uses of a tree: The DOM File systems The DOM, and XML for that matter, resemble tree structures. It makes sense, too. It makes sense because of how this data needs to be arranged. A file system, too. On a UNIX system there's a root node, and branching down below. When you mount a new device, you're attaching it onto the tree. You should also be asking yourself: does the data fall into this type of structure? Create data structures that make sense to the problem and the rest will follow. As far as being easier, I think thats relative. Are you good with recursive functions to traverse a tree/graph? What if you need to balance the tree? Think about a program that solves a word search puzzle. You could map out all the letters of the word search into a graph and check surrounding nodes to see if that string is matching any of the words. But couldn't you just do the same with with a single array? All you really need to do is move an index to check letters to the left and right, and by the width to check above and below letters. Solving this problem with a graph isn't difficult, but it can create a lot of extra work and difficulty if you're not comfortable with using them - of course that shouldn't discourage you from doing it, especially if you are learning about them. I hope that helps you think about these structures. As for a book recommendation, I'd have to go with Introduction to Algorithms. "} {"user":"457","questionId":2987,"creationDate":"2008-08-06T01:37:37Z","answerId":3003,"type":"answer","body":"You can try the BringWindowToTop function to not steal focus. I haven't used it, but it seems to be what you're looking for. "} {"user":"364","tags":["asp.net","dynamic-data"],"questionId":3004,"creationDate":"2008-08-06T01:42:51Z","title":"Using ASP.NET Dynamic Data / LINQ to SQL, how do you have two table fields have a relationship to the same foreign key?","acceptedAnswerId":3008,"type":"question","body":"I am using ASP.NET Dynamic Data for a project and I have a table that has two seperate fields that link to the same foreign key in a different table. This relationship works fine in SQL Server. However, in the LINQ to SQL model in the ASP.NET Dynamic Data model, only the first field's relationship is reflected. If I attempt to add the second relationship manually, it complains that it \"Cannot create an association \"ForeignTable_BaseTable\". The same property is listed more than once: \"Id\".\" This MSDN article gives such helpful advice as: Examine the message and note the property specified in the message. Click OK to dismiss the message box. Inspect the Association Properties and remove the duplicate entries. Click OK. "} {"user":"364","questionId":3004,"creationDate":"2008-08-06T01:53:45Z","answerId":3008,"type":"answer","body":"The solution is to delete and re-add BOTH tables to the LINQ to SQL diagram, not just the one you have added the second field and keys to. Alternatively, it appears you can make two associations using the LINQ to SQL interface - just don't try and bundle them into a single association. "} {"user":"313","questionId":36,"creationDate":"2008-08-06T01:54:21Z","answerId":3009,"type":"answer","body":"Unfortunately, I do not think that there is a clean way to do this in SQL2000. If you narrow your requirements to SQL Server 2005 (and later), then you are in business. You can use the SQLDependency class in System.Data.SqlClient. See Query Notifications in SQL Server (ADO.NET). "} {"user":"459","questionId":371,"creationDate":"2008-08-06T01:54:22Z","answerId":3010,"type":"answer","body":"You need a reverse DNS entry. You need to not send the same content to the same user twice. You need to test it with some common webmail and email clients. Personally I ran mine through a freshly installed spam assassin, a trained spam assassin, and multiple hotmail, gmail, and aol accounts. But have you seen that spam that doesn't seem to link to or advertise anything? That's a spammer trying to affect your Bayesian filter. If he can get a high rating and then include some words that would be in his future emails it might be automatically learned as good. So you can't really guess what a user's filter is going to be set as at the time of your mailing. Lastly, I did not sort my list by the domains, but randomized it. "} {"user":"49","questionId":2942,"creationDate":"2008-08-06T01:55:10Z","answerId":3011,"type":"answer","body":"The color struct provides three methods: GetHue, GetSaturation and GetBrightness. Bob Powell wrote an interesting piece on this several years ago. Bizarre historical note -- \"HSL\" (and the related \"HSV\") are one of the many things originating from Xerox's Palo Alto Research Center (PARC) in the 70's, courtesy of Alvy Ray Smith. "} {"user":"457","questionId":2993,"creationDate":"2008-08-06T01:56:58Z","answerId":3012,"type":"answer","body":"I would check out getaddrinfo. If you replace the line: host_name = Socket.gethostbyname(current_ip) with: host_name = Socket.getaddrinfo(current_ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][1] The getaddrinfo function returns an array of arrays. You can read more about it at: Ruby Socket Docs "} {"user":"49","questionId":2709,"creationDate":"2008-08-06T01:58:18Z","answerId":3013,"type":"answer","body":"You seem to have answered your own question there Nathan ;-) \"GetLastInputInfo\" is the way to go. One trick is that if your application is running on the desktop, and the user connects to a virtual machine, then GetLastInputInfo will report no activity (since there is no activity on the host machine). This can be different to the behaviour you want, depending on how you wish to apply the user input. "} {"user":"391","tags":["c#","visual-studio","setter","getter"],"questionId":3017,"creationDate":"2008-08-06T02:15:14Z","title":"How to generate getters and setters in Visual Studio?","acceptedAnswerId":3029,"type":"question","body":"By \"generate\", I mean auto-generation of the code necessary for a particuliar selected (set of) variable(s). But any more explicit explication or comment on good practice is welcome. "} {"user":"431","questionId":3017,"creationDate":"2008-08-06T02:24:29Z","answerId":3019,"type":"answer","body":"I don't have Visual Studio installed on my machine anymore (and I'm using Linux), but I do remember that there was an wizard hidden somewhere inside one of the menus that gave access to a class builder. With this wizard, you could define all your classes' details, including methods and attributes. If I remember well, there was an option through which you could ask VS to create the setters and getters automatically for you. I know it's quite vague, but check it out and you might find it. "} {"user":"468","questionId":1683,"creationDate":"2008-08-06T02:26:35Z","answerId":3020,"type":"answer","body":"Ive only built 2 applications that used the profile provider. Since then I have stayed away from using it. For both of the apps I used it to store information about the user such as their company name, address and phone number. This worked fine until our client wanted to be able to find a user by one of these fields. Searching involved looping through every users profile and comparing the information to the search criteria. As the user base grew the search time became unacceptable to our client. The only solution was to create a table to store the users information. Search speed was increased immensely. I would recommend storing this type of information in its own table. "} {"user":"358","tags":["recursion","computer-science"],"questionId":3021,"creationDate":"2008-08-06T02:29:51Z","title":"What is recursion and when should I use it?","type":"question","body":"One of the topics that seems to come up regularly on mailing lists and online discussions is the merits (or lack thereof) of doing a Computer Science Degree. An argument that seems to come up time and again for the negative party is that they have been coding for some number of years and they have never used recursion. So the question is: What is recursion? When would I use recursion? Why don't people use recursion? "} {"user":"372","questionId":3017,"creationDate":"2008-08-06T02:31:37Z","answerId":3023,"type":"answer","body":"By generate, do you mean auto-generate? If that's not what you mean: Visual Studio 2008 has the easiest implementation for this: public PropertyType PropertyName { get; set; } In the background this creates an implied instance variable to which your property is stored and retrieved. However if you want to put in more logic in your Properties, you will have to have an instance variable for it: private PropertyType _property; public PropertyType PropertyName { get { //logic here return _property; } set { //logic here _property = value; } } Previous versions of Visual Studio always used this longhand method as well. "} {"user":"2089740","questionId":3021,"creationDate":"2008-08-06T02:35:07Z","answerId":3025,"type":"answer","body":" A function that calls itself When a function can be (easily) decomposed into a simple operation plus the same function on some smaller portion of the problem. I should say, rather, that this makes it a good candidate for recursion. They do! The canonical example is the factorial which looks like: int fact(int a) { if(a==1) return 1; return a*fact(a-1); } In general, recursion isn't necessarily fast (function call overhead tends to be high because recursive functions tend to be small, see above) and can suffer from some problems (stack overflow anyone?). Some say they tend to be hard to get 'right' in non-trivial cases but I don't really buy into that. In some situations, recursion makes the most sense and is the most elegant and clear way to write a particular function. It should be noted that some languages favor recursive solutions and optimize them much more (LISP comes to mind). "} {"user":"453","questionId":3017,"creationDate":"2008-08-06T02:35:37Z","answerId":3026,"type":"answer","body":"If you are using Visual Studio 2005 and up you can create a setter/getter real fast using the insert snippet command. Right click on your code click on Insert Snippet (Ctrl+k,x) and then choose \"prop\" form the list. Hope this helps. "} {"user":"439","tags":["security","usability","captcha"],"questionId":3027,"creationDate":"2008-08-06T02:36:23Z","title":"Is there an Unobtrusive Captcha for web forms?","type":"question","body":"What is the best unobtrusive CAPTCHA for web forms? One that does not involve a UI, rather a non-UI Turing test. I have seen a simple example of a non UI CAPTCHA like the Nobot control from Microsoft. I am looking for a CAPTCHA that does not ask the user any question in any form. No riddles, no what's in this image. "} {"user":"2089740","questionId":3027,"creationDate":"2008-08-06T02:40:53Z","answerId":3028,"type":"answer","body":"How can anything on a website not have a UI? Could you maybe be more specific about what you mean by this? I think by definition a Turing test needs a UI -- it has to interact with a user. Did you mean a GUI? Does that mean a non-image based Captcha? "} {"user":"234","questionId":3017,"creationDate":"2008-08-06T02:43:21Z","answerId":3029,"type":"answer","body":"Rather than using ctrl+k,x you can also just type prop and then hit tab twice "} {"user":"369","questionId":3021,"creationDate":"2008-08-06T02:44:53Z","answerId":3030,"type":"answer","body":"A recursive function is one which calls itself. The most common reason I've found to use it is traversing a tree structure. For example, if I have a TreeView with checkboxes (think installation of a new program, \"choose features to install\" page), I might want a \"check all\" button which would be something like this (pseudocode): function cmdCheckAllClick { checkRecursively(TreeView1.RootNode); } function checkRecursively(Node n) { n.Checked = True; foreach ( n.Children as child ) { checkRecursively(child); } } So you can see that the checkRecursively first checks the node which it is passed, then calls itself for each of that node's children. You do need to be a bit careful with recursion. If you get into an infinite recursive loop, you will get a Stack Overflow exception :) I can't think of a reason why people shouldn't use it, when appropriate. It is useful in some circumstances, and not in others. I think that because it's an interesting technique, some coders perhaps end up using it more often than they should, without real justification. This has given recursion a bad name in some circles. "} {"user":"392","questionId":3017,"creationDate":"2008-08-06T02:52:02Z","answerId":3032,"type":"answer","body":"Visual Studio also has a feature that will generate a Property from a private variable. If you right-click on a variable, in the context menu that pops up click on the \"Refactor\" item. Then choose encapsulate field. This will create a getter/setter property for a variable. I'm not too big a fan of this technique as it is a little bit awkward to use if you have to create a lot of getters/setters, and it puts the property directly below the private field, which bugs me because I usually have all of my private fields grouped together, and this Visual Studio feature breaks my class' formatting. "} {"user":"219","tags":["perl","hash","iteration","each"],"questionId":3033,"creationDate":"2008-08-06T02:53:13Z","title":"What's the safest way to iterate through the keys of a Perl hash?","acceptedAnswerId":3360,"type":"question","body":"If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using each may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way? # Method 1 while (my ($key, $value) = each(%hash)) { # Something } # Method 2 foreach my $key (keys(%hash)) { # Something } "} {"user":"358","questionId":3021,"creationDate":"2008-08-06T02:54:58Z","answerId":3035,"type":"answer","body":"Recursion is a method of solving problems based on the divide and conquer mentality. The basic idea is that you take the original problem and divide it into smaller (more easily solved) instances of itself, solve those smaller instances (usually by using the same algorithm again) and then reassemble them into the final solution. The canonical example is a routine to generate the Factorial of n. The Factorial of n is calculated by multiplying all of the numbers between 1 and n. An iterative solution in C# looks like this: public int Fact(int n) { int fact = 1; for( int i = 2; i <= n; i++) { fact = fact * i; } return fact; } There's nothing surprising about the iterative solution and it should make sense to anyone familiar with C#. The recursive solution is found by recognising that the nth Factorial is n * Fact(n-1). Or to put it another way, if you know what a particular Factorial number is you can calculate the next one. Here is the recursive solution in C#: public int FactRec(int n) { if( n < 2 ) { return 1; } return n * FactRec( n - 1 ); } The first part of this function is known as a Base Case (or sometimes Guard Clause) and is what prevents the algorithm from running forever. It just returns the value 1 whenever the function is called with a value of 1 or less. The second part is more interesting and is known as the Recursive Step. Here we call the same method with a slightly modified parameter (we decrement it by 1) and then multiply the result with our copy of n. When first encountered this can be kind of confusing so it's instructive to examine how it works when run. Imagine that we call FactRec(5). We enter the routine, are not picked up by the base case and so we end up like this: // In FactRec(5) return 5 * FactRec( 5 - 1 ); // which is return 5 * FactRec(4); If we re-enter the method with the parameter 4 we are again not stopped by the guard clause and so we end up at: // In FactRec(4) return 4 * FactRec(3); If we substitute this return value into the return value above we get // In FactRec(5) return 5 * (4 * FactRec(3)); This should give you a clue as to how the final solution is arrived at so we'll fast track and show each step on the way down: return 5 * (4 * FactRec(3)); return 5 * (4 * (3 * FactRec(2))); return 5 * (4 * (3 * (2 * FactRec(1)))); return 5 * (4 * (3 * (2 * (1)))); That final substitution happens when the base case is triggered. At this point we have a simple algrebraic formula to solve which equates directly to the definition of Factorials in the first place. It's instructive to note that every call into the method results in either a base case being triggered or a call to the same method where the parameters are closer to a base case (often called a recursive call). If this is not the case then the method will run forever. "} {"user":"431","questionId":3021,"creationDate":"2008-08-06T03:00:16Z","answerId":3037,"type":"answer","body":"I have created a recursive function to concatenate a list of strings with a separator between them. I use it mostly to create SQL expressions, by passing a list of fields as the 'items' and a 'comma+space' as the separator. Here's the function (It uses some Borland Builder native data types, but can be adapted to fit any other environment): String ArrangeString(TStringList* items, int position, String separator) { String result; result = items->Strings[position]; if (position <= items->Count) result += separator + ArrangeString(items, position + 1, separator); return result; } I call it this way: String columnsList; columnsList = ArrangeString(columns, 0, \", \"); Imagine you have an array named 'fields' with this data inside it: 'albumName', 'releaseDate', 'labelId'. Then you call the function: ArrangeString(fields, 0, \", \"); As the function starts to work, the variable 'result' receives the value of the position 0 of the array, which is 'albumName'. Then it checks if the position it's dealing with is the last one. As it isn't, then it concatenates the result with the separator and the result of a function, which, oh God, is this same function. But this time, check it out, it call itself adding 1 to the position. ArrangeString(fields, 1, \", \"); It keeps repeating, creating a LIFO pile, until it reaches a point where the position being dealt with IS the last one, so the function returns only the item on that position on the list, not concatenating anymore. Then the pile is concatenated backwards. Got it? If you don't, I have another way to explain it. :o) "} {"user":"457","questionId":469,"creationDate":"2008-08-06T03:01:23Z","answerId":3040,"type":"answer","body":"Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef. Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font. "} {"user":"216","questionId":3021,"creationDate":"2008-08-06T03:12:15Z","answerId":3042,"type":"answer","body":"Recursion works best with what I like to call \"fractal problems\", where you're dealing with a big thing that's made of smaller versions of that big thing, each of which is an even smaller version of the big thing, and so on. If you ever have to traverse or search through something like a tree or nested identical structures, you've got a problem that might be a good candidate for recursion. People avoid recursion for a number of reasons: Most people (myself included) cut their programming teeth on procedural or object-oriented programming as opposed to functional programming. To such people, the iterative approach (typically using loops) feels more natural. Those of us who cut our programming teeth on procedural or object-oriented programming have often been told to avoid recursion because it's error prone. We're often told that recursion is slow. Calling and returning from a routine repeatedly involves a lot of stack pushing and popping, which is slower than looping. I think some languages handle this better than others, and those languages are most likely not those where the dominant paradigm is procedural or object-oriented. For at least a couple of programming languages I've used, I remember hearing recommendations not to use recursion if it gets beyond a certain depth because its stack isn't that deep. "} {"user":"116","questionId":3021,"creationDate":"2008-08-06T03:12:38Z","answerId":3043,"type":"answer","body":"Here's a simple example: how many elements in a set. (there are better ways to count things, but this is a nice simple recursive example.) First, we need two rules: if the set is empty, the count of items in the set is zero (duh!). if the set is not empty, the count is one plus the number of items in the set after one item is removed. Suppose you have a set like this: [x x x]. let's count how many items there are. the set is [x x x] which is not empty, so we apply rule 2. the number of items is one plus the number of items in [x x] (i.e. we removed an item). the set is [x x], so we apply rule 2 again: one + number of items in [x]. the set is [x], which still matches rule 2: one + number of items in []. Now the set is [], which matches rule 1: the count is zero! Now that we know the answer in step 4 (0), we can solve step 3 (1 + 0) Likewise, now that we know the answer in step 3 (1), we can solve step 2 (1 + 1) And finally now that we know the answer in step 2 (2), we can solve step 1 (1 + 2) and get the count of items in [x x x], which is 3. Hooray! We can represent this as: count of [x x x] = 1 + count of [x x] = 1 + (1 + count of [x]) = 1 + (1 + (1 + count of [])) = 1 + (1 + (1 + 0))) = 1 + (1 + (1)) = 1 + (2) = 3 When applying a recursive solution, you usually have at least 2 rules: the basis, the simple case which states what happens when you have \"used up\" all of your data. This is usually some variation of \"if you are out of data to process, your answer is X\" the recursive rule, which states what happens if you still have data. This is usually some kind of rule that says \"do something to make your data set smaller, and reapply your rules to the smaller data set.\" If we translate the above to pseudocode, we get: numberOfItems(set) if set is empty return 0 else remove 1 item from set return 1 + numberOfItems(set) There's a lot more useful examples (traversing a tree, for example) which I'm sure other people will cover. "} {"user":"40","questionId":3021,"creationDate":"2008-08-06T03:13:35Z","answerId":3044,"type":"answer","body":"I use recursion. What does that have to do with having a CS degree... (which I don't, by the way) Common uses I have found: sitemaps - recurse through filesystem starting at document root spiders - crawling through a website to find email address, links, etc. ? "} {"user":"271","tags":["office-2007","office-2003"],"questionId":3045,"creationDate":"2008-08-06T03:14:59Z","title":"Linking two Office documents","acceptedAnswerId":3053,"type":"question","body":"Problem: I have two spreadsheets that each serve different purposes but contain one particular piece of data that needs to be the same in both spreadsheets. This piece of data (one of the columns) gets updated in spreadsheet A but needs to also be updated in spreadsheet B. Goal: A solution that would somehow link these two spreadsheets together (keep in mind that they exist on two separate LAN shares on the network) so that when A is updated, B is automatically updated for the corresponding record. *Note that I understand fully that a database would probably be a better plan for tasks such as these but unfortunately I have no say in that matter. **Note also that this needs to work for Office 2003 and Office 2007 "} {"user":"462","tags":["java","c++","windows","unix"],"questionId":3049,"creationDate":"2008-08-06T03:19:19Z","title":"How do I configure and communicate with a serial port?","acceptedAnswerId":3054,"type":"question","body":"I need to send and receive data over serial connections (RS-232 and RS-422). How do I set up and communicate with such a connection? How do I figure out what the configuration settings (e.g. baud rate) should be and how do I set them? In particular I am looking to do this in Java, C/C++, or one of the major Unix shells but I also have some interest in serial programming using Windows/Hyperterminal. "} {"user":"369","questionId":3021,"creationDate":"2008-08-06T03:19:31Z","answerId":3050,"type":"answer","body":"Mario, I don't understand why you used recursion for that example.. Why not simply loop through each entry? Something like this: String ArrangeString(TStringList* items, String separator) { String result = items->Strings[0]; for (int position=1; position < items->count; position++) { result += separator + items->Strings[position]; } return result; } The above method would be faster, and is simpler. There's no need to use recursion in place of a simple loop. I think these sorts of examples is why recursion gets a bad rap. Even the canonical factorial function example is better implemented with a loop. "} {"user":"285","questionId":3027,"creationDate":"2008-08-06T03:19:56Z","answerId":3052,"type":"answer","body":"I think you might be alluding to an \"invisible\" captcha. Check out the Subkismet project for an invisible captcha implementation. http://www.codeplex.com/subkismet "} {"user":"431","questionId":3045,"creationDate":"2008-08-06T03:25:25Z","answerId":3053,"type":"answer","body":"So you mean that AD743 on spreadsheet B must be equal to AD743 on spreadsheet A? Try this: Open both spreadsheets on the same machine. Go to AD743 on spreadsheet B. Type =. Go to spreadsheed A and click on AD743. Press enter. You'll notice that the formula is something like '[path-to-file+file-name].worksheet-name!AD743'. The value on spreadsheet B will be updated when you open it. In fact, it will ask you if you want to update. Of course, your connection must be up and running for it to update. Also, you can't change the name or the path of spreadsheet A. "} {"user":"2089740","questionId":3049,"creationDate":"2008-08-06T03:27:43Z","answerId":3054,"type":"answer","body":"Build a time machine and go back to 1987? Ho ho. Ok, no more snarky comments. How do I figure out what the configuration settings (e.g. baud rate) should be... Read the datasheet? Ok, ok. Seriously, last one. If you don't know the baud rate of the device you are trying to communicate with, you have two choices. Start guessing, or possibly bust out an o-scope. If you need a good starting point, let me suggest 9600-8-N-1. My suspicion is you can get there with brute force relatively quickly. There's a third option of having an old-school ninja who can tell just by the LOOK of the garbled characters at some standard baud rate what actual baud rate is. An impressive party trick to be sure. Hopefully though you have access to this information. In unix/linux, you can get ahold of minicom to play with the serial port directly. This should make it fairly quick to get the configuration figured out. one of the major Unix shells In Unix the serial port(s) is/are file-mapped into the /dev/ subdir. ttyS0, for example. If you setup the correct baud rate and whatnot using minicom, you can even cat stuff to that file to send stuff out there. On to the meat of the question, you can access it programmatically through the POSIX headers. termios.h is the big one. See: http://www.easysw.com/~mike/serial/serial.html#3_1 (NOT AVAILABLE ANYMORE) but I also have some interest in serial programming using Windows/Hyperterminal. Hyperterminal and minicom are basically the same program. As for how Windows let's you get access to the serial port, I'll leave that question for someone else. I haven't done that in Windows since the Win95 days. "} {"user":"116","questionId":2970,"creationDate":"2008-08-06T03:31:22Z","answerId":3055,"type":"answer","body":"You mention your Dad was using a website publishing tool. If the publishing tool publishes from his computer to the server, it may be the case that his local files are clean, and that he just needs to republish to the server. He should see if there's a different login method to his server than plain FTP, though... that's not very secure because it sends his password as clear-text over the internet. "} {"user":"101","questionId":3021,"creationDate":"2008-08-06T03:32:35Z","answerId":3056,"type":"answer","body":"To recurse on a solved problem: do nothing, you're done. To recurse on an open problem: do the next step, then recurse on the rest. "} {"user":"58","tags":["performance","oop","maintainability","procedural","interpreted-language"],"questionId":3057,"creationDate":"2008-08-06T03:34:01Z","title":"Speed Comparisons - Procedural vs. OO in interpreted languages","acceptedAnswerId":3062,"type":"question","body":"In interpreted programming languages, such as PHP and JavaScript, what are the repercussions of going with an Object Oriented approach over a Procedural approach? Specifically what I am looking for is a checklist of things to consider when creating a web application and choosing between Procedural and Object Oriented approaches, to optimize not only for speed, but maintainability as well. Cited research and test cases would be helpful as well if you know of any articles exploring this further. Bottom line: how big (if any) is the performance hit really, when going with OO vs. Procedural in an interpreted language? "} {"user":"358","tags":["inversion-of-control","design-patterns"],"questionId":3058,"creationDate":"2008-08-06T03:35:27Z","title":"What is Inversion of Control?","acceptedAnswerId":3140,"type":"question","body":"Inversion of Control (or IoC) can be quite confusing when it is first encountered. What is it? What problems does it solve? When is it appropriate and when not? "} {"user":"116","questionId":3057,"creationDate":"2008-08-06T03:35:31Z","answerId":3059,"type":"answer","body":"Bottom line: no, because the overhead of interpretation overwhelms the overhead of method dispatching. "} {"user":"429","questionId":3049,"creationDate":"2008-08-06T03:35:50Z","answerId":3060,"type":"answer","body":"From the other side, if you want to do it using C#, which will run on both Windows and Linux--with some limitations (EDIT: which may be out of date. I have no way to test it.). Just create a SerialPort object, set its baudrate, port and any other odd settings, call open on it, and write out your byte[]s. After all the setup, the SerialPort object acts very similar to any networked stream, so it should be easy enough to figure out. And as ibrandy states, you need to know all these settings, like baud rate, before you even start attempting to communicate to any serial device. "} {"user":"121","tags":["python"],"questionId":3061,"creationDate":"2008-08-06T03:36:08Z","title":"Calling a function of a module from a string with the function's name in Python","acceptedAnswerId":3071,"type":"question","body":"What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo, and I have a string whose contents are \"bar\". What is the best way to go about calling foo.bar()? I need to get the return value of the function, which is why I don't just use eval. I figured out how to do it by using eval to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this. "} {"user":"2089740","questionId":3057,"creationDate":"2008-08-06T03:36:28Z","answerId":3062,"type":"answer","body":"Maybe I'm crazy but worrying about speed in cases like this using an interpretive language is like trying to figure out what color to paint the shed. Let's not even get into the idea that this kind of optimization is entirely pre-mature. You hit the nail on the head when you said 'maintainability'. I'd choose the approach that is the most productive and most maintainable. If you need speed later, it ain't gonna come from switching between procedural versus object oriented coding paradigms inside an interpreted language. "} {"user":"430","questionId":3033,"creationDate":"2008-08-06T03:43:58Z","answerId":3066,"type":"answer","body":"I may get bitten by this one but I think that it's personal preference. I can't find any reference in the docs to each() being different than keys() or values() (other than the obvious \"they return different things\" answer. In fact the docs state the use the same iterator and they all return actual list values instead of copies of them, and that modifying the hash while iterating over it using any call is bad. All that said, I almost always use keys() because to me it is usually more self documenting to access the key's value via the hash itself. I occasionally use values() when the value is a reference to a large structure and the key to the hash was already stored in the structure, at which point the key is redundant and I don't need it. I think I've used each() 2 times in 10 years of Perl programming and it was probably the wrong choice both times =) "} {"user":"291","tags":["visual-studio","plugins"],"questionId":3067,"creationDate":"2008-08-06T03:44:41Z","title":"Plugin for Visual Studio to Mimic Eclipse's \"Open Type\" or \"Open Resource\" Keyboard Access","type":"question","body":"If you've ever used Eclipse, you've probably noticed the great keyboard shortcuts that let you hit a shortcut key combination, then just type the first few characters of a function, class, filename, etc. It's even smart enough to put open files first in the list. I'm looking for a similar functionality for Visual Studio 2008. I know there's a findfiles plugin on codeproject, but that one is buggy and a little weird, and doesn't give me access to functions or classes. "} {"user":"92","questionId":3057,"creationDate":"2008-08-06T03:49:20Z","answerId":3068,"type":"answer","body":"If you are using an interpreted language, the difference is irrelevant. You should not be using an interpreted language if performance is an issue. Both will perform about the same. "} {"user":"363","questionId":3061,"creationDate":"2008-08-06T03:57:16Z","answerId":3071,"type":"answer","body":"Assuming module foo with method bar: import foo method_to_call = getattr(foo, 'bar') result = method_to_call() As far as that goes, lines 2 and 3 can be compressed to: result = getattr(foo, 'bar')() if that makes more sense for your use case. You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on. "} {"user":"153","questionId":3033,"creationDate":"2008-08-06T04:04:16Z","answerId":3072,"type":"answer","body":"I always use method 2 as well. The only benefit of using each is if you're just reading (rather than re-assigning) the value of the hash entry, you're not constantly de-referencing the hash. "} {"user":"457","questionId":1598,"creationDate":"2008-08-06T04:10:52Z","answerId":3073,"type":"answer","body":"The official size is 57x57. I would recommend using the exact size simply due to the fact that it takes less memory when loaded (unless Apple caches the scaled representation). With that said, Rex is right that any square size will work "} {"user":"404","questionId":2913,"creationDate":"2008-08-06T04:14:42Z","answerId":3074,"type":"answer","body":"If you're mostly concerned with data layer testing, you might want to check out this book: xUnit Test Patterns: Refactoring Test Code. I was always unsure about it myself, but this book does a great job to help enumerate the concerns like performance, reproducibility, etc. "} {"user":"404","tags":["ajax","sharepoint"],"questionId":3075,"creationDate":"2008-08-06T04:20:41Z","title":"Can ASP.NET AJAX partial rendering work inside a SharePoint 2007 application page?","acceptedAnswerId":3084,"type":"question","body":"I have a simple page with my ScriptManager and my UpdatePanel, and my ContentTemplate has one ListBox and one Label. I am just trying to catch its OnSelectionChanged so I can update the text in the Label. No matter what settings I try to tweak, I always get a full-page postback. Is this really not going to work, or am I just screwing this up? "} {"user":"328","questionId":2804,"creationDate":"2008-08-06T04:25:02Z","answerId":3078,"type":"answer","body":"I wound up just implementing the translation manually. The code's not too bad, but it did leave me wishing that they provided support for it directly. I could see such a method being useful in a lot of different circumstances. I guess that's why they added extension methods :) In pseudocode: // Recompute the image scaling the zoom mode uses to fit the image on screen imageScale ::= min(pictureBox.width / image.width, pictureBox.height / image.height) scaledWidth ::= image.width * imageScale scaledHeight ::= image.height * imageScale // Compute the offset of the image to center it in the picture box imageX ::= (pictureBox.width - scaledWidth) / 2 imageY ::= (pictureBox.height - scaledHeight) / 2 // Test the coordinate in the picture box against the image bounds if pos.x < imageX or imageX + scaledWidth < pos.x then return null if pos.y < imageY or imageY + scaledHeight < pos.y then return null // Compute the normalized (0..1) coordinates in image space u ::= (pos.x - imageX) / imageScale v ::= (pos.y - imageY) / imageScale return (u, v) To get the pixel position in the image, you'd just multiply by the actual image pixel dimensions, but the normalized coordinates allow you to address the original responder's point about resolving ambiguity on a case-by-case basis. "} {"user":"430","questionId":1276,"creationDate":"2008-08-06T04:27:52Z","answerId":3079,"type":"answer","body":"I once was called upon to look at a mysql that had \"stopped working\". I discovered that the DB files were residing on a Network Appliance filer mounted with NFS2 and with a maximum file size of 2GB. And sure enough, the table that had stopped accepting transactions was exactly 2GB on disk. But with regards to the performance curve I'm told that it was working like a champ right up until it didn't work at all! This experience always serves for me as a nice reminder that there're always dimensions above and below the one you naturally suspect. "} {"user":"457","questionId":3058,"creationDate":"2008-08-06T04:33:19Z","answerId":3082,"type":"answer","body":" Wikipedia Article. To me, inversion of control is turning your sequentially written code and turning it into an delegation structure. Instead of your program explicitly controlling everything, your program sets up a class or library with certain functions to be called when certain things happen. It solves code duplication. For example, in the old days you would manually write your own event loop, polling the system libraries for new events. Nowadays, most modern APIs you simply tell the system libraries what events you're interested in, and it will let you know when they happen. Inversion of control is a practical way to reduce code duplication, and if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control. Inversion of control is made easy in many languages through the concept of delegates, interfaces, or even raw function pointers. It is not appropriate to use in all cases, because the flow of a program can be harder to follow when written this way. It's a useful way to design methods when writing a library that will be reused, but it should be used sparingly in the core of your own program unless it really solves a code duplication problem. "} {"user":"49","questionId":3075,"creationDate":"2008-08-06T04:43:31Z","answerId":3084,"type":"answer","body":"You need to have Sharepoint 2007 service pack 1 -- or else there's no chance. (Sharepoint 2007 predates ajax 1.0 -- they built some support into service pack 1) Next, from a trouble shooting point of view, test that the exact same code functions as expected when hosted in a regular asp.net page. (Literally copy and paste your code across into a fresh page, to rule out any typographical errors). Ruling sharepoint in or out of the problem area will help narrow down the solution space. "} {"user":"92","tags":["python","language-agnostic"],"questionId":3088,"creationDate":"2008-08-06T05:01:16Z","title":"Best ways to teach a beginner to program?","type":"question","body":"Original Question I am currently engaged in teaching my brother to program. He is a total beginner, but very smart. (And he actually wants to learn). I've noticed that some of our sessions have gotten bogged down in minor details, and I don't feel I've been very organized. (But the answers to this post have helped a lot.) What can I do better to teach him effectively? Is there a logical order that I can use to run through concept by concept? Are there complexities I should avoid till later? The language we are working with is Python, but advice in any language is welcome. How to Help If you have good ones please add the following in your answer: Beginner Exercises and Project Ideas Resources for teaching beginners Screencasts / blog posts / free e-books Print books that are good for beginners Please describe the resource with a link to it so I can take a look. I want everyone to know that I have definitely been using some of these ideas. Your submissions will be aggregated in this post. Online Resources for teaching beginners: A Gentle Introduction to Programming Using Python How to Think Like a Computer Scientist Alice: a 3d program for beginners Scratch (A system to develop programming skills) How To Design Programs Structure and Interpretation of Computer Programs Learn To Program Robert Read's How To Be a Programmer Microsoft XNA Spawning the Next Generation of Hackers COMP1917 Higher Computing lectures by Richard Buckland (requires iTunes) Dive into Python Python Wikibook Project Euler - sample problems (mostly mathematical) pygame - an easy python library for creating games Invent Your Own Computer Games With Python Foundations of Programming for a next step beyond basics. Squeak by Example Snake Wrangling For Kids (It's not just for kids!) Recommended Print Books for teaching beginners Accelerated C++ Python Programming for the Absolute Beginner Code by Charles Petzold Python Programming: An Introduction to Computer Science 2nd Edition "} {"user":"342","questionId":3049,"creationDate":"2008-08-06T05:04:57Z","answerId":3090,"type":"answer","body":"At work we use teraterm and realterm for checking serial data is correctly formatted. Also we have a hardware splitter with a switch so we can monitor traffic to our application via a cable back to another port. Windows allows you access to the serial port via CreateFile. That gives you a handle and from there you can configure access. "} {"user":"342","questionId":3067,"creationDate":"2008-08-06T05:06:57Z","answerId":3091,"type":"answer","body":"Some of the neat features are available in Visual Assist X, though not all of them. I've asked on their forums, but they haven't appeared as yet. VAX gets updated regularly on a rough 4 week period for bug fixes and a new feature every couple of months. "} {"user":"430","questionId":3088,"creationDate":"2008-08-06T05:08:37Z","answerId":3092,"type":"answer","body":"If he's interested, aren't the minor details the good parts? Using python, you've already cut the GUI off of it so that confusion is gone. Why not pick a project, a game or something, and implement it. The classic hi-lo number guessing game can be simply implemented from the command line in 20-30 lines of code (depending on language of course) and gives you variables, conditions, loops, and user input. "} {"user":"101","questionId":3021,"creationDate":"2008-08-06T05:09:44Z","answerId":3093,"type":"answer","body":"There are a number of good explanations of recursion in this thread, this answer is about why you shouldn't use it in most languages.* In the majority of major imperative language implementations (i.e. every major implementation of C, C++, Basic, Python, Ruby,Java, and C#) iteration is vastly preferable to recursion. To see why, walk through the steps that the above languages use to call a function: space is carved out on the stack for the function's arguments and local variables the function's arguments are copied into this new space control jumps to the function the function's code runs the function's result is copied into a return value the stack is rewound to its previous position control jumps back to where the function was called Doing all of these steps takes time, usually a little bit more than it takes to iterate through a loop. However, the real problem is in step #1. When many programs start, they allocate a single chunk of memory for their stack, and when they run out of that memory (often, but not always due to recursion), the program crashes due to a stack overflow. So in these languages recursion is slower and it makes you vulnerable to crashing. There are still some arguments for using it though. In general, code written recursively is shorter and a bit more elegant, once you know how to read it. There is a technique that language implementers can use called tail call optimization which can eliminate some classes of stack overflow. Put succinctly: if a function's return expression is simply the result of a function call, then you don't need to add a new level onto the stack, you can reuse the current one for the function being called. Regrettably, few imperative language-implementations have tail-call optimization built in. * I love recursion. My favorite static language doesn't use loops at all, recursion is the only way to do something repeatedly. I just don't think that recursion is generally a good idea in languages that aren't tuned for it. ** By the way Mario, the typical name for your ArrangeString function is \"join\", and I'd be surprised if your language of choice doesn't already have an implementation of it. "} {"user":"423","questionId":3088,"creationDate":"2008-08-06T05:13:15Z","answerId":3095,"type":"answer","body":"First of all, start out like everyone else does: with a Hello World program. It's simple, and it gives them a basic feel for the layout of a program. Try and remember back to when you were first programming, and how difficult some of the concepts were - start simple. After Hello World, move on to creating some basic variables, arithmetic, then onto boolean logic and if/else statements. If you've got one of your old programming textbooks, check out some of the early examples and have him run through those. Just don't try to introduce too much all at once, or it will be overwhelming and confusing. "} {"user":"122","questionId":3088,"creationDate":"2008-08-06T05:16:25Z","answerId":3097,"type":"answer","body":"I would actually argue to pick a simpler language with fewer instructions. I personally learned on BASIC at home, as did Jeff. This way, you don't have to delve into more complicated issues like object oriented programming, or even procedures if you don't want to. Once he can handle simple control flow, then move on to something a little more complicated, but only simple features. Maybe start with very simple programs that just add 2 numbers, and then grow to something that might require a branch, then maybe reading input and responding to it, then some kind of loop, and start combining them all together. Just start little and work your way up. Don't do any big projects until he can grasp the fundamentals (otherwise it may very well be too daunting and he could give up midway). Once he's mastered BASIC or whatever you choose, move on to something more complicated. Just my $0.02 "} {"user":"340","questionId":3088,"creationDate":"2008-08-06T05:18:46Z","answerId":3099,"type":"answer","body":"Something you should be very mindful of while teaching your brother to program is for him not to rely too heavily on you. Often when I find myself helping others they will begin to think of me as answer book to all of their questions and instead of experimenting to find an answer they simply ask me. Often the best teacher is experimentation and every time your brother has a question like \"What will happen if I add 2 to a string?\" you should tell him to try it out and see for himself. Also I have noticed that when I cannot get a concept through to someone, it helps to see some sample code where we can look at each segment individually and explain it piece by piece. As a side note people new to programming often have trouble with the idea of object oriented programming, they will say they understand it when you teach it to them but will not get a clear concept of it until actually implementing it. "} {"user":"101","questionId":3058,"creationDate":"2008-08-06T05:20:11Z","answerId":3100,"type":"answer","body":"I agree with NilObject, but I'd like to add to this: if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control If you find yourself copying and pasting code around, you're almost always doing something wrong. Codified as the design principle Once and Only Once. "} {"user":"99","questionId":3088,"creationDate":"2008-08-06T05:29:49Z","answerId":3105,"type":"answer","body":"You could try using Alice. It's a 3D program designed for use in introductory programming classes. The two biggest obstacles for new programmers are often: syntax errors motivation (writing something meaningful and fun rather than contrived) Alice uses a drag and drop interface for constructing programs, avoiding the possibility of syntax errors. Alice lets you construct 3D worlds and have your code control (simple) 3D characters and animation, which is usually a lot more interesting than implementing linked lists. Experienced programmers may look down at Alice as a toy and scoff at dragging and dropping lines of code, but research shows that this approach works. Disclaimer: I worked on Alice. "} {"user":"327","tags":["windows","visual-studio","mono","cross-platform"],"questionId":3106,"creationDate":"2008-08-06T05:36:49Z","title":"How can I create Debian install packages in Windows for a Visual Studio project?","acceptedAnswerId":3119,"type":"question","body":"I'm developing some cross platform software targeting Mono under Visual Studio and would like to be able to build the installers for Windows and Linux (Ubuntu specifically) with a single button click. I figure I could do it by calling cygwin from a post-build event, but I was hoping for at best a Visual Studio plugin or at worst a more Windows-native way of doing it. It seems like the package format is fairly simple and this must be a common need. edit: Re-asked question under other account due to duplicate login issue. "} {"user":"101","questionId":1171,"creationDate":"2008-08-06T05:37:33Z","answerId":3107,"type":"answer","body":"As I understand it, random access is in constant time for both Python's dicts and lists, the difference is that you can only do random access of integer indexes with lists. I'm assuming that you need to lookup a node by its label, so you want a dict of dicts. However, on the performance front, loading it into memory may not be a problem, but if you use too much you'll end up swapping to disk, which will kill the performance of even Python's highly efficient dicts. Try to keep memory usage down as much as possible. Also, RAM is amazingly cheap right now; if you do this kind of thing a lot, there's no reason not to have at least 4GB. If you'd like advice on keeping memory usage down, give some more information about the kind of information you're tracking for each node. "} {"user":"116","questionId":3058,"creationDate":"2008-08-06T05:42:36Z","answerId":3108,"type":"answer","body":"Inversion of Control is what you get when your program callbacks, e.g. like a gui program. For example, in an old school menu, you might have: print \"enter your name\" read name print \"enter your address\" read address etc... store in database thereby controlling the flow of user interaction. In a GUI program or somesuch, instead we say when the user types in field a, store it in NAME when the user types in field b, store it in ADDRESS when the user clicks the save button, call StoreInDatabase So now control is inverted... instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database. Basically, anything with an event loop, callbacks, or execute triggers falls into this category. "} {"user":"116","questionId":3088,"creationDate":"2008-08-06T05:47:05Z","answerId":3109,"type":"answer","body":"A good python course is MIT's A Gentle Introduction to Programming Using Python. It's all free online, and you don't have to be an MIT uberstudent to understand it. Edit [Justin Standard] This course uses this free online book: How To Think Like a Computer Scientist I'm definitely finding it quite useful. "} {"user":"423","questionId":2639,"creationDate":"2008-08-06T05:49:40Z","answerId":3111,"type":"answer","body":"Personally I use MediaWiki for this purpose. I've tried a number of other free and paid wikis (including Confluence) and have always been impressed with MediaWiki's simplicity and ease of use. I have MediaWiki installed on a thumb drive (using XAMPP from PortableApps), which I use mostly as a personal knowledge base/code snippet repository. I can take it with me wherever I go, and view/edit it from any computer I'm using. "} {"user":"219","tags":["perl","arrays","reference","scalar"],"questionId":3112,"creationDate":"2008-08-06T05:56:00Z","title":"Can you force either a scalar or array ref to be an array in Perl?","acceptedAnswerId":3134,"type":"question","body":"I have a perl variable $results that gets returned from a service. The value is supposed to be an array, and $results should be an array reference. However, when the array has only one item in it, $results will be set to that value, and not a referenced array that contains that one item. I want to do a foreach loop on the expected array. Without checking ref($results) eq 'ARRAY', is there any way to have something equivalent to the following: foreach my $result (@$results) { # Process $result } That particular code sample will work for the reference, but will complain for the simple scalar. EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value. "} {"user":"358","questionId":2861,"creationDate":"2008-08-06T05:57:24Z","answerId":3115,"type":"answer","body":"I use Hpricot on Ruby. As an example this is a snippet of code that I use to retrieve all book titles from the six pages of my HireThings account (as they don't seem to provide a single page with this information): pagerange = 1..6 proxy = Net::HTTP::Proxy(proxy, port, user, pwd) proxy.start('www.hirethings.co.nz') do |http| pagerange.each do |page| resp, data = http.get \"/perth_dotnet?page=#{page}\" if resp.class == Net::HTTPOK (Hpricot(data)/\"h3 a\").each { |a| puts a.innerText } end end end It's pretty much complete. All that comes before this are library imports and the settings for my proxy. "} {"user":"100","questionId":3088,"creationDate":"2008-08-06T06:00:28Z","answerId":3117,"type":"answer","body":"I've had to work with several beginner (never wrote a line of code) programmers, and I'll be doing an after school workshop with high school students this fall. This is the closest thing I've got to documentation. It's still a work in progress, but I hope it helps. 1) FizzBuzz. Start with command line programs. You can write some fun games, or tools, very quickly, and you learn all of the language features very quickly without having to learn the GUI tools first. These early apps should be simple enough that you won't need to use any real debugging tools to make them work. If nothing else things like FizzBuzz are good projects. Your first few apps should not have to deal with DBs, file system, configuration, ect. These are concepts which just confuse most people, and when you're just learning the syntax and basic framework features you really don't need more complexity. Some projects: Hello World! Take the year of my birth, and calculate my age (just (now - then) no month corrections). (simple math, input, output) Ask for a direction(Up, down, left, right), then tell the user their fate (fall in a hole, find a cake, ect). (Boolean logic) FizzBuzz, but count once every second. (Loops, timers, and more logic) Depending on their age some really like an app which calls the users a random insult at some interval. (Loops, arrays, timers, and random if you make the interval random) 2) Simple Project Once they have a good grasp of language features, you can start a project(simple, fun games work good.). You should try to have the first project be able to be completed within 6-12 hours. Don't spend time to architect it early. Let them design it even if it sucks. If it falls apart, talk about what happened and why it failed, then pick another topic and start again. This is where you start introducing the debugging capabilities of your tools. Even if you can see the problem by reading the code you should teach them how to use the tools, and then show them how you could see it. That serves the dual purpose of teaching the debugging tools and teaching how to ID errors without tools. Once, or if, the project gets functional you can use it to introduce refactoring tools. Its good if you can then expand the project with some simple features which you never planned for. This usually means refactoring and significant debugging, since very few people write even half decent code their first time. Some projects: Hangman game Experimenting with robotics(Vex and Mindstorms are options) 3) Real Project Start a real project which may take some time. Use proper source control, and make a point to have a schedule. Run this project like a real project, if nothing else its good experience having to deal with the tools. Obviously you need to adjust this for each person. The most important thing I've found is to make even the first simple apps apply to what the person is interested in. Some projects: Tetris Text file based blog engine More advanced robotics work "} {"user":"91","questionId":3106,"creationDate":"2008-08-06T06:06:45Z","answerId":3119,"type":"answer","body":"I am not aware of any plugin that does it natively, especially since Mono users seem to prefer MonoDevelop. However, it should be possible to use Cygwin and a custom MSBuild Task or Batch file in order to achieve that by using the native .deb creation tools. "} {"user":"269","questionId":3088,"creationDate":"2008-08-06T06:07:51Z","answerId":3120,"type":"answer","body":"I used to teach programming and your brother has one main advantage over most of my students he wants to learn :) If you decide to go with C a friend has a site that has the sort of programs those of use from older generations remember as basic type-ins. The more complex of them use ncurses which sort of negates their use as a teaching aid somewhat but some of them are tiny little things and you can learn loads without being taught to. Personally I think Python and Ruby would make great first languages. EDIT: list of beginner programming assignments appeared overnight might be just what you are looking for. "} {"user":"372","questionId":3067,"creationDate":"2008-08-06T06:11:31Z","answerId":3122,"type":"answer","body":"Resharper does this with the Ctrl-N keyword. Unfortunately it doesn't come for free. Visual Studio doesn't have anything like this feature beyond Find. "} {"user":"372","questionId":3088,"creationDate":"2008-08-06T06:20:28Z","answerId":3125,"type":"answer","body":"I think the \"wisdom of crowds\" work here. How did most people learn how to program? Many claim that they did so by copying programs of others, usually games they wanted to play in BASIC. Maybe that route will work with him too? "} {"user":"86","questionId":3112,"creationDate":"2008-08-06T06:22:23Z","answerId":3126,"type":"answer","body":"I've just tested this with: #!/usr/bin/perl -w use strict; sub testit { my @ret = (); if (shift){ push @ret,1; push @ret,2; push @ret,3; }else{ push @ret,\"oneonly\"; } return \\@ret; } foreach my $r (@{testit(1)}){ print $r.\" test1\\n\"; } foreach my $r (@{testit()}){ print $r.\" test2\\n\"; } And it seems to work ok, so I'm thinking it has something to do with the result getting returned from the service? If you have no control over the returning service this might be hard one to crack "} {"user":"232","questionId":805,"creationDate":"2008-08-06T06:27:19Z","answerId":3128,"type":"answer","body":"I used to do that with FTP on windows (create a file of commands and shell out FTP.exe) Xetius I tried to upvote yours and accept your answer too and I received an warning that I needed 25 rep to do that. Sorry. "} {"user":"232","questionId":2780,"creationDate":"2008-08-06T06:39:12Z","answerId":3129,"type":"answer","body":"if you don't need to know this pre-render, you could always use the win32 method of getpixel, I believe. Note: typing on iPhone in the middle of Missouri with no inet access. Will look up real win32 example and see if there is a .net equivalent. In case anyone cares, and doesn't want to use the (excellent) answer posted above, you can get the color value of a pixel in .Net via this link MSDN example "} {"user":"95","questionId":2775,"creationDate":"2008-08-06T06:44:32Z","answerId":3130,"type":"answer","body":"SQL Server 2008 has a new date data type and this simplifies this problem to: SELECT CAST(CAST(GETDATE() AS date) AS datetime) "} {"user":"86","questionId":3112,"creationDate":"2008-08-06T07:13:16Z","answerId":3134,"type":"answer","body":"im not sure there's any other way than: $result = [ $result ] if ref($result) ne 'ARRAY'; foreach ..... "} {"user":"278","questionId":3088,"creationDate":"2008-08-06T07:15:53Z","answerId":3135,"type":"answer","body":"If you want to teach the basics of programming, without being language specific, there is an application called Scratch that was created in MIT. It's designed to help people develop programming skills. As users create Scratch projects, they learn to create conditions, loops, etc. There is a also a community of scratch projects, form which projects can be downloaded - that way you can explore other people's programs and see how they were built. "} {"user":"87","tags":["cron","settings","crontab"],"questionId":3136,"creationDate":"2008-08-06T07:16:16Z","title":"How to setup a crontab to execute at specific time","acceptedAnswerId":3139,"type":"question","body":"How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs? Right now my crontab looks something like this @daily /path/to/script.sh "} {"user":"91","questionId":3136,"creationDate":"2008-08-06T07:21:32Z","answerId":3139,"type":"answer","body":"When you do crontab -e, try this: 59 23 * * * /usr/sbin/myscript > /dev/null That means: At 59 Minutes and 23 Hours on every day (*) on every month on every weekday, execute myscript. See man crontab for some more info and examples. "} {"user":"373","questionId":3058,"creationDate":"2008-08-06T07:22:09Z","answerId":3140,"type":"answer","body":"The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code. For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this: public class TextEditor { private SpellChecker checker; public TextEditor() { this.checker = new SpellChecker(); } } What we've done here creates a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this: public class TextEditor { private IocSpellChecker checker; public TextEditor(IocSpellChecker checker) { this.checker = checker; } } In the first code example we are instantiating SpellChecker (this.checker = new SpellChecker();), which means the TextEditor class directly depends on the SpellChecker class. In the second code example we are creating an abstraction by having the the SpellChecker dependency class in TextEditor constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so: SpellChecker sc = new SpellChecker; // dependency TextEditor textEditor = new TextEditor(sc); Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We're injecting the the dependency to the TextEditor signature. This is just a simple example, there's a good series of articles by Simone Busoli that explains it in greater detail. "} {"user":"253","tags":["mono","nant","teamcity","mbunit"],"questionId":3143,"creationDate":"2008-08-06T07:41:11Z","title":"Using MBUnit in TeamCity","acceptedAnswerId":880219,"type":"question","body":"I'm compiling a NAnt project on linux with TeamCity Continuous Integration server. I have been able to generate a test report by running NAnt on mono thru a Command Line Runner but don't have the options of using the report like a NAnt Runner. I'm also using MBUnit for the testing framework. How can I merge in the test report and display \"Tests failed: 1 (1 new), passed: 3049\" for the build? Update: take a look at MBUnitTask its a NAnt task that uses sends messages that TeamCity expects from NUnit so it lets you use all of TeamCity's features for tests. MBUnitTask Update: Galio has better support so you just have to reference the Galio MBUnit 3.5 dlls instead of the MBUnit 3.5 dlls and switch to the galio runner to make it work. "} {"user":"475","tags":["vb.net","diff"],"questionId":3144,"creationDate":"2008-08-06T07:42:33Z","title":"'Best' Diff Algorithm","acceptedAnswerId":3146,"type":"question","body":"I need to implement a Diff algorithm in VB.NET to find the changes between two different versions of a piece of text. I've had a scout around the web and have found a couple of different algorithms. Does anybody here know of a 'best' algorithm that I could implement? "} {"user":"86","questionId":3136,"creationDate":"2008-08-06T07:43:29Z","answerId":3145,"type":"answer","body":"You will with the above response receive email with any text written to stderr. Some people redirect that away too, and make sure that the script writes a log instead. ... 2>&1 .... "} {"user":"445","questionId":3144,"creationDate":"2008-08-06T07:49:32Z","answerId":3146,"type":"answer","body":"Well I've used the c# version on codeproject and its really good for what I wanted... http://www.codeproject.com/KB/recipes/diffengine.aspx You can probably get this translated into VB.net via an online converter if you can't do it yourself... "} {"user":"380","tags":[".net"],"questionId":3147,"creationDate":"2008-08-06T07:52:31Z","title":"What are the best practices for using Extension Methods in .Net?","acceptedAnswerId":15075,"type":"question","body":"I have seen these being used every which way, and have been accused of using them the wrong way (though in that case, I was using them that way to demonstrate a point). So, what do you think are the best practices for employing Extension Methods? Should development teams create a library of extension methods and deploy them across various projects? Should there be a collection of common extension methods in the form of an open source project? Update: have decided to create an organization wide extension methods library "} {"user":"391","questionId":3144,"creationDate":"2008-08-06T07:52:42Z","answerId":3149,"type":"answer","body":"I don't know for sure if it's the best diff algorithms but you might want to check out those links that talks about SOCT4 and SOCT6 http://dev.libresource.org/home/doc/so6-user-manual/concepts and also: http://www.loria.fr/~molli/pmwiki/uploads/Main/so6group03.pdf http://www.loria.fr/~molli/pmwiki/uploads/Main/diffalgo.pdf "} {"user":"370","tags":["c++","visual-studio","unit-testing","testing"],"questionId":3150,"creationDate":"2008-08-06T07:57:50Z","title":"How to set up unit testing for Visual Studio C++","acceptedAnswerId":35963,"type":"question","body":"I'm having trouble figuring out how to get the testing framework set up and usable in Visual Studio 2008 for C++ presumably with the built-in unit testing suite. Any links or tutorials would be appreciated. "} {"user":"341","questionId":3144,"creationDate":"2008-08-06T07:58:13Z","answerId":3151,"type":"answer","body":"I like An O(ND) Difference Algorithm and Its Variations by Eugene Myers. I believe it's the algorithm that was used in GNU diff. For a good background see Wikipedia. This is quite theoretical and you might wish to find source code, but I'm not aware of any in VB. "} {"user":"51","questionId":3147,"creationDate":"2008-08-06T08:02:10Z","answerId":3152,"type":"answer","body":"I think that it depends on what purpose the Extension methods serve. Extension methods that relate to specific business needs of a project (whether they are connected to basic data types or custom objects) should not be included in a library that would be distributed across multiple projects. Extension methods that relate to basic data types (int, string, etc) or generics that have a wider application could be packaged and distributed across projects. Take care not to globally include Extension methods that have little application, as they just clog up intellisense and can lead to confusion and/or misuse. "} {"user":"95","questionId":2775,"creationDate":"2008-08-06T08:06:19Z","answerId":3154,"type":"answer","body":"Itzik Ben-Gan in DATETIME Calculations, Part 1 (SQL Server Magazine, February 2007) shows three methods of performing such a conversion (slowest to fastest; the difference between second and third method is small): SELECT CAST(CONVERT(char(8), GETDATE(), 112) AS datetime) SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) SELECT CAST(CAST(GETDATE() - 0.50000004 AS int) AS datetime) Your technique (casting to float) is suggested by a reader in the April issue of the magazine. According to him, it has performance comparable to that of second technique presented above. "} {"user":"192","questionId":3147,"creationDate":"2008-08-06T08:08:20Z","answerId":3155,"type":"answer","body":"I've been including my extension methods in with my Core libraries in the Utils class because people who are working with my framework are likely to find the methods useful, but for mass deployment where the end developer might have a choice of extension method libraries, I would advise putting all of your extensions into their own namespace, even their own project file, so that people can choose to add a reference or a using statement or simply where required, like so: Core.Extensions.Base64Encode(str); My Utils class is my bestest friend in the whole world, it was before extension methods came along and they have only helped to strengthen our relationship. The biggest rule I would go by is to give people choice over what extension framework they are using where possible. "} {"user":"476","tags":["apache",".htaccess","mod-rewrite"],"questionId":3157,"creationDate":"2008-08-06T08:15:28Z","title":".htaccess directives to *not* redirect certain URLs","acceptedAnswerId":4449,"type":"question","body":"In an application that heavily relies on .htaccess RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is: /appRoot/.htaccess app/ static/ By default every request to /appRoot/* is being rewritten to be picked up by app/webroot/index.php, where it's being analysed and corresponding controller actions are being invoked. This is done by these directives in .htaccess: RewriteBase /appRoot RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] I now want to exclude a few directories like static/ from this rewriting. I tried with this before the Cake RewriteRules: RewriteCond $1 ^(static|otherDir).*$ [NC] RewriteRule (.*) - [L] It works in so far that requests are no longer rewritten, but now all requests are being skipped, even legitimate Cake requests which should not match ^(static|otherDir).*$. I tried several variations of these rules but can't get it to work the way I want. "} {"user":"39","questionId":3067,"creationDate":"2008-08-06T08:15:53Z","answerId":3158,"type":"answer","body":"If you are looking for an add-in like this to quickly navigate to source files in your project: try the Visual Studio 2005/2008 add-in SonicFileFinder. "} {"user":"383","questionId":3157,"creationDate":"2008-08-06T08:19:29Z","answerId":3159,"type":"answer","body":"Remove the [L] from the previous rules: RewriteBase /appRoot RewriteRule ^$ app/webroot/     RewriteRule (.*) app/webroot/$1 [L] means \"Stop the rewriting process here and don't apply any more rewriting rules.\" "} {"user":"265","questionId":3157,"creationDate":"2008-08-06T08:26:56Z","answerId":3161,"type":"answer","body":"Could you not apply the condition to the following rules, but with negation, as in (with some variation thereof, I'm not too good at remembering .htaccess rules, so the flags might be wrong): RewriteCond $1 !^(static|otherDir).*$ [NC] RewriteRule ^$ app/webroot/ [L] RewriteCond $1 !^(static|otherDir).*$ [NC] RewriteRule ^$ app/webroot/$1 [L] "} {"user":"342","questionId":3150,"creationDate":"2008-08-06T08:28:14Z","answerId":3162,"type":"answer","body":"I use UnitTest++. In the years since I made this post the source has moved from SourceForge to github. Also the example tutorial is now more agnostic - doesn't go into any configuration or project set up at all. I doubt it will still work for Visual Studio 6 as the project files are now created via CMake. If you still need the older version support you can get the last available version under the SourceForge branch. "} {"user":"22","tags":["flex","actionscript-3"],"questionId":3163,"creationDate":"2008-08-06T08:33:53Z","title":"Actionscript 3 - Fastest way to parse yyyy-mm-dd hh:mm:ss to a Date object?","acceptedAnswerId":10030,"type":"question","body":"I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings. Does anyone know any faster ways of doing this or tips to speed up the methods? castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms Code: private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 && month == 0 && day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year, month, day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year, month, day, hour, minute, second); } - private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf(\"0000-00-00\") != -1 ) { return null; } dateString = dateString.split(\"-\").join(\"/\"); return new Date(Date.parse( dateString )); } - private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(\" \"); var dateParts:Array = mainParts[0].split(\"-\"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join(\"/\")+(mainParts[1]?\" \"+mainParts[1]:\" \") ) ); } No, Date.parse will not handle dashes by default. And I need to return null for date time strings like \"0000-00-00\". "} {"user":"192","tags":["asp.net","path","mappath"],"questionId":3164,"creationDate":"2008-08-06T08:34:13Z","title":"Absolute path back to web-relative path","acceptedAnswerId":3218,"type":"question","body":"If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the fastest way to convert that absolute path back into a relative web path? "} {"user":"51","questionId":3164,"creationDate":"2008-08-06T08:44:34Z","answerId":3178,"type":"answer","body":"If you used Server.MapPath, then you should already have the relative web path. According to the MSDN documentation, this method takes one variable, path, which is the virtual path of the Web server. So if you were able to call the method, you should already have the relative web path immediately accessible. "} {"user":"479","tags":["fogbugz"],"questionId":3180,"creationDate":"2008-08-06T08:47:45Z","title":"Anyone soloing using fogbugz?","acceptedAnswerId":3188,"type":"question","body":"Is there anyone working solo and using fogbugz out there? I'm interested in personal experience/overhead versus paper. I am involved in several projects and get pretty hammered with lots of details to keep track of... Any experience welcome. (Yes I know Mr. Joel is on the stackoverflow team... I still want good answers :) "} {"user":"383","questionId":3163,"creationDate":"2008-08-06T08:50:13Z","answerId":3185,"type":"answer","body":"I'm guessing Date.Parse() doesn't work? "} {"user":"91","questionId":3180,"creationDate":"2008-08-06T08:52:51Z","answerId":3188,"type":"answer","body":"I use it, especially since the hosted Version of FugBugz is free for up to 2 people. I found it a lot nicer than paper as I'm working on multiple projects, and my paper tends to get rather messy once you start making annotations or if you want to re-organize and shuffle tasks around, mark them as complete only to see that they are not complete after all... Plus, the Visual Studio integration is really neat, something paper just cannot compete with. Also, if you lay the project to rest for 6 months and come back, all your tasks and notes are still there, whereas with paper you may need to search all the old documents and notes again, if you did not discard it. But that is just the point of view from someone who is not really good at staying organized :-) If you are a really tidy and organized person, paper may work better for you than it does for me. Bonus suggestion: Run Fogbugz on a second PC (or a small Laptop like the eeePC) so that you always have it at your fingertips. The main problem with Task tracking programs - be it FogBugz, Outlook, Excel or just notepad - is that they take up screen space, and my two monitors are usually full with Visual Studio, e-Mail, Web Browsers, some Notepads etc. "} {"user":"383","questionId":3163,"creationDate":"2008-08-06T09:00:31Z","answerId":3194,"type":"answer","body":"Well then method 2 seems the best way: private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf(\"0000-00-00\") != -1 ) { return null; } dateString = dateString.split(\"-\").join(\"/\"); return new Date(Date.parse( dateString )); } "} {"user":"230","tags":["sql"],"questionId":3196,"creationDate":"2008-08-06T09:00:58Z","title":"SQL query, count and group by","acceptedAnswerId":3197,"type":"question","body":"If I have data like this: +---+----+ |Key|Name| +---+----+ |1 |Dan | +---+----+ |2 |Tom | +---+----+ |3 |Jon | +---+----+ |4 |Tom | +---+----+ |5 |Sam | +---+----+ |6 |Dan | +---+----+ What is the SQL query to bring back the records where Name is repeated 2 or more times? So the result I would want is +---+ |Tom| +---+ |Dan| +---+ "} {"user":"383","questionId":3196,"creationDate":"2008-08-06T09:02:36Z","answerId":3197,"type":"answer","body":"Couldn't be simpler... Select Name, Count(Name) As Count From Table Group By Name Having Count(Name) > 1 Order By Count(Name) Desc This could also be extended to delete duplicates: Delete From Table Where Key In ( Select Max(Key) From Table Group By Name Having Count(Name) > 1) "} {"user":"1384652","questionId":3088,"creationDate":"2008-08-06T09:02:39Z","answerId":3198,"type":"answer","body":"I recently wrote an article titled How to teach your girlfriend programming, it has little to do with girlfriends and everything about teaching something technical to someone that does not understand it. I'm told it's also funny. "} {"user":"143","questionId":2384,"creationDate":"2008-08-06T09:03:28Z","answerId":3200,"type":"answer","body":"I had no luck using the BinaryFormatter, I guess I have to have a complete struct that matches the content of the file exactly. I realised that in the end I wasn't interested in very much of the file content anyway so I went with the solution of reading part of stream into a bytebuffer and then converting it using Encoding.ASCII.GetString() for strings and BitConverter.ToInt32() for the integers. I will need to be able to parse more of the file later on but for this version I got away with just a couple of lines of code. "} {"user":"484","questionId":2898,"creationDate":"2008-08-06T09:08:45Z","answerId":3203,"type":"answer","body":"The best I've found is gedit unfortunately. Spend a few hours with it and you'll discover it's not so bad, with plugins and themes. You can use the command line to open documents in it. "} {"user":"482","questionId":3027,"creationDate":"2008-08-06T09:09:22Z","answerId":3204,"type":"answer","body":"Try akismet from wp guys "} {"user":"482","questionId":2898,"creationDate":"2008-08-06T09:12:03Z","answerId":3205,"type":"answer","body":"I use SciTE very small and simple text editor. "} {"user":"383","questionId":3027,"creationDate":"2008-08-06T09:14:18Z","answerId":3207,"type":"answer","body":"I think asking the user simple questions like: \"How many legs does a dog have?\" Would be much more effective that any CAPTCHA systems out there at the moment. Not only is it very difficult for the computer to answer that question, but it is very easy for a human to answer! "} {"user":"Kibitzer","questionId":2898,"creationDate":"2008-08-06T09:17:08Z","answerId":3211,"type":"answer","body":"+1 for pico/nano -- lightweight, gets the job done, good help "} {"user":"383","tags":["c#","integer"],"questionId":3213,"creationDate":"2008-08-06T09:21:09Z","title":"Convert integers to written numbers","acceptedAnswerId":3267,"type":"question","body":"Is there an efficient method of converting an integer into the written numbers, for example: string Written = IntegerToWritten(21); would return \"Twenty One\". Is there any way of doing this that doesn't involve a massive look-up table? "} {"user":"275","questionId":3213,"creationDate":"2008-08-06T09:22:35Z","answerId":3215,"type":"answer","body":"why massive lookup table? string GetWrittenInteger(int n) { string[] a = new string[] {\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\" } string[] b = new string[] { \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\" } string[] c = new string[] {\"Twenty\", \"Thirty\", \"Forty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"}; string[] d = new string[] {\"Hundred\", \"Thousand\", \"Million\"} string s = n.ToString(); for (int i = 0; i < s.Length; i++) { // logic (too lazy but you get the idea) } } "} {"user":"445","questionId":3213,"creationDate":"2008-08-06T09:26:04Z","answerId":3216,"type":"answer","body":"Justin Rogers has a \"NumbersToEnglish\" class which should do the job for you nicely! Initial posting. http://weblogs.asp.net/justin_rogers/archive/2004/06/09/151675.aspx Finalized Source Code http://weblogs.asp.net/justin_rogers/articles/151757.aspx It does have a bit of an internal lookup table but I don't really know how you are going to be able to get away from that. "} {"user":"486","questionId":2898,"creationDate":"2008-08-06T09:26:16Z","answerId":3217,"type":"answer","body":"Kate, the KDE Advanced Text Editor is quite good. It has syntax highlighting, block selection mode, terminal/console, sessions, window splitting both horizontal and vertical etc. "} {"user":"383","questionId":3164,"creationDate":"2008-08-06T09:28:50Z","answerId":3218,"type":"answer","body":"Perhaps this might work: String RelativePath = AbsolutePath.Replace(Request.ServerVariables[\"APPL_PHYSICAL_PATH\"], String.Empty); (i'm using c# but could be adapted to vb) (@Tags2k: I have editted the above answer) "} {"user":"483","questionId":1625,"creationDate":"2008-08-06T09:30:50Z","answerId":3220,"type":"answer","body":"For Windows, I found Microsoft's own free XML Notepad 2007 to be a great simple to use editor with a nice selection of features. Used it for both reviewing my XML output when developing and editing broken iTunes' libraries. ;) Requires .net 2.0 "} {"user":"377","questionId":1625,"creationDate":"2008-08-06T09:33:16Z","answerId":3221,"type":"answer","body":"Altova's XML Spy is a great editor, but not necesarily the cheapest option out there. "} {"user":"486","tags":["javascript","css","http","caching"],"questionId":3224,"creationDate":"2008-08-06T09:38:15Z","title":"How can I make the browser see CSS and Javascript changes?","acceptedAnswerId":3225,"type":"question","body":"CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion. Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. Could use the SVN revision number to automate this for you: ASP.NET Display SVN Revision Number Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file. In the Subversion book it says about Revision: \"This keyword describes the last known revision in which this file changed in the repository\". Firefox also allows pressing CTRL+R to reload everything on a particular page. To clarify I am looking for solutions that don't require the user to do anything on their part. "} {"user":"486","questionId":3224,"creationDate":"2008-08-06T09:41:02Z","answerId":3225,"type":"answer","body":"I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP: function urlmtime($url) { $parsed_url = parse_url($url); $path = $parsed_url['path']; if ($path[0] == \"/\") { $filename = $_SERVER['DOCUMENT_ROOT'] . \"/\" . $path; } else { $filename = $path; } if (!file_exists($filename)) { // If not a file then use the current time $lastModified = date('YmdHis'); } else { $lastModified = date('YmdHis', filemtime($filename)); } if (strpos($url, '?') === false) { $url .= '?ts=' . $lastModified; } else { $url .= '&ts=' . $lastModified; } return $url; } function include_css($css_url, $media='all') { // According to Yahoo, using link allows for progressive // rendering in IE where as @import url($css_url) does not echo ''.\"\\n\"; } function include_javascript($javascript_url) { echo ''.\"\\n\"; } "} {"user":"487","questionId":3213,"creationDate":"2008-08-06T09:46:18Z","answerId":3228,"type":"answer","body":"I use this code.It is VB code but you can easily translate it to C#. It works Function NumberToText(ByVal n As Integer) As String Select Case n Case 0 Return \"\" Case 1 To 19 Dim arr() As String = {\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\", _ \"Eight\",\"Nine\",\"Ten\",\"Eleven\",\"Twelve\",\"Thirteen\",\"Fourteen\", _ \"Fifteen\",\"Sixteen\",\"Seventeen\",\"Eighteen\",\"Nineteen\"} Return arr(n-1) & \" \" Case 20 to 99 Dim arr() as String = {\"Twenty\",\"Thirty\",\"Forty\",\"Fifty\",\"Sixty\",\"Seventy\",\"Eighty\",\"Ninety\"} Return arr(n\\10 -2) & \" \" & NumberToText(n Mod 10) Case 100 to 199 Return \"One Hundred \" & NumberToText(n Mod 100) Case 200 to 999 Return NumberToText(n\\100) & \"Hundreds \" & NumberToText(n mod 100) Case 1000 to 1999 Return \"One Thousand \" & NumberToText(n Mod 1000) Case 2000 to 999999 Return NumberToText(n\\1000) & \"Thousands \" & NumberToText(n Mod 1000) Case 1000000 to 1999999 Return \"One Million \" & NumberToText(n Mod 1000000) Case 1000000 to 999999999 Return NumberToText(n\\1000000) & \"Millions \" & NumberToText(n Mod 1000000) Case 1000000000 to 1999999999 Return \"One Billion \" & NumberTotext(n Mod 1000000000) Case Else Return NumberToText(n\\1000000000) & \"Billion \" _ & NumberToText(n mod 1000000000) End Select End Function Here is the code in c# public static string AmountInWords(double amount) { var n = (int)amount; if (n == 0) return \"\"; else if (n > 0 && n <= 19) { var arr = new string[] { \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\" }; return arr[n - 1] + \" \"; } else if (n >= 20 && n <= 99) { var arr = new string[] { \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\" }; return arr[n / 10 - 2] + \" \" + AmountInWords(n % 10); } else if (n >= 100 && n <= 199) { return \"One Hundred \" + AmountInWords(n % 100); } else if (n >= 200 && n <= 999) { return AmountInWords(n / 100) + \"Hundred \" + AmountInWords(n % 100); } else if (n >= 1000 && n <= 1999) { return \"One Thousand \" + AmountInWords(n % 1000); } else if (n >= 2000 && n <= 999999) { return AmountInWords(n / 1000) + \"Thousand \" + AmountInWords(n % 1000); } else if (n >= 1000000 && n <= 1999999) { return \"One Million \" + AmountInWords(n % 1000000); } else if (n >= 1000000 && n <= 999999999) { return AmountInWords(n / 1000000) + \"Million \" + AmountInWords(n % 1000000); } else if (n >= 1000000000 && n <= 1999999999) { return \"One Billion \" + AmountInWords(n % 1000000000); } else { return AmountInWords(n / 1000000000) + \"Billion \" + AmountInWords(n % 1000000000); } } "} {"user":"370","tags":["c++","visual-studio"],"questionId":3230,"creationDate":"2008-08-06T09:49:27Z","title":"How do you pack a visual studio c++ project for release?","acceptedAnswerId":10141,"type":"question","body":"I'm wondering how to make a release build that includes all necessary dll files into the .exe so the program can be run on a non-development machine without it having to install the microsoft redistributable on the target machine. Without doing this you get the error message that the application configuration is not correct and to reinstall. "} {"user":"381","tags":["c++","c","midi","signal-processing"],"questionId":3231,"creationDate":"2008-08-06T09:51:06Z","title":"C/C++ library for reading MIDI signals from a USB MIDI device","acceptedAnswerId":842632,"type":"question","body":"I want to write C/C++ programs that take input from a MIDI device. The MIDI device connects to my PC using a USB connector. I'm looking for a (C/C++ implemented) library that I can use to read the MIDI signals from the MIDI device through the USB port. I'm happy manipulating the MIDI data once I get it, I just don't want to have to implement the code for its capture. I'm planning on writing my code using the Bloodshed Dev-C++ IDE on Windows XP. "} {"user":"383","questionId":3224,"creationDate":"2008-08-06T09:52:01Z","answerId":3233,"type":"answer","body":"Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.