source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
56,313
ReSharper Code cleanup feature (with " reorder members " and " reformat code " enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template. Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc. ? Is there a chance that it causes many undesired conflicts ? Thank you.
Yes, it will definitely cause problems. In addition to creating conflicts that have to be manually resolved, when you check in a file that has been reformatted, the VCS will note almost every line as having been changed. This will make it hard for you or a teammate to look back at the history and see what changed when. That said, if everyone autoformats their code the same way (ie, you distribute that XML template to the team), then it might work well. The problems really only come in when not everyone is doing the same thing.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ] }
56,315
Is anyone out there using D for real world applications? If so, what are you using it for? I can't seem to find anything big on the web written in D. Despite the lack of known big users, D seems like a very promissing language to me, and according to TIOBE , it's fairly popular.
I'm using D for my research work in the area of computer graphics. I and others have had papers published in our fields based on work done using D. I think it's definitely ready for use on small to medium sized research projects where performance matters. It's a nice fit for research work because often you're starting from scratch anyway, so you don't have much legacy code to worry about integrating with. Another popular area for use seems to be web services. Hopefully someone else can comment who's in this space, but there too I think the idea is that performance often really matters so you want a compiled-to-the-metal language. Services are often fairly small, self-contained processes, so interop with large amounts of legacy C++ code is not really necessary or useful. Thus D can get its foot in the door. I think D will continue to gain grass-roots followers in this way -- on smaller projects that for whatever reason can afford to ditch the C++ legacy in order to gain a programming language that's much more enjoyable to use, and perhaps more productive too. But until there's a huge number of grass-roots users there won't be much in the way of big corporate users I suspect.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/56315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018/" ] }
56,347
I'm returning to c++ after being away for a bit and trying to dust off the old melon. In Java Iterator is an interface to a container having methods: hasNext() , next() and remove() . The presence of hasNext() means it has the concept of a limit for the container being traversed. //with an IteratorIterator<String> iter = trees.iterator();while (iter.hasNext()) { System.out.println(iter.next());} In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end. vector<int> vec;vector<int>::iterator iter;// Add some elements to vectorv.push_back(1);v.push_back(4);v.push_back(8);for (iter= v.begin(); iter != v.end(); iter++){ cout << *i << " "; //Should output 1 4 8} The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it. It there any further subtlety to this that I am missing?
Yes, there is a large conceptual difference. C++ utilizes different "classes" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, transform ). See the iterators concept in the C++ Documentation : Input Iterator Output Iterator Forward Iterator Bidirectional Iterator Random Access Iterator These are far more interesting and powerful compared to Java/C#'s puny iterators. Hopefully these conventions will be codified using C++0x's Concepts .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ] }
56,362
I'm starting to learn ruby. I'm also a day-to-day C++ dev.For C++ projects I usually go with following dir structure / -/bin <- built binaries -/build <- build time temporary object (eg. .obj, cmake intermediates) -/doc <- manuals and/or Doxygen docs -/src --/module-1 --/module-2 -- non module specific sources, like main.cpp - IDE project files (.sln), etc. What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable?
Bundler includes the necessary infrastructure to generate a gem: $ bundle gem --coc --mit --test=minitest --exe spiderCreating gem 'spider'...MIT License enabled in configCode of conduct enabled in config create spider/Gemfile create spider/lib/spider.rb create spider/lib/spider/version.rb create spider/spider.gemspec create spider/Rakefile create spider/README.md create spider/bin/console create spider/bin/setup create spider/.gitignore create spider/.travis.yml create spider/test/test_helper.rb create spider/test/spider_test.rb create spider/LICENSE.txt create spider/CODE_OF_CONDUCT.md create spider/exe/spiderInitializing git repo in /Users/francois/Projects/spiderGem 'spider' was successfully created. For more information on making a RubyGem visit https://bundler.io/guides/creating_gem.html Then, in lib/, you create modules as needed: lib/ spider/ base.rb crawler/ base.rb spider.rb require "spider/base" require "crawler/base" Read the manual page for bundle gem for details on the --coc , --exe and --mit options.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5731/" ] }
56,375
Put differently: Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility? As far as I understand, generic collections not only are type-safe, but their performance is better. Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0 .
The non-generic collections are so obsolete that they've been removed from the CoreCLR used in Silverlight and Live Mesh.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1670/" ] }
56,391
Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available. The problem is that I have no idea about what have to be done on the server side. I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ? Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ? @ pilif : thanks for your detailed answer. There is still something which is unclear for me : like http://www.example.com/update?version=1.2.4 Then you can return what ever you want, probably also the download-URL of the installer of the new version. How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the ?version=1.2.4 part in order to return something accordingly ?
I would absolutely recommend to just do a plain HTTP request to your website. Everything else is bound to fail. I'd make a HTTP GET request to a certain page on your site containing the version of the local application. like http://www.example.com/update?version=1.2.4 Then you can return what ever you want, probably also the download-URL of the installer of the new version. Why not just put a static file with the latest version to the server and let the client decide? Because you may want (or need) to have control over the process. Maybe 1.2 won't be compatible with the server in the future, so you want the server to force the update to 1.3, but the update from 1.2.4 to 1.2.6 could be uncritical, so you might want to present the client with an optional update. Or you want to have a breakdown over the installed base. Or whatever. Usually, I've learned it's best to keep as much intelligence on the server, because the server is what you have ultimate control over. Speaking here with a bit of experience in the field, here's a small preview of what can (and will - trust me) go wrong: Your Application will be prevented from making HTTP-Requests by the various Personal Firewall applications out there. A considerable percentage of users won't have the needed permissions to actually get the update process going. Even if your users have allowed the old version past their personal firewall, said tool will complain because the .EXE has changed and will recommend the user not to allow the new exe to connect (users usually comply with the wishes of their security tool here). In managed environments, you'll be shot and hanged (not necessarily in that order) for loading executable content from the web and then actually executing it. So to keep the damage as low as possible, fail silently when you can't connect to the update server before updating, make sure that you have write-permission to the install directory and warn the user if you do not, or just don't update at all. Provide a way for administrators to turn the auto-update off. It's no fun to do what you are about to do - especially when you deal with non technically inclined users as I had to numerous times.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2796/" ] }
56,402
I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments. For horizontal alignment I can use text-anchor with left , middle or right . I can't find a equivalent for vertical alignment; alignment-baseline doesn't seem to do it, so at present I'm using dy="0.5ex" as a kludge for centre alignment. Is there a proper manner for aligning with the vertical centre or top of the text?
It turns out that you don't need explicit text paths. Firefox 3 has only partial support of the vertical alignment tags ( see this thread ). It also seems that dominant-baseline only works when applied as a style whereas text-anchor can be part of the style or a tag attribute. <path d="M10, 20 L17, 20" style="fill:none; color:black; stroke:black; stroke-width:1.00"/><text fill="black" font-family="sans-serif" font-size="16" x="27" y="20" style="dominant-baseline: central;"> Vertical</text><path d="M60, 40 L60, 47" style="fill:none; color:red; stroke:red; stroke-width:1.00"/><text fill="red" font-family="sans-serif" font-size="16" x="60" y="70" style="text-anchor: middle;"> Horizontal</text><path d="M60, 90 L60, 97" style="fill:none; color:blue; stroke:blue; stroke-width:1.00"/><text fill="blue" font-family="sans-serif" font-size="16" x="60" y="97" style="text-anchor: middle; dominant-baseline: hanging;"> Bit of Both</text> This works in Firefox. Unfortunately Inkscape doesn't seem to handle dominant-baseline (or at least not in the same way).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/56402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5764/" ] }
56,411
First off, this question is ripped out from this question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me. Assume that you have a algorithm that generates randomness. Now how do you test it?Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm? To add some theory to the problem -A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!. What is the chance that you, after shuffling, will get A, K, Q, J ... of each suit in a sequence? Answer 1 / 52! So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more... How would you black box test a shuffling algorithm for randomness?
Statistics. The de facto standard for testing RNGs is the Diehard suite (originally available at http://stat.fsu.edu/pub/diehard ). Alternatively, the Ent program provides tests that are simpler to interpret but less comprehensive. As for shuffling algorithms, use a well-known algorithm such as Fisher-Yates (a.k.a "Knuth Shuffle"). The shuffle will be uniformly random so long as the underlying RNG is uniformly random. If you are using Java, this algorithm is available in the standard library (see Collections.shuffle ). It probably doesn't matter for most applications, but be aware that most RNGs do not provide sufficient degrees of freedom to produce every possible permutation of a 52-card deck (explained here ).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4165/" ] }
56,417
We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects? Thanks for your time!
I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply. Dabo is indeed well-known in the Python community. I have presented it at 3 of the last 4 US PyCons, and we have several hundred users who subscribe to our email lists. Our website ( http://dabodev.com ) has not had any service interruptions; I don't know why the first responder claimed to have trouble. Support is through our email lists, and we pride ourselves on helping people quickly and efficiently. Many of the newbie questions help us to identify places where our docs are lacking, so we strongly encourage newcomers to ask questions! Dabo has been around for 4 years. The fact that it is still a few days away from a 0.9 release is more of a reflection of the rather conservative version numbering of my partner, Paul McNett, than any instabilities in the framework. I know of Dabo apps that have been in production since 2006; I have used it for my own projects since 2004. Whatever importance you attach to release numbers, we are at revision 4522, with consistent work being done to add more and more stuff to the framework; refactor and streamline some of the older code, and yes, clean up some bugs. Please sign up for our free email support list: http://leafe.com/mailman/listinfo/dabo-users ...and ask any questions you may have about Dabo there. Not many people have discovered Stack Overflow yet, so I wouldn't expect very informed answers here yet. There are several regular contributors there who use Dabo on a daily basis, and are usually more than happy to offer their opinions and their help.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3497/" ] }
56,443
I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and .NET 2.0. Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working.
I do not know if that would work with a DataGridView column but it works with ComboBoxes: comboBox1.DataSource = Enum.GetValues(typeof(MyEnum)); and: MyEnum value = (MyEnum)comboBox1.SelectedValue; UPDATE: It works with DataGridView columns too, just remember to set the value type. DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();col.Name = "My Enum Column";col.DataSource = Enum.GetValues(typeof(MyEnum));col.ValueType = typeof(MyEnum);dataGridView1.Columns.Add(col);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4660/" ] }
56,518
In C# are the nullable primitive types (i.e. bool? ) just aliases for their corresponding Nullable<T> type or is there a difference between the two?
If you look at the IL using Ildasm , you'll find that they both compile down to Nullable<bool> .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/56518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93/" ] }
56,547
How do you perform a CROSS JOIN with LINQ to SQL?
A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it. var combo = from p in people from c in cars select new { p.Name, c.Make, c.Model, c.Colour };
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/56547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556/" ] }
56,553
I use a MacBook, but I've got a usual keyboard attached to it. The problem is that the keys don't exactly map 1-to-1. One thing is the APPLE and ALT keys. They map to WIN and ALT, but they are usually physically inverted, so if you want to use them with the same layout you have to invert them in the OS.The Function keys work differently too. Fx on the external = Fn + Fx on the MacBook keyboard. And then there are all the insert, delete, keys. So, the question is, how do you come around this? Now I remap all the things I want at the System Preferences panel, but when I unplug the external keyboard it's all messed up. Is there a way to remap keys only for the external one? Some model of keyboard can store it's own mappings without needing the OS? Am I the only one who is bothered by this? (I would like to avoid buying an external mac keyboard, because I wanted to try one of the ergonomic models, and as far as I know, there are no mac ergonomic models) Update:Thanks for the responses, I fixed this. To set the control keys for different keyboards, you have to go to System Preferences/Modifier Keys, then the drop down menu Select Keyboard allows you to choose one particular keyboard and set these keys. Works after unpluging/pluging it seems The suggestion from @Matthew Schinckel seems to work for the rest of the issues (function keys, ...). I didn't try it yet, as the commands keys were my biggest gripe.
In OS X 10.5 they allow you to have different keyboard setups for different keyboards. This works most of the time. I've had issues with very old keyboards that are plugged in via a PS2 to USB but otherwise it works fine.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3785/" ] }
56,554
Let's say I want to represent \q (or any other particular "backslash-escaped character"). That is, I want to match \q but not \\q , since the latter is a backslash-escaped backslash followed by a q . Yet \\\q would match, since it's a backslash-escaped backslash followed by a backslash-escaped q . (Well, it would match the \q at the end, not the \\ at the beginning.) I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.
Updated:My new and improved Perl regex, supporting more than 3 backslashes: /(?<!\\) # Not preceded by a single backslash (?>\\\\)* # an even number of backslashes \\q # Followed by a \q /x; or if your regex library doesn't support extended syntax. /(?<!\\)(?>\\\\)*\\q/ Output of my test program: q does not match\q does match\\q does not match\\\q does match\\\\q does not match\\\\\q does match Older version /(?:(?<!\\)|(?<=\\\\))\\q/
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ] }
56,561
What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to<> templated functions on Google, but it appears that this feature never made the cut for Visual Studio 2005 (and isn't in Visual Studio 2008 either, AFAIK). I have also seen some code on Stan Lippman's blog , but it's from 2004. I have also seen Marshal::StringToHGlobalAnsi(). Is there a method that is considered "best practice"?
System::String has a constructor that takes a char*: using namespace system; const char* charstr = "Hello, world!"; String^ clistr = gcnew String(charstr); Console::WriteLine(clistr); Getting a char* back is a bit harder, but not too bad: IntPtr p = Marshal::StringToHGlobalAnsi(clistr); char *pNewCharStr = static_cast<char*>(p.ToPointer()); cout << pNewCharStr << endl; Marshal::FreeHGlobal(p);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ] }
56,574
A while back I was reading the W3C article on ' Re-using Strings in Scripted Content ', which contains some useful advice on internationalisation, but which strikes me as at odds iwth the DRY (Don't Repeat Yourself) principle of eliminating repetitive code. To take their example, we might have some code like this... print "The printer is ";if (printer.working) { print "on.\n";} else { print "off.\n";}print "The stapler is ";if (stapler.working) { print "on.\n";} else { print "off.\n";} My instinct would be to eliminate the repetition roughly as follows... report-state(printer, "printer");report-state(stapler, "stapler");function report-state(name, object) { print "The "+name+" is "; if (object.working) { print "on\n"; } else { print "off\n"; }} ...but doing so would cause a difficulty in the code if we needed to localise it to Spanish because the word for 'on' is apparently different in those two cases. So, I guess my question is, how have other developers approached balancing the DRY principle with internationalisation of their code? Part of me wants to argue that internationalisation is one of those extreme programming “ you arent gonna need it ” situations. On the flip side however, refactoring with the DRY principle in mind is supposed to balance this by making it easy to implement functionality as it’s required, not harder as it does here.
I'd try to keep complete sentences in the language resource. As you said you might need different words in different contexts. But a bigger problem is that the order of sentences might be different in different languages. So building up strings from words can cause problems. Just store The printer is onThe printer is offThe stapler is onThe stapler is off in the language resource for every language. The repetition here is less of a maintenance headache than trying to figure out where all the single words are going to pop up in your application.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ] }
56,615
Possible Duplicate: Debugging JavaScript in IE7 Firefox has Web Developer plugin and Firebug for troubleshooting html/css/javascript issues. Google Chrome and Safari have a very similar console and right-click options for "Inspect Element". Does IE7 have anything similar for troubleshooting layout/html/css issues?
Yes - The Internet Explorer Developer Toolbar Download details: Internet Explorer Developer Toolbar
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/56615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ] }
56,628
I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log?
Making a log file smaller should really be reserved for scenarios where it encountered unexpected growth which you do not expect to happen again. If the log file will grow to the same size again, not very much is accomplished by shrinking it temporarily. Now, depending on the recovery goals of your database, these are the actions you should take. First, take a full backup Never make any changes to your database without ensuring you can restore it should something go wrong. If you care about point-in-time recovery (And by point-in-time recovery, I mean you care about being able to restore to anything other than a full or differential backup.) Presumably your database is in FULL recovery mode. If not, then make sure it is: ALTER DATABASE testdb SET RECOVERY FULL; Even if you are taking regular full backups, the log file will grow and grow until you perform a log backup - this is for your protection, not to needlessly eat away at your disk space. You should be performing these log backups quite frequently, according to your recovery objectives. For example, if you have a business rule that states you can afford to lose no more than 15 minutes of data in the event of a disaster, you should have a job that backs up the log every 15 minutes. Here is a script that will generate timestamped file names based on the current time (but you can also do this with maintenance plans etc., just don't choose any of the shrink options in maintenance plans, they're awful). DECLARE @path NVARCHAR(255) = N'\\backup_share\log\testdb_' + CONVERT(CHAR(8), GETDATE(), 112) + '_' + REPLACE(CONVERT(CHAR(8), GETDATE(), 108),':','') + '.trn';BACKUP LOG foo TO DISK = @path WITH INIT, COMPRESSION; Note that \\backup_share\ should be on a different machine that represents a different underlying storage device. Backing these up to the same machine (or to a different machine that uses the same underlying disks, or a different VM that's on the same physical host) does not really help you, since if the machine blows up, you've lost your database and its backups. Depending on your network infrastructure it may make more sense to backup locally and then transfer them to a different location behind the scenes; in either case, you want to get them off the primary database machine as quickly as possible. Now, once you have regular log backups running, it should be reasonable to shrink the log file to something more reasonable than whatever it's blown up to now. This does not mean running SHRINKFILE over and over again until the log file is 1 MB - even if you are backing up the log frequently, it still needs to accommodate the sum of any concurrent transactions that can occur. Log file autogrow events are expensive, since SQL Server has to zero out the files (unlike data files when instant file initialization is enabled), and user transactions have to wait while this happens. You want to do this grow-shrink-grow-shrink routine as little as possible, and you certainly don't want to make your users pay for it. Note that you may need to back up the log twice before a shrink is possible (thanks Robert). So, you need to come up with a practical size for your log file. Nobody here can tell you what that is without knowing a lot more about your system, but if you've been frequently shrinking the log file and it has been growing again, a good watermark is probably 10-50% higher than the largest it's been. Let's say that comes to 200 MB, and you want any subsequent autogrowth events to be 50 MB, then you can adjust the log file size this way: USE [master];GOALTER DATABASE Test1 MODIFY FILE (NAME = yourdb_log, SIZE = 200MB, FILEGROWTH = 50MB);GO Note that if the log file is currently > 200 MB, you may need to run this first: USE yourdb;GODBCC SHRINKFILE(yourdb_log, 200);GO If you don't care about point-in-time recovery If this is a test database, and you don't care about point-in-time recovery, then you should make sure that your database is in SIMPLE recovery mode. ALTER DATABASE testdb SET RECOVERY SIMPLE; Putting the database in SIMPLE recovery mode will make sure that SQL Server re-uses portions of the log file (essentially phasing out inactive transactions) instead of growing to keep a record of all transactions (like FULL recovery does until you back up the log). CHECKPOINT events will help control the log and make sure that it doesn't need to grow unless you generate a lot of t-log activity between CHECKPOINT s. Next, you should make absolute sure that this log growth was truly due to an abnormal event (say, an annual spring cleaning or rebuilding your biggest indexes), and not due to normal, everyday usage. If you shrink the log file to a ridiculously small size, and SQL Server just has to grow it again to accommodate your normal activity, what did you gain? Were you able to make use of that disk space you freed up only temporarily? If you need an immediate fix, then you can run the following: USE yourdb;GOCHECKPOINT;GOCHECKPOINT; -- run twice to ensure file wrap-aroundGODBCC SHRINKFILE(yourdb_log, 200); -- unit is set in MBsGO Otherwise, set an appropriate size and growth rate. As per the example in the point-in-time recovery case, you can use the same code and logic to determine what file size is appropriate and set reasonable autogrowth parameters. Some things you don't want to do Back up the log with TRUNCATE_ONLY option and then SHRINKFILE . For one, this TRUNCATE_ONLY option has been deprecated and is no longer available in current versions of SQL Server. Second, if you are in FULL recovery model, this will destroy your log chain and require a new, full backup. Detach the database, delete the log file, and re-attach . I can't emphasize how dangerous this can be. Your database may not come back up, it may come up as suspect, you may have to revert to a backup (if you have one), etc. etc. Use the "shrink database" option . DBCC SHRINKDATABASE and the maintenance plan option to do the same are bad ideas, especially if you really only need to resolve a log problem issue. Target the file you want to adjust and adjust it independently, using DBCC SHRINKFILE or ALTER DATABASE ... MODIFY FILE (examples above). Shrink the log file to 1 MB . This looks tempting because, hey, SQL Server will let me do it in certain scenarios, and look at all the space it frees! Unless your database is read only (and it is, you should mark it as such using ALTER DATABASE ), this will absolutely just lead to many unnecessary growth events, as the log has to accommodate current transactions regardless of the recovery model. What is the point of freeing up that space temporarily, just so SQL Server can take it back slowly and painfully? Create a second log file . This will provide temporarily relief for the drive that has filled your disk, but this is like trying to fix a punctured lung with a band-aid. You should deal with the problematic log file directly instead of just adding another potential problem. Other than redirecting some transaction log activity to a different drive, a second log file really does nothing for you (unlike a second data file), since only one of the files can ever be used at a time. Paul Randal also explains why multiple log files can bite you later . Be proactive Instead of shrinking your log file to some small amount and letting it constantly autogrow at a small rate on its own, set it to some reasonably large size (one that will accommodate the sum of your largest set of concurrent transactions) and set a reasonable autogrow setting as a fallback, so that it doesn't have to grow multiple times to satisfy single transactions and so that it will be relatively rare for it to ever have to grow during normal business operations. The worst possible settings here are 1 MB growth or 10% growth. Funny enough, these are the defaults for SQL Server (which I've complained about and asked for changes to no avail ) - 1 MB for data files, and 10% for log files. The former is much too small in this day and age, and the latter leads to longer and longer events every time (say, your log file is 500 MB, first growth is 50 MB, next growth is 55 MB, next growth is 60.5 MB, etc. etc. - and on slow I/O, believe me, you will really notice this curve). Further reading Please don't stop here; while much of the advice you see out there about shrinking log files is inherently bad and even potentially disastrous, there are some people who care more about data integrity than freeing up disk space. A blog post I wrote in 2009, when I saw a few "here's how to shrink the log file" posts spring up . A blog post Brent Ozar wrote four years ago, pointing to multiple resources, in response to a SQL Server Magazine article that should not have been published . A blog post by Paul Randal explaining why t-log maintenance is important and why you shouldn't shrink your data files, either . Mike Walsh has a great answer covering some of these aspects too, including reasons why you might not be able to shrink your log file immediately .
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/56628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
56,642
I am building on C++ dll, by writing code in C#. I get an error, saying LoaderLock was detected Message: Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang. I tried seraching what this error exactly means, but I am drawing pointless articles, mostly saying that it's just a warning, and I should switch that off in Visual Studio.The other solutions seem to be due to ITunes, or this problem occurring when programming with DirectX. My problem is connected to neither. Can anybody explain, what this actually means?
The general idea of loader lock:The system runs the code in DllMain inside a lock (as in - synchronization lock). Therefore, running non-trivial code inside DllMain is "asking for a deadlock", as described here . The question is, why are you trying to run code inside DllMain? Is it crucial that this code run inside the context of DllMain or can you spawn a new thread and run the code in it, and not wait for the code to finish execution inside DllMain? I believe that the problem with manged code specifically, is that running managed code might involves loading the CLR and suchlike and there's no knowing what could happen there that would result in a deadlock... I would not heed the advice of "disable this warning" if I were you because most chances are you'll find your applications hangs unexpectedly under some scenarios.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895/" ] }
56,648
If you have an NSMutableArray , how do you shuffle the elements randomly? (I have my own answer for this, which is posted below, but I'm new to Cocoa and I'm interested to know if there is a better way.) Update: As noted by @Mukesh, as of iOS 10+ and macOS 10.12+, there is an -[NSMutableArray shuffledArray] method that can be used to shuffle. See https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc for details. (But note that this creates a new array, rather than shuffling the elements in place.)
I solved this by adding a category to NSMutableArray. Edit: Removed unnecessary method thanks to answer by Ladd. Edit: Changed (arc4random() % nElements) to arc4random_uniform(nElements) thanks to answer by Gregory Goltsov and comments by miho and blahdiblah Edit: Loop improvement, thanks to comment by Ron Edit: Added check that array is not empty, thanks to comment by Mahesh Agrawal // NSMutableArray_Shuffling.h#if TARGET_OS_IPHONE#import <UIKit/UIKit.h>#else#include <Cocoa/Cocoa.h>#endif// This category enhances NSMutableArray by providing// methods to randomly shuffle the elements.@interface NSMutableArray (Shuffling)- (void)shuffle;@end// NSMutableArray_Shuffling.m#import "NSMutableArray_Shuffling.h"@implementation NSMutableArray (Shuffling)- (void)shuffle{ NSUInteger count = [self count]; if (count <= 1) return; for (NSUInteger i = 0; i < count - 1; ++i) { NSInteger remainingCount = count - i; NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount); [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex]; }}@end
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/56648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ] }
56,658
Summary What's the best way to ensure a table cell cannot be less than a certain minimum width. Example I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space. Browser compatibility I possible I would like to find a solution that works in IE 6-8 FF 2-3 Safari In order of preference.
This CSS should suffice: td { min-width: 100px; } However, it's not always obeyed correctly (the min-width attribute) by all browsers (for example, IE6 dislikes it a great deal). Edit: As for an IE6 (and before) solution, there isn't one that works reliably under all circumstances, as far as I know. Using the nowrap HTML attribute doesn't really achieve the desired result, as that just prevents line-breaks in the cell, rather than specifying a minimum width. However, if nowrap is used in conjunction with a regular cell width property (such as using width: 100px), the 100px will act like a minimum width and the cell will still expand with the text (due to the nowrap). This is a less-than-ideal solution, which cannot be fully applied using CSS and, as such, would be tedious to implement if you have many tables you wish to apply this to. (Of course, this entire alternative solution falls down if you want to have dynamic line-breaks in your cells, anyway).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/56658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5182/" ] }
56,677
I have 150+ SQL queries in separate text files that I need to analyze (just the actual SQL code, not the data results) in order to identify all column names and table names used. Preferably with the number of times each column and table makes an appearance. Writing a brand new SQL parsing program is trickier than is seems, with nested SELECT statements and the like. There has to be a program, or code out there that does this (or something close to this), but I have not found it.
I actually ended up using a tool called SQL Pretty Printer . You can purchase a desktop version, but I just used the free online application. Just copy the query into the text box, set the Output to "List DB Object" and click the Format SQL button. It work great using around 150 different (and complex) SQL queries.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5854/" ] }
56,684
I want Windows Update to automatically download and install updates on my Vista machine, however I don't want to be bothered by the system tray reboot prompts (which can, at best, only be postponed by 4 hours). I have performed the registry hack described here to prevent Windows forcibly rebooting my machine, which is a good start. However, is there any way to get rid of the reboot prompts altogether, or decrease their frequency?
Not sure if it is the same for vista, but worth a try. On Windows XP, you can modify a group policy setting to change how frequently it re-prompts you. (start -> run type gpedit.msc) Look under Computer Configuration/Administrative Templates/Windows Components/Windows Update The setting you want is called Re-Prompt for restart with scheduled installations. The default is 10 minutes. You can also try modifying the No auto-restart for scheduled Automatic Updates installations setting found in the same location.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ] }
56,692
Consider the class below that represents a Broker: public class Broker{ public string Name = string.Empty; public int Weight = 0; public Broker(string n, int w) { this.Name = n; this.Weight = w; }} I'd like to randomly select a Broker from an array, taking into account their weights. What do you think of the code below? class Program { private static Random _rnd = new Random(); public static Broker GetBroker(List<Broker> brokers, int totalWeight) { // totalWeight is the sum of all brokers' weight int randomNumber = _rnd.Next(0, totalWeight); Broker selectedBroker = null; foreach (Broker broker in brokers) { if (randomNumber <= broker.Weight) { selectedBroker = broker; break; } randomNumber = randomNumber - broker.Weight; } return selectedBroker; } static void Main(string[] args) { List<Broker> brokers = new List<Broker>(); brokers.Add(new Broker("A", 10)); brokers.Add(new Broker("B", 20)); brokers.Add(new Broker("C", 20)); brokers.Add(new Broker("D", 10)); // total the weigth int totalWeight = 0; foreach (Broker broker in brokers) { totalWeight += broker.Weight; } while (true) { Dictionary<string, int> result = new Dictionary<string, int>(); Broker selectedBroker = null; for (int i = 0; i < 1000; i++) { selectedBroker = GetBroker(brokers, totalWeight); if (selectedBroker != null) { if (result.ContainsKey(selectedBroker.Name)) { result[selectedBroker.Name] = result[selectedBroker.Name] + 1; } else { result.Add(selectedBroker.Name, 1); } } } Console.WriteLine("A\t\t" + result["A"]); Console.WriteLine("B\t\t" + result["B"]); Console.WriteLine("C\t\t" + result["C"]); Console.WriteLine("D\t\t" + result["D"]); result.Clear(); Console.WriteLine(); Console.ReadLine(); } } } I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight. Is there a more accurate algorithm? Thanks!
Your algorithm is nearly correct. However, the test should be < instead of <= : if (randomNumber < broker.Weight) This is because 0 is inclusive in the random number while totalWeight is exclusive. In other words, a broker with weight 0 would still have a small chance of being selected – not at all what you want. This accounts for broker A having more hits than broker D. Other than that, your algorithm is fine and in fact the canonical way of solving this problem.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2868/" ] }
56,708
What would be the best way to write Objective-C on the Windows platform? Cygwin and gcc? Is there a way I can somehow integrate this into Visual Studio? Along those lines - are there any suggestions as to how to link in and use the Windows SDK for something like this. Its a different beast but I know I can write assembly and link in the Windows DLLs giving me accessibility to those calls but I don't know how to do this without googling and getting piecemeal directions. Is anyone aware of a good online or book resource to do or explain these kinds of things?
Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets. Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features. I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows. For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/56708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4910/" ] }
56,737
Is the standard Java 1.6 javax.xml.parsers.DocumentBuilder class thread safe? Is it safe to call the parse() method from several threads in parallel? The JavaDoc doesn't mention the issue, but the JavaDoc for the same class in Java 1.4 specifically says that it isn't meant to be concurrent; so can I assume that in 1.6 it is? The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.
Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal: private static final ThreadLocal<DocumentBuilder> builderLocal = new ThreadLocal<DocumentBuilder>() { @Override protected DocumentBuilder initialValue() { try { return DocumentBuilderFactory .newInstance( "xx.MyDocumentBuilderFactory", getClass().getClassLoader() ).newDocumentBuilder(); } catch (ParserConfigurationException exc) { throw new IllegalArgumentException(exc); } } }; (Disclaimer: Not so much as attempted to compile the code.)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1605/" ] }
56,786
We have a 42U rack which is getting a load of new 1U and 2U servers real soon. One of the guys here reckons that you need to leave a gap between the servers (of 1U) to aid cooling. Question is, do you? When looking around the datacenter, no-one else seems to be, and it also diminishes how much we can fit in. We're using Dell 1850 and 2950 hardware.
Simply NO, the servers and switches, and KVMs, and PSUs are all designed to be on the rack stacked on top of eachother. I'm basing this on a few years building, COs and Data centers for AT&T.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4787/" ] }
56,810
I have used fork() in C to start another process. How do I start a new thread?
Since you mentioned fork() I assume you're on a Unix-like system, in which case POSIX threads (usually referred to as pthreads) are what you want to use. Specifically, pthread_create() is the function you need to create a new thread. Its arguments are: int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg); The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/56810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ] }
56,820
The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this: n = 5.59round(n, 1) # 5.6 But, in actuality, good old floating point weirdness creeps in and you get: 5.5999999999999996 For the purposes of UI, I need to display 5.6 . I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. See here also . Short of creating my own round library, is there any way around this?
I can't help the way it's stored, but at least formatting works correctly: '%.1f' % round(n, 1) # Gives you '5.6'
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/56820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/736/" ] }
56,860
I have heard that the Liskov Substitution Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?
A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn't quite work in code. In mathematics, a Square is a Rectangle . Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you made Square derive from Rectangle , then a Square should be usable anywhere you expect a Rectangle . This makes for some strange behavior. Imagine you had SetWidth and SetHeight methods on your Rectangle base class; this seems perfectly logical. However if your Rectangle reference pointed to a Square , then SetWidth and SetHeight doesn't make sense because setting one would change the other to match it. In this case Square fails the Liskov Substitution Test with Rectangle and the abstraction of having Square inherit from Rectangle is a bad one. Y'all should check out the other priceless SOLID Principles Explained With Motivational Posters .
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/56860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ] }
56,867
When should I use an interface and when should I use a base class? Should it always be an interface if I don't want to actually define a base implementation of the methods? If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.
Let's take your example of a Dog and a Cat class, and let's illustrate using C#: Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them: public abstract class Mammal This base class will probably have default methods such as: Feed Mate All of which are behavior that have more or less the same implementation between either species. To define this you will have: public class Dog : Mammalpublic class Cat : Mammal Now let's suppose there are other mammals, which we will usually see in a zoo: public class Giraffe : Mammalpublic class Rhinoceros : Mammalpublic class Hippopotamus : Mammal This will still be valid because at the core of the functionality Feed() and Mate() will still be the same. However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful: public interface IPettable{ IList<Trick> Tricks{get; set;} void Bathe(); void Train(Trick t);} The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea. Your Dog and Cat definitions should now look like: public class Dog : Mammal, IPettablepublic class Cat : Mammal, IPettable Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance. Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/56867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2871/" ] }
56,895
How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set. As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there was no out of place results.
The best you can do is compare the 2 query outputs based on a given set of inputs looking for any differences. To say that they will always return the same results for all inputs really depends on the data. For Oracle one of the better if not best approaches (very efficient) is here ( Ctrl + F Comparing the Contents of Two Tables): http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html Which boils down to: select c1,c2,c3, count(src1) CNT1, count(src2) CNT2 from (select a.*, 1 src1, to_number(null) src2 from a union all select b.*, to_number(null) src1, 2 src2 from b )group by c1,c2,c3having count(src1) <> count(src2);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ] }
56,923
Just what the title says, I need to change the password for an existing sql server login and I want to do it via sql script.
ALTER LOGIN http://msdn.microsoft.com/en-us/library/ms189828.aspx
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642688/" ] }
56,947
In follow up to this question , it appears that some numbers cannot be represented by floating point at all, and instead are approximated. How are floating point numbers stored? Is there a common standard for the different sizes? What kind of gotchas do I need to watch out for if I use floating point? Are they cross-language compatible (ie, what conversions do I need to deal with to send a floating point number from a python program to a C program over TCP/IP)?
As mentioned, the Wikipedia article on IEEE 754 does a good job of showing how floating point numbers are stored on most systems. Now, here are some common gotchas: The biggest is that you almost never want to compare two floating point numbers for equality (or inequality). You'll want to use greater than/less than comparisons instead. The more operations you do on a floating point number, the more significant rounding errors can become. Precision is limited by the size of the fraction, so you may not be able to correctly add numbers that are separated by several orders of magnitude. (For example, you won't be able to add 1E-30 to 1E30.)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/56947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ] }
56,950
We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired... I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example: Value---------- 143.55 3532.13 1.75 How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever". I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control. Thank you.
The STR function has an optional length argument as well as a number-of-decimals one. SELECT STR(123.45, 6, 1)------ 123.5(1 row(s) affected)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2230/" ] }
56,954
The code private SomeClass<Integer> someClass;someClass = EasyMock.createMock(SomeClass.class); gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>".
AFAIK, you can't avoid the unchecked warning when a class name literal is involved, and the SuppressWarnings annotation is the only way to handle this. Note that it is good form to narrow the scope of the SuppressWarnings annotation as much as possible. You can apply this annotation to a single local variable assignment: public void testSomething() { @SuppressWarnings("unchecked") Foo<Integer> foo = EasyMock.createMock(Foo.class); // Rest of test method may still expose other warnings} or use a helper method: @SuppressWarnings("unchecked")private static <T> Foo<T> createFooMock() { return (Foo<T>)EasyMock.createMock(Foo.class);}public void testSomething() { Foo<String> foo = createFooMock(); // Rest of test method may still expose other warnings}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/56954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ] }
56,974
In the following snippet: public class a { public void otherMethod(){} public void doStuff(String str, InnerClass b){} public void method(a){ doStuff("asd", new InnerClass(){ public void innerMethod(){ otherMethod(); } } ); }} Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is outer.otherMethod() , or something of the like, but can't seem to find anything.
In general you use OuterClassName.this to refer to the enclosing instance of the outer class. In your example that would be a.this.otherMethod()
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/56974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ] }
57,002
What CSS should I use to make a cell's border appear even if the cell is empty? IE 7 specifically.
If I recall, the cell dosn't exist in some IE's unless it's filled with something... If you can put a &nbsp; (non-breaking space) to fill the void, that will usually work. Or do you require a pure CSS solution? Apparently, IE8 shows the cells by default, and you have to hide it with empty-cells:hide But it doesn't work at all in IE7 (which hides by default).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/57002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ] }
57,019
I'm building an application that is targeting Windows, Mac and Linux soon. I was wondering where should I keep application data such as settings, etc. Application's installation folder is the easiest choice, but I think that might be a problem with new Vista security model. Besides, users might want different settings. Is it C:\Documents and Settings\username\MyApp good for both Vista and XP?Is it /home/username/.MyApp good for Linux and Macs? Any ideas and/or links to best practices much appreciated. Thanks! Juan
Each platform has its own API for finding the user's home folder, or documents folder, or preferences folder. Windows: SHGetFolderPath() or SHGetKnownFolderPath() Mac OS X and iPhone OS: NSSearchPathForDirectoriesInDomains() Unix: $HOME environment variable Don't hardcode specific paths or just tack a prefix and suffix on the user's name. Also, try to follow whatever conventions there are for the platform for naming the files.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5908/" ] }
57,068
Does anybody know of any sample databases I could download, preferably in CSV or some similar easy to import format so that I could get more practice in working with different types of data sets? I know that the Canadian Department of Environment has historical weather data that you can download. However, it's not in a common format I can import into any other database. Moreover, you can only run queries based on the included program, which is actually quite limited in what kind of data it can provide. Does anybody know of any interesting data sets that are freely available in a common format that I could use with mySql, Sql Server, and other types of database engines?
The datawrangling blog posted a nice list a while back: http://www.datawrangling.com/some-datasets-available-on-the-web Includes financial, government data (labor, housing, etc.), and too many more to list here.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ] }
57,124
I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so. If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0. Is there a way to bypass this behaviour and get true Windows version?
The best approach I know is to check if specific API is exported from some DLL. Each new Windows version adds new functions and by checking the existance of those functions one can tell which OS the application is running on. For example, Vista exports GetLocaleInfoEx from kernel32.dll while previous Windowses didn't. To cut the long story short, here is one such list containing only exports from kernel32.dll. > *function: implemented in* > GetLocaleInfoEx: Vista > GetLargePageMinimum: Vista, Server 2003 GetDLLDirectory: Vista, Server 2003, XP SP1 GetNativeSystemInfo: Vista, Server 2003, XP SP1, XP ReplaceFile: Vista, Server 2003, XP SP1, XP, 2000 OpenThread: Vista, Server 2003, XP SP1, XP, 2000, ME GetThreadPriorityBoost: Vista, Server 2003, XP SP1, XP, 2000, NT 4 IsDebuggerPresent: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98 GetDiskFreeSpaceEx: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98, 95 OSR2 ConnectNamedPipe: Vista, Server 2003, XP SP1, XP, 2000, NT 4, NT 3 Beep: Vista, Server 2003, XP SP1, XP, 2000, ME, 98, 95 OSR2, 95 Writing the function to determine the real OS version is simple; just proceed from newest OS to oldest and use GetProcAddress to check exported APIs. Implementing this in any language should be trivial. The following code in Delphi was extracted from the free DSiWin32 library): TDSiWindowsVersion = (wvUnknown, wvWin31, wvWin95, wvWin95OSR2, wvWin98, wvWin98SE, wvWinME, wvWin9x, wvWinNT3, wvWinNT4, wvWin2000, wvWinXP, wvWinNT, wvWinServer2003, wvWinVista);function DSiGetWindowsVersion: TDSiWindowsVersion;var versionInfo: TOSVersionInfo;begin versionInfo.dwOSVersionInfoSize := SizeOf(versionInfo); GetVersionEx(versionInfo); Result := wvUnknown; case versionInfo.dwPlatformID of VER_PLATFORM_WIN32s: Result := wvWin31; VER_PLATFORM_WIN32_WINDOWS: case versionInfo.dwMinorVersion of 0: if Trim(versionInfo.szCSDVersion[1]) = 'B' then Result := wvWin95OSR2 else Result := wvWin95; 10: if Trim(versionInfo.szCSDVersion[1]) = 'A' then Result := wvWin98SE else Result := wvWin98; 90: if (versionInfo.dwBuildNumber = 73010104) then Result := wvWinME; else Result := wvWin9x; end; //case versionInfo.dwMinorVersion VER_PLATFORM_WIN32_NT: case versionInfo.dwMajorVersion of 3: Result := wvWinNT3; 4: Result := wvWinNT4; 5: case versionInfo.dwMinorVersion of 0: Result := wvWin2000; 1: Result := wvWinXP; 2: Result := wvWinServer2003; else Result := wvWinNT end; //case versionInfo.dwMinorVersion 6: Result := wvWinVista; end; //case versionInfo.dwMajorVersion end; //versionInfo.dwPlatformIDend; { DSiGetWindowsVersion }function DSiGetTrueWindowsVersion: TDSiWindowsVersion; function ExportsAPI(module: HMODULE; const apiName: string): boolean; begin Result := GetProcAddress(module, PChar(apiName)) <> nil; end; { ExportsAPI }var hKernel32: HMODULE;begin { DSiGetTrueWindowsVersion } hKernel32 := GetModuleHandle('kernel32'); Win32Check(hKernel32 <> 0); if ExportsAPI(hKernel32, 'GetLocaleInfoEx') then Result := wvWinVista else if ExportsAPI(hKernel32, 'GetLargePageMinimum') then Result := wvWinServer2003 else if ExportsAPI(hKernel32, 'GetNativeSystemInfo') then Result := wvWinXP else if ExportsAPI(hKernel32, 'ReplaceFile') then Result := wvWin2000 else if ExportsAPI(hKernel32, 'OpenThread') then Result := wvWinME else if ExportsAPI(hKernel32, 'GetThreadPriorityBoost') then Result := wvWinNT4 else if ExportsAPI(hKernel32, 'IsDebuggerPresent') then //is also in NT4! Result := wvWin98 else if ExportsAPI(hKernel32, 'GetDiskFreeSpaceEx') then //is also in NT4! Result := wvWin95OSR2 else if ExportsAPI(hKernel32, 'ConnectNamedPipe') then Result := wvWinNT3 else if ExportsAPI(hKernel32, 'Beep') then Result := wvWin95 else // we have no idea Result := DSiGetWindowsVersion;end; { DSiGetTrueWindowsVersion } --- updated 2009-10-09 It turns out that it gets very hard to do an "undocumented" OS detection on Vista SP1 and higher. A look at the API changes shows that all Windows 2008 functions are also implemented in Vista SP1 and that all Windows 7 functions are also implemented in Windows 2008 R2. Too bad :( --- end of update FWIW, this is a problem I encountered in practice. We (the company I work for) have a program that was not really Vista-ready when Vista was released (and some weeks after that ...). It was not working under the compatibility layer either. (Some DirectX problems. Don't ask.) We didn't want too-smart-for-their-own-good users to run this app on Vista at all - compatibility mode or not - so I had to find a solution (a guy smarter than me pointed me into right direction; the stuff above is not my brainchild). Now I'm posting it for your pleasure and to help all poor souls that will have to solve this problem in the future. Google, please index this article! If you have a better solution (or an upgrade and/or fix for mine), please post an answer here ...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4997/" ] }
57,137
I recently upgraded to Subversion 1.5, and now I cannot commit my code to the repository. I get an error message: "403 Forbidden in response to MKACTIVITY". I know the upgrade worked because my fellow developers are not getting this issue. What's going on?
Answering my own question: Apparently my SVN URL had the wrong case! A Google search turned up an article (no longer available online) that explained what was going on. My URL was of the form http://svn.foobar.com/foobar but the actual repository was called http://svn.foobar.com/fooBar . I use TortoiseSVN, so the fix was to use the Relocate command to correct the path to the repository. Hopefully this will help someone else.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/57137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5626/" ] }
57,168
I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility).
As long as there are no identity columns you can just INSERT INTO TableNewSELECT * FROM TableOldWHERE [Conditions]
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/57168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536/" ] }
57,350
I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path?
How about this, for example: String appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); I don't see an enum for just the Local Settings folder. http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx has a list with examples.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ] }
57,383
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code: public void test1(){ // Throw an exception for testing purposes throw new ArgumentException("test1");}void test2(){ try { MethodInfo mi = typeof(Program).GetMethod("test1"); mi.Invoke(this, null); } catch (TargetInvocationException tiex) { // Throw the new exception throw tiex.InnerException; }}
In .NET 4.5 there is now the ExceptionDispatchInfo class. This lets you capture an exception and re-throw it without changing the stack-trace: using ExceptionDispatchInfo = System.Runtime.ExceptionServices.ExceptionDispatchInfo;try{ task.Wait();}catch(AggregateException ex){ ExceptionDispatchInfo.Capture(ex.InnerException).Throw();} This works on any exception, not just AggregateException . It was introduced due to the await C# language feature, which unwraps the inner exceptions from AggregateException instances in order to make the asynchronous language features more like the synchronous language features.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/57383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205/" ] }
57,409
In Eclipse, I have a workspace that contains all of my projects. Each project builds and compiles separately. A project does not interact with another project. How does this relate to Visual Studio and Projects/Solutions there?
A VS project is it's own entity. It will build and compile by itself. A Solution is just a way to contain multiple projects. The projects don't necessarily need the other projects to compile (though, they can depend on the other projects). This just lets you conceptually group projects together into one Big Project. For instance, you can have a separate testing project. It depends on the code from the actual project, and should be kept together with the actual project, but it does not need to be in the same exe/dll.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
57,439
No, this is not a question about generics. I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory). My problem is that CreateInstance fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter. Example // FailsActivator.CreateInstance(type);// WorksActivator.CreateInstance(type, true); I wanted to make the factory generic to make it a little simpler, like this: public class GenericFactory<T> where T : MyAbstractType{ public static T GetInstance() { return Activator.CreateInstance<T>(); }} However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal). Did I miss something or it isn't possible?
To get around this, couldnt you just alter your usage as such: public class GenericFactory<T> where T : MyAbstractType{ public static T GetInstance() { return Activator.CreateInstance(typeof(T), true); }} Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ] }
57,467
Is there an equivalent of svn's blame for Perforce on the command line? p4 annotate doesn't display usernames -- only changeset numbers (without ancestor history!). I currently have to track code back through ancestors and compare against the filelog, and there just has to be an easier way -- maybe a F/OSS utility?
I'm not overly familiar with the blame command, but I assume that you are looking for who changes a particular line of code. The easiest way is to use Perforce's 'time lapse view' available from both p4win and p4v. This tool uses annotate and some other commands to give you a view of the code line over time. You can see who modified what code, when it was inserted or removed from the codeline, etc. It's not command line though. I checked briefly in the help and there doesnt' seem to be a way to launch the time lapse view directly from a p4win or p4v invocation. There might be though...I'll be checking further... Edit: I checked with support, and you can launch the timelapse view through p4v as follows: p4v.exe -cmd "annotate //<path/to/file>" HTH.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ] }
57,483
What is the difference between a pointer variable and a reference variable?
A pointer can be re-assigned: int x = 5;int y = 6;int *p;p = &x;p = &y;*p = 10;assert(x == 5);assert(y == 10); A reference cannot be re-bound, and must be bound at initialization: int x = 5;int y = 6;int &q; // errorint &r = x; A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary & operator and a certain amount of space that can be measured with the sizeof operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable. int x = 0;int &r = x;int *p = &x;int *p2 = &r;assert(p == p2); // &x == &rassert(&p != &p2); You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection. int x = 0;int y = 0;int *p = &x;int *q = &y;int **pp = &p;**pp = 2;pp = &q; // *pp is now q**pp = 4;assert(y == 4);assert(x == 2); A pointer can be assigned nullptr , whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to nullptr , but this is undefined and will not behave consistently. /* the code below is undefined; your compiler may optimise it * differently, emit warnings, or outright refuse to compile it */int &r = *static_cast<int *>(nullptr);// prints "null" under GCC 10std::cout << (&r != nullptr ? "not null" : "null") << std::endl;bool f(int &r) { return &r != nullptr; }// prints "not null" under GCC 10std::cout << (f(*static_cast<int *>(nullptr)) ? "not null" : "null") << std::endl; You can, however, have a reference to a pointer whose value is nullptr . Pointers can iterate over an array; you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to. A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access its members whereas a reference uses a . . References cannot be put into an array, whereas pointers can be (Mentioned by user @litb) Const references can be bound to temporaries. Pointers cannot (not without some indirection): const int &x = int(12); // legal C++int *y = &int(12); // illegal to take the address of a temporary. This makes const & more convenient to use in argument lists and so forth.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/57483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ] }
57,484
I'm trying to do a basic "OR" on three fields using a hibernate criteria query. Example class Whatever{ string name; string address; string phoneNumber;} I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".
You want to use Restrictions.disjuntion() . Like so session.createCriteria(Whatever.class) .add(Restrictions.disjunction() .add(Restrictions.eq("name", queryString)) .add(Restrictions.eq("address", queryString)) .add(Restrictions.eq("phoneNumber", queryString)) ); See the Hibernate doc here .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/57484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ] }
57,493
In my WPF application, I have a number of databound TextBoxes. The UpdateSourceTrigger for these bindings is LostFocus . The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind? @palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want. @dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself. @Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem: <Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Window.Resources> <ObjectDataProvider x:Key="MyItemProvider" /> </Window.Resources> <DockPanel LastChildFill="True"> <Menu DockPanel.Dock="Top"> <MenuItem Header="File"> <MenuItem Header="Save" Click="MenuItem_Click" /> </MenuItem> </Menu> <StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}"> <Label Content="Enter some text and then File > Save:" /> <TextBox Text="{Binding ValueA}" /> <TextBox Text="{Binding ValueB}" /> </StackPanel> </DockPanel></Window> using System;using System.Text;using System.Windows;using System.Windows.Data;namespace WpfApplication2{ public partial class Window1 : Window { public MyItem Item { get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; } set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; } } public Window1() { InitializeComponent(); Item = new MyItem(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB)); } } public class MyItem { public string ValueA { get; set; } public string ValueB { get; set; } }}
I found that removing the menu items that are scope depended from the FocusScope of the menu causes the textbox to lose focus correctly. I wouldn't think this applies to ALL items in Menu, but certainly for a save or validate action. <Menu FocusManager.IsFocusScope="False" >
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ] }
57,530
Are there any tools to facilitate a migration from Sourcegear's Vault to Subversion ? I'd really prefer an existing tool or project (I'll buy!). Requirements: One-time migration only Full history with comments Optional: Some support for labels/branches/tags Relatively speedy. It can take hours but not days. Cost if available Bonus points if you can share personal experience related to this process. One of the reasons I'd like to do this is because we have lots of projects spread between Vault and Subversion (we're finally away from sourcesafe). It'd be helpful in some situations to be able to consolidate a particular customer's repos to SVN. Additionally, SVN is better supported among third party tools. For example, Hudson and Redmine . Again, though: we're not abandoning vault altogether.
We are thinking about migrating from vault to git. I wrote vault2git converter that takes care of history and removes vault bindings from *.sln, *.csproj files. Once you have git repo, there is git2svn. I know it sounds like going rounds, but it might be faster than writing vault2svn from scratch.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29/" ] }
57,537
In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying. It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost. Does anyone know of a method for getting the context directory so that I can load and write files to disk?
This should give you the real path that you can use to extract / edit files. Javadoc Link We're doing something similar in a context listener. public class MyServlet extends HttpServlet { public void init(final ServletConfig config) { final String context = config.getServletContext().getRealPath("/"); ... } ...}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682/" ] }
57,584
I've found some examples using the Win32 api or simulating the ^+ button combination ( ctrl - + ) using SendKeys , but at least with the SendKeys method the listview grabs the cursor and sets it to an hourglass until I hit the start button on my keyboard. What is the cleanest way to do this?
Looks like a call to myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent) will do what you want. I would think, just call it after adding an item. More info here
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ] }
57,599
What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)? The datediff function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my stored procedure .
Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate. DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days intSELECT @date = '2/29/04'SELECT @tmpdate = @dateSELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 ENDSELECT @tmpdate = DATEADD(yy, @years, @tmpdate)SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 ENDSELECT @tmpdate = DATEADD(m, @months, @tmpdate)SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())SELECT @years, @months, @days
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/57599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845/" ] }
57,600
Should developers avoid using continue in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about Goto ?
I think there should be more use of continue! Too often I come across code like: for (...){ if (!cond1) { if (!cond2) { ... highly indented lines ... } }} instead of for (...){ if (cond1 || cond2) { continue; } ...} Use it to make the code more readable!
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/57600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831/" ] }
57,615
I have a console app in which I want to give the user x seconds to respond to the prompt. If no input is made after a certain period of time, program logic should continue. We assume a timeout means empty response. What is the most straightforward way of approaching this?
I'm surprised to learn that after 5 years, all of the answers still suffer from one or more of the following problems: A function other than ReadLine is used, causing loss of functionality. (Delete/backspace/up-key for previous input). Function behaves badly when invoked multiple times (spawning multiple threads, many hanging ReadLine's, or otherwise unexpected behavior). Function relies on a busy-wait. Which is a horrible waste since the wait is expected to run anywhere from a number of seconds up to the timeout, which might be multiple minutes. A busy-wait which runs for such an ammount of time is a horrible suck of resources, which is especially bad in a multithreading scenario. If the busy-wait is modified with a sleep this has a negative effect on responsiveness, although I admit that this is probably not a huge problem. I believe my solution will solve the original problem without suffering from any of the above problems: class Reader { private static Thread inputThread; private static AutoResetEvent getInput, gotInput; private static string input; static Reader() { getInput = new AutoResetEvent(false); gotInput = new AutoResetEvent(false); inputThread = new Thread(reader); inputThread.IsBackground = true; inputThread.Start(); } private static void reader() { while (true) { getInput.WaitOne(); input = Console.ReadLine(); gotInput.Set(); } } // omit the parameter to read a line without a timeout public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) { getInput.Set(); bool success = gotInput.WaitOne(timeOutMillisecs); if (success) return input; else throw new TimeoutException("User did not provide input within the timelimit."); }} Calling is, of course, very easy: try { Console.WriteLine("Please enter your name within the next 5 seconds."); string name = Reader.ReadLine(5000); Console.WriteLine("Hello, {0}!", name);} catch (TimeoutException) { Console.WriteLine("Sorry, you waited too long.");} Alternatively, you can use the TryXX(out) convention, as shmueli suggested: public static bool TryReadLine(out string line, int timeOutMillisecs = Timeout.Infinite) { getInput.Set(); bool success = gotInput.WaitOne(timeOutMillisecs); if (success) line = input; else line = null; return success; } Which is called as follows: Console.WriteLine("Please enter your name within the next 5 seconds.");string name;bool success = Reader.TryReadLine(out name, 5000);if (!success) Console.WriteLine("Sorry, you waited too long.");else Console.WriteLine("Hello, {0}!", name); In both cases, you cannot mix calls to Reader with normal Console.ReadLine calls: if the Reader times out, there will be a hanging ReadLine call. Instead, if you want to have a normal (non-timed) ReadLine call, just use the Reader and omit the timeout, so that it defaults to an infinite timeout. So how about those problems of the other solutions I mentioned? As you can see, ReadLine is used, avoiding the first problem. The function behaves properly when invoked multiple times. Regardless of whether a timeout occurs or not, only one background thread will ever be running and only at most one call to ReadLine will ever be active. Calling the function will always result in the latest input, or in a timeout, and the user won't have to hit enter more than once to submit his input. And, obviously, the function does not rely on a busy-wait. Instead it uses proper multithreading techniques to prevent wasting resources. The only problem that I foresee with this solution is that it is not thread-safe. However, multiple threads can't really ask the user for input at the same time, so synchronization should be happening before making a call to Reader.ReadLine anyway.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/57615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ] }
57,622
I have a start of a webapp that I wrote without using the Object Oriented features of PHP. I don't really know if it is worth it to go back and rewrite the parts I have finished. Is object oriented PHP worth rewriting all or part of a decent working app?
Given that you have an incomplete app I would say that reworking it into an Object based app will probably be helpful. One thing to consider is the expected size of the end application. Below a certain complexity Object based may be overkill except for the learning experience. I started out avoiding Objects like the plague because my initial introduction to them in university classes was terrible. I somewhat recently had to work on a project which was implemented in php objects. making the required changes was much easier than other projects. I have since then worked in the object model frequently and find it very handy for quick creation and easier upkeep.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ] }
57,652
Scenario: The user has two monitors. Their browser is open on the secondary monitor. They click a link in the browser which calls window.open() with a specific top and left window offset. The popup window always opens on their primary monitor. Is there any way in JavaScript to get the popup window to open on the same monitor as the initial browser window (the opener)?
You can't specify the monitor, but you can specify the position of the popup window as being relative to the where the click caused the window to popup. Use the getMouseXY() function to get values to pass as the left and top args to the window.open() method. (the left and top args only work with V3 and up browsers). window.open docs: http://www.javascripter.net/faq/openinga.htm function getMouseXY( e ) { if ( event.clientX ) { // Grab the x-y pos.s if browser is IE. CurrentLeft = event.clientX + document.body.scrollLeft; CurrentTop = event.clientY + document.body.scrollTop; } else { // Grab the x-y pos.s if browser isn't IE. CurrentLeft = e.pageX; CurrentTop = e.pageY; } if ( CurrentLeft < 0 ) { CurrentLeft = 0; }; if ( CurrentTop < 0 ) { CurrentTop = 0; }; return true;}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436/" ] }
57,665
Is there an easy way to return data to web service clients in JSON using Rails?
Rails resource gives a RESTful interface for your model. Let's see. Model class Contact < ActiveRecord::Base ...end Routes map.resources :contacts Controller class ContactsController < ApplicationController ... def show @contact = Contact.find(params[:id] respond_to do |format| format.html format.xml {render :xml => @contact} format.js {render :json => @contact.json} end end ...end So this gives you an API interfaces without the need to define special methods to get the type of respond required Eg. /contacts/1 # Responds with regular html page/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes/contacts/1.js # Responds with json output of Contact.find(1) and its attributes
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5988/" ] }
57,701
It's shown that 'as' casting is much faster than prefix casting, but what about 'is' reflection? How bad is it? As you can imagine, searching for 'is' on Google isn't terribly effective.
There are a few options: The classic cast : Foo foo = (Foo)bar The as cast operator : Foo foo = bar as Foo The is test : bool is = bar is Foo The classic cast needs to check if bar can be safely cast to Foo (quick), and then actually do it (slower), or throw an exception (really slow). The as operator needs to check if bar can be cast, then do the cast, or if it cannot be safely cast, then it just returns null . The is operator just checks if bar can be cast to Foo, and return a boolean . The is test is quick, because it only does the first part of a full casting operation. The as operator is quicker than a classic cast because doesn't throw an exception if the cast fails (which makes it good for situations where you legitimately expect that the cast might fail). If you just need to know if the variable bar is a Foo then use the is operator, BUT , if you're going to test if bar is a Foo , and if so, then cast it , then you should use the as operator. Essentially every cast needs to do the equivalent of an is check internally to begin with, in order to ensure that the cast is valid. So if you do an is check followed by a full cast (either an as cast, or with the classic cast operator) you are effectively doing the is check twice, which is a slight extra overhead.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ] }
57,708
I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type? For example: I get back: &#x01ce; which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value u'\u01ce'
The standard lib’s very own HTMLParser has an undocumented function unescape() which does exactly what you think it does: up to Python 3.4: import HTMLParserh = HTMLParser.HTMLParser()h.unescape('&copy; 2010') # u'\xa9 2010'h.unescape('&#169; 2010') # u'\xa9 2010' Python 3.4+: import htmlhtml.unescape('&copy; 2010') # u'\xa9 2010'html.unescape('&#169; 2010') # u'\xa9 2010'
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/57708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ] }
57,712
What is the best way to get hosting of an ASP.NET MVC application to work on IIS 5 (6 or 7). When I tried to publish my ASP.NET MVC application, all I seemed to get is 404 errors. I've done a bit of googleing and have found a couple of solutions, but neither seem super elegant, and I worry if they will be unusable once I come to use a shared hosting environment for the application. Solution 1 Right-click your application virtual directory on inetmgr.exe. Properties->Virtual Directory Tab-> Configuration. Add a new mapping extension. The extension should be .*, which will be mapped to the Executable C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll, or the appropriate location on your computer (you can simply copy this from the mapping for .aspx files). On the mapping uncheck "check that file exists". 3 X OK and you're good to go. If you want, you can apply this setting to all your web sites. In step1, click on the "Default Web Site" node instead of your own virtual directory, and in step 2 go to the "Home Directory" tab. The rest is the same. It seems a tad hacky to route everything through ASP.NET. Solutions 2 Edit the MVC routing to contain .mvc in the URL and then follow the steps in solution 1 based around this extension. Edit: The original image link was lost, but here it is from Google's Cache:
Answer is here If *.mvc extension is not registered to the hosting , it will give 404 exception. The working way of hosting MVC apps in that case is to modify global.asax routing caluse in the following way. routes.Add(new Route("{controller}.mvc.aspx/{action}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary (new{ controller = "YourController"} ) }); In this way all your controller request will end up in *.mvc.aspx, which is recognized by your hosting. And as the MVC dlls are copied into your local bin , no special setttings need to be done for it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ] }
57,725
Let's say I want a way to display just the the center 50x50px of an image that's 250x250px in HTML. How can I do that. Also, is there a way to do this for css:url() references? I'm aware of clip in CSS, but that seems to only work when used with absolute positioning.
One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/57725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4489/" ] }
57,747
I have to setup team foundation server for a company, something that I don't have any experience in. The company will have about 5 or so developers that will be using it. Is this a big task or something that is fairly easy to do (with instructions)? Any helpful tutorials that you can recommend? Any recommendations on server specs for a team of 5-10?
Your first step should be to download the latest TFS Installation Guide (TFSInstall.chm) from here: http://www.microsoft.com/downloads/details.aspx?FamilyID=FF12844F-398C-4FE9-8B0D-9E84181D9923&displaylang=en You should use TFS 2008 SP1, since it is the latest release and includes many new features and performance improvements. If you are planning on installing with Windows 2008 & SQL 2008, you will need to "integrate" the TFS 2008 SP1 into the installation disc. Instructions are included in the TFSInstall.chm, but Martin Woodward also has a walkthrough on his blog: http://www.woodwardweb.com/vsts/creating_a_tfs.html (This isn't required for SQL 2005 SP2 + Windows 2003) The install guide also has hardware recommendations. For a team of your size, you should also consider running your TFS instance as a Virtual Machine. This will allow you to up-size and move your installation around more easily at a later date. TFS is supported on the Hyper-V virtualization platform: http://blogs.msdn.com/granth/archive/2008/06/27/team-foundation-server-and-hyper-v-virtualization.aspx And if you need help along the way, you have three options: Call up MS product support ($$, but you will get an answer) Post on the official Team Foundation Server - Setup forums: http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=68&SiteID=1 Sign up to the http://OzTFS.com/ mailing list. The people on this list are pretty good at responding to questions almost instantaneously. It's also a great list to join if you just want to "watch" what's happening.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ] }
57,751
I want to find any text in a file that matches a regexp of the form t [A-Z] u (i.e., a match t followed by a capital letter and another match u , and transform the matched text so that the capital letter is lowercase. For example, for the regexp x[A-Z]y xAy becomes xay and xZy becomes xzy Emacs' query-replace function allows back-references, but AFAIK not the transformation of the matched text. Is there a built-in function that does this? Does anybody have a short Elisp function I could use? UPDATE @Marcel Levy has it: \, in a replacement expression introduces an (arbitrary?) Elisp expression. E.g., the solution to the above is M-x replace-regexp <RET> x\([A-Z]\)z <RET> x\,(downcase \1)z
It looks like Steve Yegge actually already posted the answer to this a few years back: "Shiny and New: Emacs 22." Scroll down to "Changing Case in Replacement Strings" and you'll see his example code using the replace-regexp function. The general answer is that you use "\," to call any lisp expression as part of the replacement string, as in \,(capitalize \1) . Reading the help text, it looks like it's only in interactive mode, but that seems like the one place where this would be most necessary.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ] }
57,762
Seems like there are so many different ways of automating one's build/deployment that it becomes difficult to parse through all the different scenarios that people support in tutorials on the web. So I wanted to present the question to the stackoverflow crowd ... what would be the best way to set up an automated build and deployment system using the following configuration: Visual Studio 2008 Web Application Project CruiseControl.NET One of the first things I tried was to have CCnet automatically zip the output and copy it to the server, but then that requires manual work to unzip at the destination. However, if we try to copy all the files individually, then it could potentially take a long time if it's a large application (build server lives outside of the datacenter in our office ... I know). Also of particular interest is how we would support multiple environments as we have dev, qa, uat, and then of course prod. MSDeploy seems really interesting, but unless I'm interpreting the literature incorrectly, doesn't help in the scenario of deploying from the output of a build server. If anything, it seems like it'll be useful in deploying one build across a build farm ... but even for deploying from one environment to another, one would have to manually change config settings and web service URLs, etc.
I recently spent a few days working on automating deployments at my company. We use a combination of CruiseControl, NAnt, MSBuild to generate a release version of the app. Then a separate script uses MSDeploy and XCopy to backup the live site and transfer the new files over. Our solution is briefly described in an answer to this question Automate Deployment for Web Applications?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ] }
57,776
I have a free standing set of files not affiliated with any C# project at all that reside in a complicated nested directory structure. I want to add them in that format to a different directory in an ASP.NET web application I am working on; while retaining the same structure. So, I copied the folder into the target location of my project and I tried to “add existing item” only to lose the previous folder hierarchy. Usually I have re-created the directories by hand, copied across on a one-to-one basis, and then added existing items. There are simply too many directories/items in this case. So how do you add existing directories and files in Visual Studio 2008?
Drag the files / folders from Windows Explorer into the Solution Explorer. It will add them all. Note this doesn't work if Visual Studio is in Administrator Mode, because Windows Explorer is a User Mode process.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/57776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213/" ] }
57,803
How do you convert decimal values to their hexadecimal equivalent in JavaScript?
Convert a number to a hexadecimal string with: hexString = yourNumber.toString(16); And reverse the process with: yourNumber = parseInt(hexString, 16);
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/57803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556/" ] }
57,804
Now, before you say it: I did Google and my hbm.xml file is an Embedded Resource. Here is the code I am calling: ISession session = GetCurrentSession();var returnObject = session.Get<T>(Id); Here is my mapping file for the class: <?xml version="1.0" encoding="utf-8" ?><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true"> <id name="ID" column="ID" unsaved-value="0"> <generator class="identity" /> </id> <property name="Name" column="Name" /> <property name="NumberOfBuckets" column="NumberOfBuckets" /> <property name="SearchCriteriaOne" column="SearchCriteriaOne" /> <bag name="_Businesses" cascade="all"> <key column="SubCategoryId"/> <one-to-many class="HQData.Objects.Business, HQData"/> </bag> <bag name="_Buckets" cascade="all"> <key column="SubCategoryId"/> <one-to-many class="HQData.Objects.Bucket, HQData"/> </bag> </class></hibernate-mapping> Has anyone run to this issue before? Here is the full error message: MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id) in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory() in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e) in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436 Update , here's what the solution for my scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime.
Sounds like you forgot to add a mapping assembly to the session factory configuration.. If you're using app.config... .. <property name="show_sql">true</property> <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property> <mapping assembly="Project.DomainModel"/> <!-- Here --></session-factory>..
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/57804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ] }
57,812
I have a div with id="a" that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works: $("#a").removeClass("bg*");
With jQuery, the actual DOM element is at index zero, this should work $('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/57812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5464/" ] }
57,840
I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code? This is the wrapper that I have which calls GetData() defined in a C++ file: [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl, EntryPoint = "GetData", BestFitMapping = false)] public static extern String GetData(String url); The code is crashing and I want to investigate the root cause. Thanks,Nikhil
Check the Debug tab on your project's properties page. There should be an "Enable unmanaged code debugging" checkbox. This worked for me when we developed a new .NET UI for our old c++ DLLs. If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have the DLL's pdb file handy for the debugging. The other approach is to use the C# exe as the target exe to run from the DLL project, you can then debug your DLL normally.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734/" ] }
57,845
Is it possible to use BackGroundWorker thread in ASP.NET 2.0 for the following scenario, so that the user at the browser's end does not have to wait for long time? Scenario The browser requests a page, say SendEmails.aspx SendEmails.aspx page creates a BackgroundWorker thread, and supplies the thread with enough context to create and send emails. The browser receives the response from the ComposeAndSendEmails.aspx, saying that emails are being sent. Meanwhile, the background thread is engaged in a process of creating and sending emails which could take some considerable time to complete. My main concern is about keeping the BackgroundWorker thread running, trying to send, say 50 emails while the ASP.NET workerprocess threadpool thread is long gone.
If you don't want to use the AJAX libraries, or the e-mail processing is REALLY long and would timeout a standard AJAX request, you can use an AsynchronousPostBack method that was the "old hack" in the .net 1.1 days. Essentially what you do is have your submit button begin the e-mail processing in an asynchronous state, while the user is taken to an intermediate page. The benefit to this is that you can have your intermediate page refresh as much as needed, without worrying about hitting the standard timeouts. When your background process is complete, it will put a little "done" flag in the database/application variable/whatever. When your intermediate page does a refresh of itself, it detects this flag and automatically redirects the user to the "done" page. Again, AJAX makes all of this moot, but if for some reason you have a very intensive or timely process that has to be done over the web, this solution will work for you. I found a nice tutorial on it here and there are plenty more out there. I had to use a process like this when we were working on a "web check-in" type application that was interfacing with a third party application and their import API was hideously slow. EDIT: GAH! Curse you Guzlar and your god-like typing abilities 8^D.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647/" ] }
57,854
How can I close a browser window without receiving the Do you want to close this window prompt? The prompt occurs when I use the window.close(); function.
My friend... there is a way but "hack" does not begin to describe it. You have to basically exploit a bug in IE 6 & 7. Works every time! Instead of calling window.close() , redirect to another page. Opening Page: alert("No whammies!");window.open("closer.htm", '_self'); Redirect to another page. This fools IE into letting you close the browser on this page. Closing Page: <script type="text/javascript"> window.close();</script> Awesome huh?!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5440/" ] }
57,878
If I create an index on columns (A, B, C), in that order, my understanding is that the database will be able to use it even if I search only on (A), or (A and B), or (A and B and C), but not if I search only on (B), or (C), or (B and C). Is this correct?
There are actually three index-based access methods that Oracle can use when a predicate is placed on a non-leading column of an index. i) Index skip-scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#PFGRF10105 ii) Fast full index scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i52044 iii) Index full scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i82107 I've most often seen the fast full index scan "in the wild", but all are possible.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/57878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ] }
57,909
Most restrictions and tricks with windows forms are common to most programmers. But since .NET 3.0 there is also WPF available, the Windows Presentation Foundation. It is said that you can make "sexy applications" more easy with it and with .NET 3.5 SP1 it got a good speed boost on execution. But on the other side a lot of things are working different with WPF. I will not say it is more difficult but you have to learn "everything" from scratch. My question: Is it worth to spend this extra time when you have to create a new GUI and there is no time pressure for the project?
WPF enables you to do some amazing things, and I LOVE it... but I always feel obligated to qualify my recommendations, whenever developers ask me whether I think they should be moving to the new technology. Are your developers willing (preferrably, EAGER) to spend the time it takes to learn to use WPF effectively? I never would have thought to say this about MFC, or Windows Forms, or even unmanaged DirectX, but you probably do NOT want a team trying to "pick up" WPF over the course of a normal dev. cycle for a shipping product! Do at least one or two of your developers have some design sensibilities, and do individuals with final design authority have a decent understanding of development issues, so you can leverage WPF capabilities to create something which is actually BETTER, instead of just more "colorful", featuring gratuitous animation? Does some percentage of your target customer base run on integrated graphics chip sets that might not support the features you were planning -- or are they still running Windows 2000, which would eliminate them as customers altogether? Some people would also ask whether your customers actually CARE about enhanced visuals but, having lived through internal company "Our business customers don't care about colors and pictures" debates in the early '90s, I know that well-designed solutions from your competitors will MAKE them care, and the real question is whether the conditions are right, to enable you to offer something that will make them care NOW. Does the project involve grounds-up development, at least for the presentation layer, to avoid the additional complexity of trying to hook into incompatible legacy scaffolding (Interop with Win Forms is NOT seamless)? Can your manager accept (or be distracted from noticing) a significant DROP in developer productivity for four to six months? This last issue is due to what I like to think of as the "FizzBin" nature of WPF, with ten different ways to implement any task, and no apparent reason to prefer one approach to another, and little guidance available to help you make a choice. Not only will the shortcomings of whatever choice you make become clear only much later in the project, but you are virtually guaranteed to have every developer on your project adopting a different approach, resulting in a major maintenance headache. Most frustrating of all are the inconsistencies that constantly trip you up, as you try to learn the framework. You can find more in-depth WPF-related information in an entry on my blog: http://missedmemo.com/blog/2008/09/13/WPFTheFizzBinAPI.aspx
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/57909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5703/" ] }
57,918
We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner: SELECT * FROM customer WHERE fname LIKE '%someName%' Does full-text indexing help in the scenario? We're using SQL Server 2005.
It will depend upon your DBMS. I believe that most systems will not take advantage of the full-text index unless you use the full-text functions. (e.g. MATCH/AGAINST in mySQL or FREETEXT/CONTAINS in MS SQL) Here is two good articles on when, why, and how to use full-text indexing in SQL Server: How To Use SQL Server Full-Text Searching Solving Complex SQL Problems with Full-Text Indexing
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ] }
57,923
I've been writing C / C++ code for almost twenty years, and I know Perl, Python, PHP, and some Java as well, and I'm teaching myself JavaScript. But I've never done any .NET, VB, or C# stuff. What exactly does managed code mean? Wikipedia describes it simply as Code that executes under the management of a virtual machine and it specifically says that Java is (usually) managed code, so why does the term only seem to apply to C# / .NET? Can you compile C# into a .exe that contains the VM as well, or do you have to package it up and give it to another .exe (a la java)? In a similar vein, is .NET a language or a framework , and what exactly does "framework" mean here? OK, so that's more than one question, but for someone who's been in the industry as long as I have, I'm feeling rather N00B-ish right now...
When you compile C# code to a .exe, it is compiled to Common Intermediate Language(CIL) bytecode. Whenever you run a CIL executable it is executed on Microsofts Common Language Runtime(CLR) virtual machine. So no, it is not possible to include the VM withing your .NET executable file. You must have the .NET runtime installed on any client machines where your program will be running. To answer your second question, .NET is a framework, in that it is a set of libraries, compilers and VM that is not language specific. So you can code on the .NET framework in C#, VB, C++ and any other languages which have a .NET compiler. https://bitbucket.org/brianritchie/wiki/wiki/.NET%20Languages The above page has a listing of languages which have .NET versions, as well as links to their pages.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/57923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821/" ] }
57,999
I'm just looking for a simple, concise explanation of the difference between these two. MSDN doesn't go into a hell of a lot of detail here.
__declspec(dllexport) tells the linker that you want this object to be made available for other DLL's to import. It is used when creating a DLL that others can link to. __declspec(dllimport) imports the implementation from a DLL so your application can use it. I'm only a novice C/C++ developer, so perhaps someone's got a better explanation than I.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/57999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ] }
58,000
We have a recurring problem at my company with build breaks in our Flex projects. The problem primarily occurs because the build that the developers do on their local machines is fundamentally different from the build that occurs on the build machine. The devs are building the projects using FlexBuilder/eclipse and the build machine is using the command line compilers. Inevitably, the {projectname}-config.xml and/or the batch file that runs the build get out of sync with the project files used by eclipse, so the the build succeeds on the dev's machine, but fails on the build machine. We started down the path of writing a utility program to convert FlexBuilder's project files into a {projectname}-config.xml file, but it's a) undocumented and b) a horrible hack. I've looked into the -dump-config switch to get the config files, but this has a couple of problems: 1) The generated config file has absolute paths which doesn't work in our environment (some developers use macs, some windows machines), and 2) only works right when run from the IDE, so can't be build into the build process. Tomorrow, we are going to discuss a couple of options, neither of which I'm terribly fond of: a) Add a post check-in event to Subversion to remove these absolute references, or b) add a pre-build process that removes the absolute reference. I can't believe that we are the first group of developers to run across this issue, but I can't find any good solutions on Google. How have other groups dealt with this problem?
__declspec(dllexport) tells the linker that you want this object to be made available for other DLL's to import. It is used when creating a DLL that others can link to. __declspec(dllimport) imports the implementation from a DLL so your application can use it. I'm only a novice C/C++ developer, so perhaps someone's got a better explanation than I.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946325/" ] }
58,024
I'm trying to provide a link to my company's website from a Windows Form. I want to be well behaved and launch using the user's preferred browser. What is the best way to open a URL in the user's default browser from a Windows Forms application?
This article will walk you through it. Short answer: ProcessStartInfo sInfo = new ProcessStartInfo("http://mysite.com/"); Process.Start(sInfo);
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/58024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148/" ] }
58,054
I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.
Here is a solution I found. It doesn't seem very elegant, though: <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><% pageContext.setAttribute("newLineChar", "\n"); %>${fn:replace(item.comments, newLineChar, "; ")}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027/" ] }
58,058
I'm trying to write a small class library for a C++ course. I was wondering if it was possible to define a set of classes in my shared object and then using them directly in my main program that demos the library. Are there any tricks involved? I remember reading this long ago (before I started really programming) that C++ classes only worked with MFC .dlls and not plain ones, but that's just the windows side.
C++ classes work fine in .so shared libraries (they also work in non-MFC DLLs on Windows, but that's not really your question). It's actually easier than Windows, because you don't have to explicitly export any symbols from the libraries. This document will answer most of your questions: http://people.redhat.com/drepper/dsohowto.pdf The main things to remember are to use the -fPIC option when compiling, and the -shared option when linking. You can find plenty of examples on the net.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5387/" ] }
58,119
I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are?
Well, re.compile certainly may: >>> import re>>> re.compile('he(lo')Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python25\lib\re.py", line 180, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 233, in _compile raise error, v # invalid expressionsre_constants.error: unbalanced parenthesis The documentation does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the error exception. Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to decompile them (if written in Python) or even look at the source , if they're in the standard library.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ] }
58,123
This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object? And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface: private IWebBase FindWebBase(){ if (HttpContext.Current as IWebBase != null) { return (IWebBase)HttpContext.Current.; } throw new NotImplementedException("Crawling for IWebBase not implemented yet");} The general context is that some controls need to know whether they are executing as a SharePoint webpart, or as part of an Asp.Net framework. I have solved the problem by requiring the control to pass a reference to itself, and checking the Page property of the control, but I'm still curious why the above does not work. The compiler error is:Cannot convert System.Web.HttpContext to ...IWebBase via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion.
No, from MSDN on HttpContext.Current: "Gets or sets the HttpContext object for the current HTTP request." In other words it is an HttpContext object, not a Page. You can get to the Page object via HttpContext using: Page page = HttpContext.Current.Handler as Page;if (page != null){ // Use page instance.}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/58123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1685/" ] }
58,141
I knew of some performance reasons back in the SQL 7 days, but do the same issues still exist in SQL Server 2005? If I have a resultset in a stored procedure that I want to act upon individually, are cursors still a bad choice? If so, why?
Because cursors take up memory and create locks. What you are really doing is attempting to force set-based technology into non-set based functionality. And, in all fairness, I should point out that cursors do have a use, but they are frowned upon because many folks who are not used to using set-based solutions use cursors instead of figuring out the set-based solution. But, when you open a cursor, you are basically loading those rows into memory and locking them, creating potential blocks. Then, as you cycle through the cursor, you are making changes to other tables and still keeping all of the memory and locks of the cursor open. All of which has the potential to cause performance issues for other users. So, as a general rule, cursors are frowned upon. Especially if that's the first solution arrived at in solving a problem.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/58141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
58,174
I'm obviously not talking about a full solution, but just a good starting point for common applications for software architects. It could be for a CMS, e-commerce storefront, address book, etc. A UML diagram is not essential, but a table schema with data types in the least. Thanks!
Check out the Library of Free Data Models from DatabaseAnswers.org -- might be a good starting point. I can't vouch for the quality, but there is a lot here...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
58,190
My current view is no, prefer Transact SQL stored procedures because they are a lighter weight and (possibly) higher performing option, while CLR procedures allow developers to get up to all sorts of mischief. However recently I have needed to debug some very poorly written TSQL stored procs. As usual I found many of the problems due to the original developer developer having no real TSQL experience, they were ASP.NET / C# focused. So, using CLR procedures would firstly provide a much more familiar toolset to this type of developer, and secondly, the debugging and testing facilities are more powerful (ie Visual Studio instead of SQL Management Studio). I'd be very interested in hearing your experience as it's seems it is not a simple choice.
There are places for both well-written, well-thought-out T-SQL and CLR. If some function is not called frequently and if it required extended procedures in SQL Server 2000, CLR may be an option. Also running things like calculation right next to the data may be appealing. But solving bad programmers by throwing in new technology sounds like a bad idea.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5023/" ] }
58,207
To create a playlist for all of the music in a folder, I am using the following command in bash: ls > list.txt I would like to use the result of the pwd command for the name of the playlist. Something like: ls > ${pwd}.txt That doesn't work though - can anyone tell me what syntax I need to use to do something like this? Edit: As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!
The best way to do this is with "$(command substitution)" (thanks, Landon ): ls > "$(pwd).txt" You will sometimes also see people use the older backtick notation, but this has several drawbacks in terms of nesting and escaping: ls > "`pwd`.txt" Note that the unprocessed substitution of pwd is an absolute path, so the above command creates a file with the same name in the same directory as the working directory, but with a .txt extension. Thomas Kammeyer pointed out that the basename command strips the leading directory, so this would create a text file in the current directory with the name of that directory: ls > "$(basename "$(pwd)").txt" Also thanks to erichui for bringing up the problem of spaces in the path.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/58207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840/" ] }
58,245
I've got a menu that contains, among other things, some most-recently-used file paths. The paths to these files can be long, so the text sometimes gets clipped like "C:\Progra...\foo.txt" I'd like to pop a tooltip with the full path when the user hovers over the item, but this doesn't seem possible with the Tooltip class in .NET 2.0. Am I missing something obvious?
If you are creating your menu items using the System.Windows.Forms.MenuItem class you won't have a "ToolTipText" property. You should use the System.Windows.Forms.ToolStripMenuItem class which is new as of .Net Framework 2.0 and DOES include the "ToolTipText" property. You also have to remember to specify ShowItemToolTips = True on the MenuStrip control
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773/" ] }
58,280
Is it possible to use an UnhandledException Handler in a Windows Service? Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesn’t achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points: Protected Overrides Sub OnStart(ByVal args() As String) ' Add code here to start your service. This method should set things ' in motion so your service can do its work. Try MyServiceComponent.Start() Catch ex As Exception 'call into our exception handler MyExceptionHandlingComponent.ManuallyHandleException (ex) 'zero is the default ExitCode for a successfull exit, so if we set it to non-zero ExitCode = -1 'So, we use Environment.Exit, it seems to be the most appropriate thing to use 'we pass an exit code here as well, just in case. System.Environment.Exit(-1) End Try End Sub Is there a way my Custom Exception Handling component can deal with this better so I don't have to fill my OnStart with messy exception handling plumbing?
Ok, I’ve done a little more research into this now.When you create a windows service in .Net, you create a class that inherits from System.ServiceProcess.ServiceBase (In VB this is hidden in the .Designer.vb file). You then override the OnStart and OnStop function, and OnPause and OnContinue if you choose to. These methods are invoked from within the base class so I did a little poking around with reflector.OnStart is invoked by a method in System.ServiceProcess.ServiceBase called ServiceQueuedMainCallback. The vesion on my machine "System.ServiceProcess, Version=2.0.0.0" decompiles like this: Private Sub ServiceQueuedMainCallback(ByVal state As Object) Dim args As String() = DirectCast(state, String()) Try Me.OnStart(args) Me.WriteEventLogEntry(Res.GetString("StartSuccessful")) Me.status.checkPoint = 0 Me.status.waitHint = 0 Me.status.currentState = 4 Catch exception As Exception Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { exception.ToString }), EventLogEntryType.Error) Me.status.currentState = 1 Catch obj1 As Object Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { String.Empty }), EventLogEntryType.Error) Me.status.currentState = 1 End Try Me.startCompletedSignal.SetEnd Sub So because Me.OnStart(args) is called from within the Try portion of a Try Catch block I assume that anything that happens within the OnStart method is effectively wrapped by that Try Catch block and therefore any exceptions that occur aren't technically unhandled as they are actually handled in the ServiceQueuedMainCallback Try Catch. So CurrentDomain.UnhandledException never actually happens at least during the startup routine. The other 3 entry points (OnStop, OnPause and OnContinue) are all called from the base class in a similar way. So I ‘think’ that explains why my Exception Handling component can’t catch UnhandledException on Start and Stop, but I’m not sure if it explains why timers that are setup in OnStart can’t cause an UnhandledException when they fire.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6042/" ] }
58,305
Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?
Believe it or not, you can actually use java.awt.Robot to "create an image containing pixels read from the screen." You can then write that image to a file on disk. I just tried it, and the whole thing ends up like: Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());BufferedImage capture = new Robot().createScreenCapture(screenRect);ImageIO.write(capture, "bmp", new File(args[0])); NOTE: This will only capture the primary monitor. See GraphicsConfiguration for multi-monitor support.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/58305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ] }
58,306
I am trying to determine the best time efficient algorithm to accomplish the task described below. I have a set of records. For this set of records I have connection data which indicates how pairs of records from this set connect to one another. This basically represents an undirected graph, with the records being the vertices and the connection data the edges. All of the records in the set have connection information (i.e. no orphan records are present; each record in the set connects to one or more other records in the set). I want to choose any two records from the set and be able to show all simple paths between the chosen records. By "simple paths" I mean the paths which do not have repeated records in the path (i.e. finite paths only). Note: The two chosen records will always be different (i.e. start and end vertex will never be the same; no cycles). For example: If I have the following records: A, B, C, D, E and the following represents the connections: (A,B),(A,C),(B,A),(B,D),(B,E),(B,F),(C,A),(C,E), (C,F),(D,B),(E,C),(E,F),(F,B),(F,C),(F,E) [where (A,B) means record A connects to record B] If I chose B as my starting record and E as my ending record, I would want to find all simple paths through the record connections that would connect record B to record E. All paths connecting B to E: B->E B->F->E B->F->C->E B->A->C->E B->A->C->F->E This is an example, in practice I may have sets containing hundreds of thousands of records.
It appears that this can be accomplished with a depth-first search of the graph. The depth-first search will find all non-cyclical paths between two nodes. This algorithm should be very fast and scale to large graphs (The graph data structure is sparse so it only uses as much memory as it needs to). I noticed that the graph you specified above has only one edge that is directional (B,E). Was this a typo or is it really a directed graph? This solution works regardless. Sorry I was unable to do it in C, I'm a bit weak in that area. I expect that you will be able to translate this Java code without too much trouble though. Graph.java: import java.util.HashMap;import java.util.LinkedHashSet;import java.util.LinkedList;import java.util.Map;import java.util.Set;public class Graph { private Map<String, LinkedHashSet<String>> map = new HashMap(); public void addEdge(String node1, String node2) { LinkedHashSet<String> adjacent = map.get(node1); if(adjacent==null) { adjacent = new LinkedHashSet(); map.put(node1, adjacent); } adjacent.add(node2); } public void addTwoWayVertex(String node1, String node2) { addEdge(node1, node2); addEdge(node2, node1); } public boolean isConnected(String node1, String node2) { Set adjacent = map.get(node1); if(adjacent==null) { return false; } return adjacent.contains(node2); } public LinkedList<String> adjacentNodes(String last) { LinkedHashSet<String> adjacent = map.get(last); if(adjacent==null) { return new LinkedList(); } return new LinkedList<String>(adjacent); }} Search.java: import java.util.LinkedList;public class Search { private static final String START = "B"; private static final String END = "E"; public static void main(String[] args) { // this graph is directional Graph graph = new Graph(); graph.addEdge("A", "B"); graph.addEdge("A", "C"); graph.addEdge("B", "A"); graph.addEdge("B", "D"); graph.addEdge("B", "E"); // this is the only one-way connection graph.addEdge("B", "F"); graph.addEdge("C", "A"); graph.addEdge("C", "E"); graph.addEdge("C", "F"); graph.addEdge("D", "B"); graph.addEdge("E", "C"); graph.addEdge("E", "F"); graph.addEdge("F", "B"); graph.addEdge("F", "C"); graph.addEdge("F", "E"); LinkedList<String> visited = new LinkedList(); visited.add(START); new Search().depthFirst(graph, visited); } private void depthFirst(Graph graph, LinkedList<String> visited) { LinkedList<String> nodes = graph.adjacentNodes(visited.getLast()); // examine adjacent nodes for (String node : nodes) { if (visited.contains(node)) { continue; } if (node.equals(END)) { visited.add(node); printPath(visited); visited.removeLast(); break; } } for (String node : nodes) { if (visited.contains(node) || node.equals(END)) { continue; } visited.addLast(node); depthFirst(graph, visited); visited.removeLast(); } } private void printPath(LinkedList<String> visited) { for (String node : visited) { System.out.print(node); System.out.print(" "); } System.out.println(); }} Program Output: B E B A C E B A C F E B F E B F C E
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/58306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3534/" ] }
58,340
Using win forms with an MVC / MVP architecture, I would normally use a class to wrap a view to test the UI while using mocks for the model and controller/presenter. The wrapper class would make most everything in the UI an observable property for the test runner through properties and events. Would this be a viable approach to testing a WPF app? Is there a better way? Are there any gotchas to watch out for?
As for the testing itself, you're probably best off using the UI Automation framework. Or if you want a more fluent and wpf/winforms/win32/swt-independent way of using the framework, you could download White from Codeplex (provided that you're in a position to use open source code in your environment). For the gotchas; If you're trying to test your views, you will probably run in to some threading issues. For instance, if you're running NUnit the default testrunner will run in MTA (Multi-Threaded Appartment), while as WPF needs to run as STA (Single-threaded Appartment). Mike Two has a real easy getting-started on unit testing WPF, but without considering the threading issue. Josh Smith has some thoughts on the threading issue in this post , and he also points to this article by Chris Hedgate. Chris uses a modified version of Peter Provost's CrossThreadTestRunner to wrap the MTA/STA issues in a bit more friendly way.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3826/" ] }
58,354
What are some simple algorithm or data structure related "white boarding" problems that you find effective during the candidate screening process? I have some simple ones that I use to validate problem solving skills and that can be simply expressed but have some opportunity for the application of some heuristics. One of the basics that I use for junior developers is: Write a C# method that takes a string which contains a set of words (a sentence) and rotates those words X number of places to the right. When a word in the last position of the sentence is rotated it should show up at the front of the resulting string. When a candidate answers this question I look to see that they available .NET data structures and methods (string.Join, string.Split, List, etc...) to solve the problem. I also look for them to identify special cases for optimization. Like the number of times that the words need to be rotated isn't really X it's X % number of words. What are some of the white board problems that you use to interview a candidate and what are some of the things you look for in an answer (do not need to post the actual answer).
I enjoy the classic "what's the difference between a LinkedList and an ArrayList (or between a linked list and an array/vector) and why would you choose one or the other?" The kind of answer I hope for is one that includes discussion of: insertion performance iteration performance memory allocation/reallocation impact impact of removing elements from the beginning/middle/end how knowing (or not knowing) the maximum size of the list can affect the decision
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ] }
58,380
The following bit of code catches the EOS Exception using (var reader = new BinaryReader(httpRequestBodyStream)) { try { while (true) { bodyByteList.Add(reader.ReadByte()); } } catch (EndOfStreamException) { }} So why do I still receive first-chance exceptions in my console? A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll Is there a way to hide these first chance exception messages?
To avoid seeing the messages, right-click on the output window and uncheck "Exception Messages". However, seeing them happen might be nice, if you're interested in knowing when exceptions are thrown without setting breakpoints and reconfiguring the debugger.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/58380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ] }
58,425
I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException". The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception." Here is my app.xaml: <Application x:Class="MyNamespace.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Application.Resources> </Application.Resources></Application> And here is my app.xaml.cs (exception thrown at "public App()"): public partial class App : Application{ public App() { Bootstrapper bootStrapper = new Bootstrapper(); bootStrapper.Run(); }} I have set the "App" class as the startup object in the project. What is going astray?
Thanks @ima, your answer pointed me in the right direction. I was using an app.config file and it contained this: <configuration> <startup> <supportedRuntime version="v2.0.50727" sku="Client"/> </startup> <configSections> <section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/> </configSections> <modules> <module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/> </modules></configuration> It seems the problem was the <startup> element because when I removed it the application ran fine. I was confused because Visual Studio 2008 added that when I checked the box to utilise the "Client Profile" available in 3.5 SP1. After some mucking about checking and un-checking the box I ended up with a configuration file like this: <configuration> <configSections> <section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/> </configSections> <modules> <module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/> </modules> <startup> <supportedRuntime version="v2.0.50727" sku="Client"/> </startup></configuration> Which works! I'm not sure why the order of elements in the app.config is important - but it seems it is.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148/" ] }
58,457
How do you randomly select a table row in T-SQL based on an applied weight for all candidate rows? For example, I have a set of rows in a table weighted at 50, 25, and 25 (which adds up to 100 but does not need to), and I want to select one of them randomly with a statistical outcome equivalent to the respective weight.
Dane's answer includes a self joins in a way that introduces a square law. (n*n/2) rows after the join where there are n rows in the table. What would be more ideal is to be able to just parse the table once. DECLARE @id int, @weight_sum int, @weight_point intDECLARE @table TABLE (id int, weight int)INSERT INTO @table(id, weight) VALUES(1, 50)INSERT INTO @table(id, weight) VALUES(2, 25)INSERT INTO @table(id, weight) VALUES(3, 25)SELECT @weight_sum = SUM(weight)FROM @tableSELECT @weight_point = FLOOR(((@weight_sum - 1) * RAND() + 1))SELECT @id = CASE WHEN @weight_point < 0 THEN @id ELSE [table].id END, @weight_point = @weight_point - [table].weightFROM @table [table]ORDER BY [table].Weight DESC This will go through the table, setting @id to each record's id value while at the same time decrementing @weight point. Eventually, the @weight_point will go negative. This means that the SUM of all preceding weights is greater than the randomly chosen target value. This is the record we want, so from that point onwards we set @id to itself (ignoring any IDs in the table). This runs through the table just once, but does have to run through the entire table even if the chosen value is the first record. Because the average position is half way through the table (and less if ordered by ascending weight) writing a loop could possibly be faster... (Especially if the weightings are in common groups): DECLARE @id int, @weight_sum int, @weight_point int, @next_weight int, @row_count intDECLARE @table TABLE (id int, weight int)INSERT INTO @table(id, weight) VALUES(1, 50)INSERT INTO @table(id, weight) VALUES(2, 25)INSERT INTO @table(id, weight) VALUES(3, 25)SELECT @weight_sum = SUM(weight)FROM @tableSELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)SELECT @next_weight = MAX(weight) FROM @tableSELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weightSET @weight_point = @weight_point - (@next_weight * @row_count)WHILE (@weight_point > 0)BEGIN SELECT @next_weight = MAX(weight) FROM @table WHERE weight < @next_weight SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight SET @weight_point = @weight_point - (@next_weight * @row_count)END-- # Once the @weight_point is less than 0, we know that the randomly chosen record-- # is in the group of records WHERE [table].weight = @next_weightSELECT @row_count = FLOOR(((@row_count - 1) * RAND() + 1))SELECT @id = CASE WHEN @row_count < 0 THEN @id ELSE [table].id END, @row_count = @row_count - 1FROM @table [table]WHERE [table].weight = @next_weightORDER BY [table].Weight DESC
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2929/" ] }
58,482
I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet: foo = ["goo", "baz"] How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)? Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this: [foo, goo, bar].each { |param| if param.class != Array puts "param_name wasn't an Array. It was a/an #{param.class}" return "Error: param_name wasn't an Array" end } My question is then: Can I replace the instances of 'param_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala dbr's answer )
What if you turn your problem around? Instead of trying to get names from variables, get the variables from the names: ["foo", "goo", "bar"].each { |param_name| param = eval(param_name) if param.class != Array puts "#{param_name} wasn't an Array. It was a/an #{param.class}" return "Error: #{param_name} wasn't an Array" end } If there were a chance of one the variables not being defined at all (as opposed to not being an array), you would want to add "rescue nil" to the end of the "param = ..." line to keep the eval from throwing an exception...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ] }
58,484
In SEO people talk a lot about Google PageRank . It's kind of a catch 22 because until your site is actually big and you don't really need search engines as much, it's unlikely that big sites will link to you and increase your PageRank! I've been told that it's easiest to simply get a couple high quality links to point to a site to raise it's PageRank. I've also been told that there are certain Open Directories like dmoz.org that Google pays special attention to (since they're human managed links). Can anyone speak to the validity of this or suggest another site/technique to increase a site's PageRank?
Have great content Nothing helps your google rank more than having content or offering a service people are interested in. If your web site is better than the competition and solves a real need you will naturally generate more traffic and inbound links. Keep your content fresh Use friendly url's that contain keywords Good : http://cars.com/products/cars/ford/focus/ Bad : http://cars.com/p?id=1232 Make sure the page title is relevant and well constructed For example : Buy A House In France :. Property Purchasing in France Use a domain name that describes your site Good : http://cars.com/ Bad : http://somerandomunrelateddomainname.com/ Example Type car into Google, out of the top 5 links all 4 have car in the domain: http://www.google.co.uk/search?q=car Make it accessible Make sure people can read your content. This includes a variety of different audiences People with disabilities: Sight, motor, cognitive disabilities etc.. Search bots In particular make sure search bots can read every single relevant page on your site. Quite often search bots get blocked by the use of javascript to link between pages or the use of frames / flash / silverlight . One easy way to do this is have a site map page that gives access to the whole site, dividing it into categories / sub categories etc.. Down level browsers Submit your site map automatically Most search engines allow you to submit a list of pages on your site including when they were last updated. Google: https://www.google.com/webmasters/tools/docs/en/about.html Inbound links Generate as much buzz about your website as possible, to increase the likely hood of people linking to you. Blog / podcast about your website if appropriate. List it in online directories (if appropriate). References Google Search Engine Ranking Factors, by an SEO company Creating a Google-friendly site: Best practices Wikipedia - Search engine optimization
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5642/" ] }