source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
29,044 | Consider the need to develop a lightweight desktop DB application on the Microsoft platforms. It could be done fairly easily with MS Access but I'd like to be able to distribute it to others and I don't want to pay for a runtime license. Requirements: easy distribution to others no runtime licensing issues Considerations and Candidates: Base from the OpenOffice suite . My concerns were around its stability. MySQL + writing custom DB code in C++ or Python or whatever seems like a rather heavy-handed solution. Question : What are the low cost or free database alternatives to MS Access? See Also: Open Source Reporting Engines @Schnapple Bruceatk kind of hit on what I'm thinking of; it's not so much the DB engine as I want the other niceties that Access brings to the party. The nice form designer, the nice reporting engine etc. But you do raise a very good point about the installation footprint. I had considered that but I've not made any firm decisions about which way I'm going with this yet anyway. It'll probably be something fairly lightweight anyway and a small installation footprint would definitely be a plus. @Remou, No I was unaware that the MS Access 2007 runtime is free; thanks for pointing that out. The last time I'd bothered to investigate it (I don't remember when it was) I think it was a fairly expensive license for the runtime because I think they were trying to sell it to Corporate IT departments. And thanks to everyone else who responded as well; I was completely unaware of those other options you all pointed out. | One thing to keep in mind here is the MS Access product is much more than just the raw database engine. It provides a full application development platform, including form and menu designer, client application language and environment (VBA), and report designer. When you take all those things together, MS Access really has no peer. But for the scope of this question, we're concerned with the raw database engine. With that in mind: SQLlite , Firebird , VistaDB (not free), SQL Server Compact Edition (not Express) and now SQL Server LocalDB all come to mind. Another thought: while the original question does ask about desktop databases, its likely some people will land here looking for a database to use with a web site. It's important to remember that these are all in-process databases, and as such are rarely if ever appropriate for use on the web. If you want to build a web site, where it's common to need to support significant concurrent access, you generally want a database server engine, like MS SQL, Postgresql, MySQL, Oracle, or their brethren. At the same time, those server engines are rarely if ever appropriate for a single-user desktop application. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/29044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820/"
]
} |
29,061 | When I try to use an ssh command in a shell script, the command just sits there. Do you have an example of how to use ssh in a shell script? | Depends on what you want to do, and how you use it. If you just want to execute a command remotely and safely on another machine, just use ssh user@host command for example ssh user@host ls In order to do this safely you need to either ask the user for the password during runtime, or set up keys on the remote host. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
]
} |
29,099 | Since debate without meaningful terms is meaningless , I figured I would point at the elephant in the room and ask: What exactly makes a language "object-oriented"? I'm not looking for a textbook answer here, but one based on your experiences with OO languages that work well in your domain, whatever it may be. A related question that might help to answer first is: What is the archetype of object-oriented languages and why? | Definitions for Object-Orientation are of course a huge can of worms , but here are my 2 cents: To me, Object-Orientation is all about objects that collaborate by sending messages. That is, to me, the single most important trait of an object-oriented language. If I had to put up an ordered list of all the features that an object-oriented language must have, it would look like this: Objects sending messages to other objects Everything is an Object Late Binding Subtype Polymorphism Inheritance or something similarly expressive, like Delegation Encapsulation Information Hiding Abstraction Obviously, this list is very controversial, since it excludes a great variety of languages that are widely regarded as object-oriented, such as Java , C# and C++ , all of which violate points 1, 2 and 3. However, there is no doubt that those languages allow for object-oriented programming (but so does C ) and even facilitate it (which C doesn't). So, I have come to call languages that satisfy those requirements "purely object-oriented". As archetypical object-oriented languages I would name Self and Newspeak . Both satisfy the above-mentioned requirements. Both are inspired by and successors to Smalltalk , and both actually manage to be "more OO" in some sense. The things that I like about Self and Newspeak are that both take the message sending paradigm to the extreme (Newspeak even more so than Self). In Newspeak, everything is a message send. There are no instance variables, no fields, no attributes, no constants, no class names. They are all emulated by using getters and setters. In Self, there are no classes , only objects. This emphasizes, what OO is really about: objects, not classes. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3121/"
]
} |
29,104 | How do you go about the requirements gathering phase? Does anyone have a good set of guidelines or tips to follow? What are some good questions to ask the stakeholders? I am currently working on a new project and there are a lot of unknowns. I am in the process of coming up with a list of questions to ask the stakeholders. However I cant help but to feel that I am missing something or forgetting to ask a critical question. | You're almost certainly missing something. A lot of things, probably. Don't worry, it's ok. Even if you remembered everything and covered all the bases stakeholders aren't going to be able to give you very good, clear requirements without any point of reference. The best way to do this sort of thing is to get what you can from them now, then take that and give them something to react to. It can be a paper prototype, a mockup, version 0.1 of the software, whatever. Then they can start telling you what they really want. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1375/"
]
} |
29,107 | Can anyone suggest a good implementation of a generic collection class that implements the IBindingListView & IBindingList interfaces and provides Filtering and Searching capabilities? I see my current options as: Using a class that someone else has written and tested Inheriting from BindingList<T> , and implementing the IBindingListView interfaces Write a custom collection from scratch, implementing IBindingListView and IBindingList . Obviously, the first option is my preferred choice. | I used and built upon an implementation I found on and old MSDN forum post from a few years ago, but recently I searched around again and found a sourceforge project called BindingListView . It looks pretty nice, I just haven't pulled it in to replace my hacked version yet. nuget package: Equin.ApplicationFramework.BindingListView Example code: var lst = new List<DemoClass>{ new DemoClass { Prop1 = "a", Prop2 = "b", Prop3 = "c" }, new DemoClass { Prop1 = "a", Prop2 = "e", Prop3 = "f" }, new DemoClass { Prop1 = "b", Prop2 = "h", Prop3 = "i" }, new DemoClass { Prop1 = "b", Prop2 = "k", Prop3 = "l" }};dataGridView1.DataSource = new BindingListView<DemoClass>(lst);// you can now sort by clicking the column headings //// to filter the view...var view = (BindingListView<DemoClass>)dataGridView1.DataSource; view.ApplyFilter(dc => dc.Prop1 == "a"); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
]
} |
29,142 | This is a follow-on question to the How do you use ssh in a shell script? question. If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return? When I try to just include the ampersand (&) at the end of the command it just hangs. The exact form of the command looks like this: ssh user@target "cd /some/directory; program-to-execute &" Any ideas? One thing to note is that logins to the target machine always produce a text banner and I have SSH keys set up so no password is required. | I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on nohup , copied here for your convenience. Nohuping backgrounded jobs is for example useful when logged in via SSH, since backgrounded jobs can cause the shell to hang on logout due to a race condition [2]. This problem can also be overcome by redirecting all three I/O streams: nohup myprogram > foo.out 2> foo.err < /dev/null & | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/29142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/171/"
]
} |
29,155 | What are the differences between delegates and an events? Don't both hold references to functions that can be executed? | An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/29155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
]
} |
29,157 | I am using StretchImage because the box is resizable with splitters. It looks like the default is some kind of smooth bilinear filtering, causing my image to be blurry and have moire patterns. | I needed this functionality also. I made a class that inherits PictureBox, overrides OnPaint and adds a property to allow the interpolation mode to be set: using System.Drawing.Drawing2D;using System.Windows.Forms;/// <summary>/// Inherits from PictureBox; adds Interpolation Mode Setting/// </summary>public class PictureBoxWithInterpolationMode : PictureBox{ public InterpolationMode InterpolationMode { get; set; } protected override void OnPaint(PaintEventArgs paintEventArgs) { paintEventArgs.Graphics.InterpolationMode = InterpolationMode; base.OnPaint(paintEventArgs); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
]
} |
29,168 | My master branch layout is like this: / <-- top level /client <-- desktop client source files /server <-- Rails app What I'd like to do is only pull down the /server directory in my deploy.rb , but I can't seem to find any way to do that. The /client directory is huge, so setting up a hook to copy /server to / won't work very well, it needs to only pull down the Rails app. | Without any dirty forking action but even dirtier ! In my config/deploy.rb : set :deploy_subdir, "project/subdir" Then I added this new strategy to my Capfile : require 'capistrano/recipes/deploy/strategy/remote_cache'class RemoteCacheSubdir < Capistrano::Deploy::Strategy::RemoteCache private def repository_cache_subdir if configuration[:deploy_subdir] then File.join(repository_cache, configuration[:deploy_subdir]) else repository_cache end end def copy_repository_cache logger.trace "copying the cached version to #{configuration[:release_path]}" if copy_exclude.empty? run "cp -RPp #{repository_cache_subdir} #{configuration[:release_path]} && #{mark}" else exclusions = copy_exclude.map { |e| "--exclude=\"#{e}\"" }.join(' ') run "rsync -lrpt #{exclusions} #{repository_cache_subdir}/* #{configuration[:release_path]} && #{mark}" end endendset :strategy, RemoteCacheSubdir.new(self) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/29168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/574/"
]
} |
29,174 | I'm using jQuery and SimpleModal in an ASP.Net project to make some nice dialogs for a web app. Unfortunately, any buttons in a modal dialog can no longer execute their postbacks, which is not really acceptable. There is one source I've found with a workaround , but for the life of me I can't get it to work, mostly because I am not fully understanding all of the necessary steps. I also have a workaround, which is to replace the postbacks, but it's ugly and probably not the most reliable. I would really like to make the postbacks work again. Any ideas? UPDATE: I should clarify, the postbacks are not working because the Javascript used to execute the post backs has broken in some way, so nothing happens at all when the button is clicked. | Both of you were on the right track. What I realized is that SimpleModal appends the dialog to the body, which is outside ASP.Net's <form> , which breaks the functionality, since it can't find the elements. To fix it, I just modified the SimpleModal source to append eveything to 'form' instead of 'body' . When I create the dialog, I also use the persist: true option, to make sure the buttons stay through opening and closing. Thanks everyone for the suggestions! UPDATE: Version 1.3 adds an appendTo option in the configuration for specifying which element the modal dialog should be appended to. Here are the docs . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2363/"
]
} |
29,242 | I work a lot with network and serial communications software, so it is often necessary for me to have code to display or log hex dumps of data packets. Every time I do this, I write yet another hex-dump routine from scratch. I'm about to do so again, but figured I'd ask here: Is there any good free hex dump code for C++ out there somewhere? Features I'd like: N bytes per line (where N is somehow configurable) optional ASCII/UTF8 dump alongside the hex configurable indentation, per-line prefixes, per-line suffixes, etc. minimal dependencies (ideally, I'd like the code to all be in a header file, or be a snippet I can just paste in) Edit: Clarification: I am looking for code that I can easily drop in to my own programs to write to stderr, stdout, log files, or other such output streams. I'm not looking for a command-line hex dump utility. | I often use this little snippet I've written long time ago. It's short and easy to add anywhere when debugging etc... #include <ctype.h>#include <stdio.h>void hexdump(void *ptr, int buflen) { unsigned char *buf = (unsigned char*)ptr; int i, j; for (i=0; i<buflen; i+=16) { printf("%06x: ", i); for (j=0; j<16; j++) if (i+j < buflen) printf("%02x ", buf[i+j]); else printf(" "); printf(" "); for (j=0; j<16; j++) if (i+j < buflen) printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.'); printf("\n"); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
]
} |
29,292 | Say a development team includes (or makes use of) graphic artists who create all the images that go into a product. Such things include icons, bitmaps, window backgrounds, button images, animations, etc. Obviously, everything needed to build a piece of software should be under some form of version control. But most version control systems for developers are designed primarily for text-based information. Should the graphics people use the same version-control system and repository that the coders do? If not, what should they use, and what is the best way to keep everything synchronized? | Yes, having art assets in version control is very useful. You get the ability to track history, roll back changes, and you have a single source to do backups with. Keep in mind that art assets are MUCH larger so your server needs to have lots of disk space & network bandwidth. I've had success with using perforce on very large projects (+100 GB), however we had to wrap access to the version control server with something a little more artist friendly. I've heard some good things about Alienbrain as well, it does seem to have a very slick UI. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
]
} |
29,324 | What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this? And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair? | Map map = new HashMap();Hashtable ht = new Hashtable(); Both classes can be found from the java.util package. The difference between the 2 is explained in the following jGuru FAQ entry . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
]
} |
29,335 | My current employer uses a 3rd party hosted CRM provider and we have a fairly sophisticated integration tier between the two systems. Amongst the capabilities of the CRM provider is for developers to author business logic in a Java like language and on events such as the user clicking a button or submitting a new account into the system, have validation and/or business logic fire off. One of the capabilities that we make use of is for that business code running on the hosted provider to invoke web services that we host. The canonical example is a sales rep entering in a new sales lead and hitting a button to ping our systems to see if we can identify that new lead based on email address, company/first/last name, etc, and if so, return back an internal GUID that represents that individual. This all works for us fine, but we've run into a wall again and again in trying to setup a sane dev environment to work against. So while our use case is a bit nuanced, this can generally apply to any development house that builds APIs for 3rd party consumption: what are some best practices when designing a development pipeline and environment when you're building APIs to be consumed by the outside world? At our office, all our devs are behind a firewall, so code in progress can't be hit by the outside world, in our case the CRM provider. We could poke holes in the firewall but that's less than ideal from a security surface area standpoint. Especially if the # of devs who need to be in a DMZ like area is high. We currently are trying a single dev machine in the DMZ and then remoting into it as needed to do dev work, but that's created a resource scarcity issue if multiple devs need the box, let alone they're making potentially conflicting changes (e.g. different branches). We've considered just mocking/faking incoming requests by building fake clients for these services, but that's a pretty major overhead in building out feature sets (though it does by nature reinforce a testability of our APIs). This also doesn't obviate the fact that sometimes we really do need to diagnose/debug issues coming from the real client itself, not some faked request payload. What have others done in these types of scenarios? In this day and age of mashups, there have to be a lot of folks out there w/ experiences of developing APIs--what's worked (and not worked so) well for the folks out there? | Map map = new HashMap();Hashtable ht = new Hashtable(); Both classes can be found from the java.util package. The difference between the 2 is explained in the following jGuru FAQ entry . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228/"
]
} |
29,383 | Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :) | How about using the C++ language itself? bool t = true;bool f = false;std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl; std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl; UPDATE: If you want more than 4 lines of code without any console output, please go to cppreference.com's page talking about std::boolalpha and std::noboolalpha which shows you the console output and explains more about the API. Additionally using std::boolalpha will modify the global state of std::cout , you may want to restore the original behavior go here for more info on restoring the state of std::cout . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/29383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
29,399 | I'm working on building a development tool that is written in JavaScript. This will not be an open source project and will be sold (hopefully) as a commercial product. I'm looking for the best way to protect my investment. Is using an obfuscator (code mangler) enough to reasonably secure the code? Are there other alternatives that I am not aware of? (I'm not sure if obfuscator is the right word, it's one of the apps that takes your code and makes it very unreadable.) | I'm going to tell you a secret. Once you understand it, you'll feel a lot better about the fact that Javascript obfuscation is only really useful for saving bandwidth when sending scripts over the wire. Your source-code is not worth stealing. I know this comes as a shock to the ego, but I can say this confidently without ever having seen a line of code you've written because outside the very few realms of development where serious magic happens, it's true of all source-code. Say, tomorrow, someone dumped a pile of DVDs on your doorstep containing the source code for Windows Vista. What would you be able to do with it? Sure, you could compile it and give away copies, but that's just one step more effort than copying the retail version. You could painstakingly find and remove the license-checking code, but that's something some bright kid has already done to the binaries. Replace the logo and graphics, pretend you wrote it yourself and market it as "Vicrosoft Mista"? You'll get caught. You could spend an enormous amount of time reading the code, trying to understand it and truly "stealing the intellectual property" that Microsoft invested in developing the product. But you'd be disappointed. You'd find the code was a long series of mundane decisions, made one after the other. Some would be smarter than you could think of. Some would leave you shaking your head wondering what kind of monkeys they're hiring over there. Most would just make you shrug and say "yeah, that's how you do that." In the process you'll learn a lot about writing operating systems, but that's not going to hurt Microsoft. Replace "Vista" with "Leopard" and the above paragraphs don't change one bit. It's not Microsoft, it's software . Half the people on this site could probably develop a Stack Overflow clone, with or without looking at the source of this site. They just haven't. The source-code of Firefox and WebKit are out there for anyone to read. Now go write your own browser from scratch. See you in a few years. Software development is an investment of time. It's utter hubris to imagine that what you're doing is so special that nobody could clone it without looking at your source, or even that it would make their job that much easier without an actionable (and easily detectable) amount of cut and paste. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/29399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2490/"
]
} |
29,426 | I'm looking for a good GUI designer for swing in eclipse. My preference is for a free/open-source plugin. | Window Builder Pro is a great GUI Designer for eclipse and is now offered for free by google. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/29426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2612/"
]
} |
29,466 | I'd like to write a game for the Nintendo Wii. How do I go about obtaining an SDK and/or any other tools necessary for writing a game? | The Wii Remote and Wii Balance Board use bluetooth. You can pair them with your PC and write your own PC apps that interact with them (like this guy ). If you want to make something that actually runs on the Wii, you can try finding some homebrew development help. If you want to actually sell your software for Wii, you need: game development experience secure office facilities $2,000 - $10,000 for dev kit (WiiWare is cheapest) The Nintendo Software Development Support Group Authorized Developer Application UPDATE: Also see the Wii U Developer Site . Nintendo now has a simple application for individual developers to makes games for the Wii U, giving you access to the SDK and dev-kits. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
]
} |
29,482 | How do I cast an int to an enum in C#? | From an int: YourEnum foo = (YourEnum)yourInt; From a string: YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);// The foo.ToString().Contains(",") check is necessary for // enumerations marked with a [Flags] attribute.if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(",")){ throw new InvalidOperationException( $"{yourString} is not an underlying value of the YourEnum enumeration." );} From a number: YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt); | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/29482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
29,496 | I'd like to write a script/batch that will bunch up my daily IIS logs and zip them up by month. ex080801.log which is in the format of ex yymmdd .log ex080801.log - ex080831.log gets zipped up and the log files deleted. The reason we do this is because on a heavy site a log file for one day could be 500mb to 1gb so we zip them up which compresses them by 98% and dump the real log file. We use webtrend to analyze the log files and it is capable of reading into a zip file. Does anyone have any ideas on how to script this or would be willing to share some code? | You'll need a command line tool to zip up the files. I recommend 7-Zip which is free and easy to use. The self-contained command line version (7za.exe) is the most portable choice. Here's a two-line batch file that would zip the log files and delete them afterwards: 7za.exe a -tzip ex%1-logs.zip %2\ex%1*.logdel %2\ex%1*.log The first parameter is the 4 digit year-and-month, and the second parameter is the path to the directory containing your logs. For example: ziplogs.bat 0808 c:\logs It's possible to get more elaborate (i.e. searching the filenames to determine which months to archive). You might want to check out the Windows FINDSTR command for searching input text with regular expressions. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648/"
]
} |
29,511 | In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I'm seeing their ASCII values instead: >> a = "0123"=> "0123">> a[0]=> 48 I've looked online but can't find any way to get the original "0" back out of it. I'm a little new to Ruby to I know it has to be something simple but I just can't seem to find it. | Or you can convert the integer to its character value: a[0].chr | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
} |
29,539 | Is there a one line function call that quits the program and displays a message? I know in Perl it's as simple as: die("Message goes here") I'm tired of typing this: puts "Message goes here"exit | The abort function does this. For example: abort("Message goes here") Note: the abort message will be written to STDERR as opposed to puts which will write to STDOUT . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/29539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
} |
29,557 | I've read time and time again that TDD/test first is more difficult with MSTest than it is with other testing frameworks such as nUnit, MBUnit, etc... What are some suggested manual workarounds and/or 3rd party bits that you suggest when MSTest is the only option due to infrastructure policy? I'm mainly wondering about VS 2008 Team Suite, but I suppose tips for VS 2008 Pro on up would be suitable too since some MSTest functionality is now included with those versions as well. | MSTest is certainly not as efficient or extensible as some of the open source frameworks, but it is workable. Since the question asks about making life easier with MSTest and not about alternatives, here are my MSTest tips. Shortcuts . Like Haacked said, take a few seconds to learn the shortcuts. Current Context . Since MSTest is so slow, run tests only in the current context when you can. ( CTRL + R , CTRL + T ). If your cursor is in a test method, this will only run the method. If your cursor is outside a method, but in a test class, this will only run the test. And with namespace, etc etc Efficient tests and organization . It's dog slow. Make things as best as you can by writing efficient tests. Move slow tests to other test classes or projects so you can run the fast tests more frequently. Testing with WCF . If you're testing services, be sure to DEBUG tests rather than RUN tests so Visual Studio can fire up the ASP.NET development web servers. After these are up, then you can go back to RUN, but it can be easier to just always DEBUG so you don't have to think about it. Config Files . Edit your test-run configuration to move .config files into the test execution folder. Integration with Source Safe . You need to be aware that MSTest hates SourceSafe and the feeling is mutual. Because MSTest wants to put test files under source control, and add them to the solution, it must check out the solution every time you run tests. So SourceSafe must be running in multi-check-out mode to avoid killing your fellow developers. Ignore the fluff With MSTest, you get a dozen different windows and views. Test Runs, Test View, Test Lists ... they're all less-than-helpful. Stick with Test Results and you'll be much happier. Stick with "Unit Tests" . When you add a new test, you can add an ordered test, a unit test, or run through a wizard. Stick with just plain simple unit tests. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644/"
]
} |
29,562 | I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform. my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now. edit : Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it? Here are a few useful links Ubuntu Python Packaging Guide This Guide is very helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application The Ubuntu MOTU Project This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'. "Python distutils to deb?" - Ars Technica Forum discussion According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide "A bdist_deb command for distutils This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it. Description of the deb format and how distutils fit in - python mailing list | See the distutils simple example . That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same. Here is a real-life (anonymized) example: #!/usr/bin/python from distutils.core import setup setup (name = 'Initech Package 3', description = "Services and libraries ABC, DEF", author = "That Guy, Initech Ltd", author_email = "[email protected]", version = '1.0.5', package_dir = {'Package3' : 'site-packages/Package3'}, packages = ['Package3', 'Package3.Queries'], data_files = [ ('/etc/Package3', ['etc/Package3/ExternalResources.conf']) ]) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
]
} |
29,580 | It's one of those things that seems to have an odd curve where the more I think about it, the more it makes sense. To a certain extent, of course. And then it doesn't make sense to me at all. Care to enlighten me? | Because in most cases you've got to sort your results first. For example, when you search on Google, you can view only up to 100 pages of results . They don't bother sorting by page-rank beyond 1000 websites for given keyword (or combination of keywords). Pagination is fast. Sorting is slow. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293/"
]
} |
29,621 | On Windows I can do: HANDLE hCurrentProcess = GetCurrentProcess();SetPriorityClass(hCurrentProcess, ABOVE_NORMAL_PRIORITY_CLASS); How can I do the same thing on *nix? | Try: #include <sys/time.h>#include <sys/resource.h>int main(){ setpriority(PRIO_PROCESS, 0, -20);} Note that you must be running as superuser for this to work. (for more info, type 'man setpriority' at a prompt.) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
]
} |
29,626 | In a VB.NET WinForms project, I get an exception Cannot access a disposed of object when closing a form. It occurs very rarely and I cannot recreate it on demand. The stack trace looks like this: Cannot access a disposed object. Object name: 'dbiSchedule'. at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.Control.PointToScreen(Point p) at Dbi.WinControl.Schedule.dbiSchedule.a(Boolean A_0) at Dbi.WinControl.Schedule.dbiSchedule.a(Object A_0, EventArgs A_1) at System.Windows.Forms.Timer.OnTick(EventArgs e) at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) The dbiSchedule is a schedule control from Dbi-tech. There is a timer on the form that updates the schedule on the screen every few minutes. Any ideas what is causing the exception and how I might go about fixing it? or even just being able to recreate it on demand? Hej! Thanks for all the answers. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help. It's a really annoying problem because if someone did come up with a solution that worked - I wouldn't be able to confirm the solution because I cannot recreate the problem manually. | Try checking the IsDisposed property before accessing the control. You can also check it on the FormClosing event, assuming you're using the FormClosed event. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help. Calling GC.Collect before checking IsDisposed may help, but be careful with this. Read this article by Rico Mariani " When to call GC.Collect() ". | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961/"
]
} |
29,647 | Let's say I'm creating a program in C that needs to use a tempfile. Creating an ad hoc tempfile in /tmp is probably not a good idea. Is there a function or OS call to supply me with a tempfile name so that I can begin to write and read from it? | You can use the mkstemp(3) function for this purpose. Another alternative is the tmpfile(3) function.Which one of them you choose depends on whether you want the file to be opened as a C library file stream (which tmpfile does), or a direct file descriptor ( mkstemp ). The tmpfile function also deletes the file automatically when you program finishes. The advantage of using these functions is that they avoid race conditions between determining the unique filename and creating the file -- so that two programs won't try to create the same file at the same time, for example. See the man pages for both functions for more details. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
29,664 | I need to specifically catch SQL server timeout exceptions so that they can be handled differently. I know I could catch the SqlException and then check if the message string Contains "Timeout" but was wondering if there is a better way to do it? try{ //some code}catch (SqlException ex){ if (ex.Message.Contains("Timeout")) { //handle timeout } else { throw; }} | To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation. -2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading Reflector , and looking under System.Data.SqlClient.TdsEnums for TIMEOUT_EXPIRED. Your code would read: if (ex.Number == -2){ //handle timeout} Code to demonstrate failure: try{ SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;"); sql.Open(); SqlCommand cmd = sql.CreateCommand(); cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END"; cmd.ExecuteNonQuery(); // This line will timeout. cmd.Dispose(); sql.Close();}catch (SqlException ex){ if (ex.Number == -2) { Console.WriteLine ("Timeout occurred"); }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/29664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2231/"
]
} |
29,686 | I'll have an ASP.net page that creates some Excel Sheets and sends them to the user. The problem is, sometimes I get Http timeouts, presumably because the Request runs longer than executionTimeout (110 seconds per default). I just wonder what my options are to prevent this, without wanting to generally increase the executionTimeout in web.config ? In PHP, set_time_limit exists which can be used in a function to extend its life, but I did not see anything like that in C#/ASP.net? How do you handle long-running functions in ASP.net? | If you want to increase the execution timeout for this one request you can set HttpContext.Current.Server.ScriptTimeout But you still may have the problem of the client timing out which you can't reliably solve directly from the server. To get around that you could implement a "processing" page (like Rob suggests) that posts back until the response is ready. Or you might want to look into AJAX to do something similar. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
} |
29,689 | I have a large codebase without Javadoc, and I want to run a program to write a skeleton with the basic Javadoc information (e.g., for each method's parameter write @param...), so I just have to fill the gaps left. Anyone know a good solution for this? Edit: JAutodoc is what I was looking for. It has Ant tasks, an Eclipse plugin, and uses Velocity for the template definition. | The JAutodoc plugin for eclipse does exactly what you need, but with a package granularity : right click on a package, select "Add javadoc for members..." and the skeleton will be added. There are numerous interesting options : templates for javadoc, adding a TODO in the header of every file saying : "template javadoc, must be filled...", etc. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
]
} |
29,696 | How do you stop the designer from auto generating code that sets the value for public properties on a user control? | Use the DesignerSerializationVisibilityAttribute on the properties that you want to hide from the designer serialization and set the parameter to Hidden. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]public string Name{ get; set;} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/29696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2253/"
]
} |
29,699 | I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows: SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' I (understandably) get an error. How do I prevent this error from occurring. I am using Oracle and PLSQL. | The escape character is ', so you would need to replace the quote with two quotes. For example, SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' becomes SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe' That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use in SQL, but an even better option is to use parameters. Usually this works as follows. Your SQL command would be : SELECT * FROM PEOPLE WHERE SURNAME=? Then, when you execute it, you pass in "O'Keefe" as a parameter. Because the SQL is parsed before the parameter value is set, there's no way for the parameter value to alter the structure of the SQL (and it's even a little faster if you want to run the same statement several times with different parameters). I should also point out that, while your example just causes an error, you open youself up to a lot of other problems by not escaping strings appropriately. See http://en.wikipedia.org/wiki/SQL_injection for a good starting point or the following classic xkcd comic . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445/"
]
} |
29,709 | I am using jQuery and trying to find a cross browser way to get the pixel coordinates of the caret in <textarea> s and input boxes such that I can place an absolutely positioned div around this location. Is there some jQuery plugin? Or JavaScript snippet to do just that? | I've looked for a textarea caret coordinates plugin for meteor-autocomplete , so I've evaluated all the 8 plugins on GitHub. The winner is, by far, textarea-caret-position from Component . Features pixel precision no dependencies whatsoever browser compatibility: Chrome, Safari, Firefox (despite two bugs it has), IE9+; may work but not tested in Opera, IE8 or older supports any font family and size, as well as text-transforms the text area can have arbitrary padding or borders not confused by horizontal or vertical scrollbars in the textarea supports hard returns, tabs (except on IE) and consecutive spaces in the text correct position on lines longer than the columns in the text area no "ghost" position in the empty space at the end of a line when wrapping long words Here's a demo - http://jsfiddle.net/dandv/aFPA7/ How it works A mirror <div> is created off-screen and styled exactly like the <textarea> . Then, the text of the textarea up to the caret is copied into the div and a <span> is inserted right after it. Then, the text content of the span is set to the remainder of the text in the textarea, in order to faithfully reproduce the wrapping in the faux div. This is the only method guaranteed to handle all the edge cases pertaining to wrapping long lines. It's also used by GitHub to determine the position of its @ user dropdown. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
]
} |
29,761 | Can anyone recommend a good repository viewer for Git, similar to gitk, that works on Mac OS X Leopard? (I'm not saying gitk doesn't work) Of course I would like a native Mac application, but as I haven't found any, what are the best options to gitk? I know about gitview, but I'm looking forward to evaluate as many alternatives as possible. http://sourceforge.net/projects/gitview | There's also gitx , it's progressing well and under active development (multiple commits per day). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
]
} |
29,810 | I am in charge of about 100+ documents (word document, not source code) that needs revision by different people in my department. Currently all the documents are in a shared folder where they will retrieve, revise and save back into the folder. What I am doing now is looking up the "date modified" in the shared folder, opened up recent modified documents and use the "Track Change" function in MS Word to apply the changes. I find this a bit tedious. So will it be better and easier if I commit this in a version control database? Basically I want to keep different version of a file. What have I learn from answers: Use Time Machine to save differentversion (or Shadow copy in Vista) There is a difference between textand binary documents when you useversion control app. (I didn't knowthat) Diff won't work on binary files A notification system (ie email) for revision is great Google Docs revision feature. Update : I played around with Google Docs revision feature and feel that it is almost right for me. Just a bit annoyed with the too frequent versioning (autosaving). But what feels right for me doesn't mean it feels right for my dept. Will they be okay with saving all these documents with Google? | I've worked with Word documents in SVN. With TortoiseSVN , you can easily diff Word documents (between working copy and repository, or between two repository revisions). It's really slick and definitely recommended. The other thing to do if you're using Word documents in SVN is to add the svn:needs-lock property to the Word documents. This will prevent two people from trying to edit the same document at the same time, since unfortunately there's no good way to merge Word documents. With the above two things, handling revision controlled Word documents is at least tolerable. It certainly beats the alternative of using a shared folder and track-changes. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/29810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1261/"
]
} |
29,845 | I have an application on which I am implementing localization. I now need to dynamically reference a name in the resouce file. assume I have a resource file called Login.resx, an a number of strings: foo="hello", bar="cruel" and baz="world" normally, I will refer as: String result =Login.foo;and result=="hello"; my problem is, that at code time, I do not know if I want to refer to foo, bar or baz - I have a string that contains either "foo", "bar" or "baz". I need something like: Login["foo"]; Does anyone know if there is any way to dynamically reference a string in a resource file? | You'll need to instance a ResourceManager for the Login.resx : var resman = new System.Resources.ResourceManager( "RootNamespace.Login", System.Reflection.Assembly.GetExecutingAssembly())var text = resman.GetString("resname"); It might help to look at the generated code in the code-behind files of the resource files that are created by the IDE. These files basically contain readonly properties for each resource that makes a query to an internal resource manager. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1090/"
]
} |
29,869 | I need to match and remove all tags using a regular expression in Perl. I have the following: <\\??(?!p).+?> But this still matches with the closing </p> tag. Any hint on how to match with the closing tag as well? Note, this is being performed on xhtml. | I came up with this: <(?!\/?p(?=>|\s.*>))\/?.*?>x/< # Match open angle bracket(?! # Negative lookahead (Not matching and not consuming) \/? # 0 or 1 / p # p (?= # Positive lookahead (Matching and not consuming) > # > - No attributes | # or \s # whitespace .* # anything up to > # close angle brackets - with attributes ) # close positive lookahead) # close negative lookahead # if we have got this far then we don't match # a p tag or closing p tag # with or without attributes\/? # optional close tag symbol (/).*? # and anything up to> # first closing tag/ This will now deal with p tags with or without attributes and the closing p tags, but will match pre and similar tags, with or without attributes. It doesn't strip out attributes, but my source data does not put them in. I may change this later to do this, but this will suffice for now. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
]
} |
29,943 | Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form? The submit button is not there . I am using a custom div instead of that. | To submit the form when the enter key is pressed create a javascript function along these lines. function checkSubmit(e) { if(e && e.keyCode == 13) { document.forms[0].submit(); }} Then add the event to whatever scope you need eg on the div tag: <div onKeyPress="return checkSubmit(event)"/> This is also the default behaviour of Internet Explorer 7 anyway though (probably earlier versions as well). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/29943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
29,995 | I want to practice my skills away from a keyboard (i.e. pen and paper) and I'm after simple practice questions like Fizz Buzz, Print the first N primes. What are your favourite simple programming questions? | I've been working on http://projecteuler.net/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/29995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
]
} |
30,003 | I have the following html code: <h3 id="headerid"><span onclick="expandCollapse('headerid')">⇑</span>Header title</h3> I would like to toggle between up arrow and down arrow each time the user clicks the span tag. function expandCollapse(id) { var arrow = $("#"+id+" span").html(); // I have tried with .text() too if(arrow == "⇓") { $("#"+id+" span").html("⇑"); } else { $("#"+id+" span").html("⇓"); }} My function is going always the else path. If I make a javacript:alert of arrow variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the arrow variable as a string and not as html. | When the HTML is parsed, what JQuery sees in the DOM is a UPWARDS DOUBLE ARROW ("⇑"), not the entity reference. Thus, in your Javascript code you should test for "⇑" or "\u21d1" . Also, you need to change what you're switching to: function expandCollapse(id) { var arrow = $("#"+id+" span").html(); if(arrow == "\u21d1") { $("#"+id+" span").html("\u21d3"); } else { $("#"+id+" span").html("\u21d1"); }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
} |
30,005 | I have to load a PDF within a page. Ideally I would like to have a loading animated gif which is replaced once the PDF has loaded. | Have you tried: $("#iFrameId").on("load", function () { // do something once the iframe is loaded}); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/30005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3168/"
]
} |
30,018 | How can I use XPath to select an XML-node based on its content? If I e.g. have the following xml and I want to select the <author>-node that contains Ritchie to get the author's full name: <books> <book isbn='0131103628'> <title>The C Programming Language</title> <authors> <author>Ritchie, Dennis M.</author> <author>Kernighan, Brian W.</author> </authors> </book> <book isbn='1590593898'> <title>Joel on Software</title> <authors> <author>Spolsky, Joel</author> </authors> </book></books> | /books/book/authors/author[contains(., 'Ritchie')] or //author[contains(., 'Ritchie')] | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/30018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523/"
]
} |
30,026 | I've seen a lot of commonality in regex capabilities of different regex-enabled tools/languages (e.g. perl, sed, java, vim, etc), but I've also many differences. Is there a standard subset of regex capabilities that all regex-enabled tools/languages will support? How do regex capabilities vary between tools/languages? | Compare Regular Expression Flavors http://www.regular-expressions.info/refflavors.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2045/"
]
} |
30,036 | Is there some way to do multi-threading in JavaScript? | See http://caniuse.com/#search=worker for the most up-to-date support info. The following was the state of support circa 2009. The words you want to google for are JavaScript Worker Threads Apart from from Gears there's nothing available right now, but there's plenty of talk about how to implement this so I guess watch this question as the answer will no doubt change in future. Here's the relevant documentation for Gears: WorkerPool API WHATWG has a Draft Recommendation for worker threads: Web Workers And there's also Mozilla’s DOM Worker Threads Update: June 2009, current state of browser support for JavaScript threads Firefox 3.5 has web workers. Some demos of web workers, if you want to see them in action: Simulated Annealing ("Try it" link) Space Invaders (link at end of post) MoonBat JavaScript Benchmark (first link) The Gears plugin can also be installed in Firefox. Safari 4 , and the WebKit nightlies have worker threads: JavaScript Ray Tracer Chrome has Gears baked in, so it can do threads, although it requires a confirmation prompt from the user (and it uses a different API to web workers, although it will work in any browser with the Gears plugin installed): Google Gears WorkerPool Demo (not a good example as it runs too fast to test in Chrome and Firefox, although IE runs it slow enough to see it blocking interaction) IE8 and IE9 can only do threads with the Gears plugin installed | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/30036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
30,058 | The Apple Developer Documentation (link is dead now) explains that if you place a link in a web page and then click it whilst using Mobile Safari on the iPhone, the Google Maps application that is provided as standard with the iPhone will launch. How can I launch the same Google Maps application with a specific address from within my own native iPhone application (i.e. not a web page through Mobile Safari) in the same way that tapping an address in Contacts launches the map? NOTE: THIS ONLY WORKS ON THE DEVICE ITSELF. NOT IN THE SIMULATOR. | For iOS 5.1.1 and lower, use the openURL method of UIApplication . It will perform the normal iPhone magical URL reinterpretation. so [someUIApplication openURL:[NSURL URLWithString:@"http://maps.google.com/maps?q=London"]] should invoke the Google maps app. From iOS 6, you'll be invoking Apple's own Maps app. For this, configure an MKMapItem object with the location you want to display, and then send it the openInMapsWithLaunchOptions message. To start at the current location, try: [[MKMapItem mapItemForCurrentLocation] openInMapsWithLaunchOptions:nil]; You'll need to be linked against MapKit for this (and it will prompt for location access, I believe). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
]
} |
30,062 | Yesterday I wanted to add a boolean field to an Oracle table. However, there isn't actually a boolean data type in Oracle. Does anyone here know the best way to simulate a boolean? Googling the subject discovered several approaches Use an integer and just don't bother assigning anything other than 0 or 1 to it. Use a char field with 'Y' or 'N' as the only two values. Use an enum with the CHECK constraint. Do experienced Oracle developers know which approach is preferred/canonical? | I found this link useful. Here is the paragraph highlighting some of the pros/cons of each approach. The most commonly seen design is to imitate the many Boolean-like flags that Oracle's data dictionary views use, selecting 'Y' for true and 'N' for false. However, to interact correctly with host environments, such as JDBC, OCCI, and other programming environments, it's better to select 0 for false and 1 for true so it can work correctly with the getBoolean and setBoolean functions. Basically they advocate method number 2, for efficiency's sake, using values of 0/1 (because of interoperability with JDBC's getBoolean() etc.) with a check constraint a type of CHAR (because it uses less space than NUMBER). Their example: create table tbool (bool char check (bool in (0,1));insert into tbool values(0);insert into tbool values(1);` | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
]
} |
30,067 | I just listened to the StackOverflow team's 17th podcast, and they talked so highly of ASP.NET MVC that I decided to check it out. But first, I want to be sure it's worth it. I already created a base web application (for other developers to build on) for a project that's starting in a few days and wanted to know, based on your experience, if I should take the time to learn the basics of MVC and re-create the base web application with this model. Are there really big pros that'd make it worthwhile? EDIT: It's not an existing project, it's a project about to start, so if I'm going to do it it should be now... I just found this It does not, however, use the existing post-back model for interactions back to the server. Instead, you'll route all end-user interactions to a Controller class instead - which helps ensure clean separation of concerns and testability ( it also means no viewstate or page lifecycle with MVC based views ). How would that work? No viewstate? No events? | If you are quite happy with WebForms today, then maybe ASP.NET MVC isn't for you. I have been frustrated with WebForms for a really long time. I'm definitely not alone here. The smart-client, stateful abstraction over the web breaks down severely in complex scenarios. I happen to love HTML, Javascript, and CSS. WebForms tries to hide that from me. It also has some really complex solutions to problems that are really not that complex. Webforms is also inherently difficult to test, and while you can use MVP, it's not a great solution for a web environment...(compared to MVC). MVC will appeal to you if...- you want more control over your HTML- want a seamless ajax experience like every other platform has- want testability through-and-through- want meaningful URLs- HATE dealing with postback & viewstate issues And as for the framework being Preview 5, it is quite stable, the design is mostly there, and upgrading is not difficult. I started an app on Preview 1 and have upgraded within a few hours of the newest preview being available. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
]
} |
30,080 | I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle. | From my "Geometry" class: public struct Line{ public static Line Empty; private PointF p1; private PointF p2; public Line(PointF p1, PointF p2) { this.p1 = p1; this.p2 = p2; } public PointF P1 { get { return p1; } set { p1 = value; } } public PointF P2 { get { return p2; } set { p2 = value; } } public float X1 { get { return p1.X; } set { p1.X = value; } } public float X2 { get { return p2.X; } set { p2.X = value; } } public float Y1 { get { return p1.Y; } set { p1.Y = value; } } public float Y2 { get { return p2.Y; } set { p2.Y = value; } }}public struct Polygon: IEnumerable<PointF>{ private PointF[] points; public Polygon(PointF[] points) { this.points = points; } public PointF[] Points { get { return points; } set { points = value; } } public int Length { get { return points.Length; } } public PointF this[int index] { get { return points[index]; } set { points[index] = value; } } public static implicit operator PointF[](Polygon polygon) { return polygon.points; } public static implicit operator Polygon(PointF[] points) { return new Polygon(points); } IEnumerator<PointF> IEnumerable<PointF>.GetEnumerator() { return (IEnumerator<PointF>)points.GetEnumerator(); } public IEnumerator GetEnumerator() { return points.GetEnumerator(); }}public enum Intersection{ None, Tangent, Intersection, Containment}public static class Geometry{ public static Intersection IntersectionOf(Line line, Polygon polygon) { if (polygon.Length == 0) { return Intersection.None; } if (polygon.Length == 1) { return IntersectionOf(polygon[0], line); } bool tangent = false; for (int index = 0; index < polygon.Length; index++) { int index2 = (index + 1)%polygon.Length; Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2])); if (intersection == Intersection.Intersection) { return intersection; } if (intersection == Intersection.Tangent) { tangent = true; } } return tangent ? Intersection.Tangent : IntersectionOf(line.P1, polygon); } public static Intersection IntersectionOf(PointF point, Polygon polygon) { switch (polygon.Length) { case 0: return Intersection.None; case 1: if (polygon[0].X == point.X && polygon[0].Y == point.Y) { return Intersection.Tangent; } else { return Intersection.None; } case 2: return IntersectionOf(point, new Line(polygon[0], polygon[1])); } int counter = 0; int i; PointF p1; int n = polygon.Length; p1 = polygon[0]; if (point == p1) { return Intersection.Tangent; } for (i = 1; i <= n; i++) { PointF p2 = polygon[i % n]; if (point == p2) { return Intersection.Tangent; } if (point.Y > Math.Min(p1.Y, p2.Y)) { if (point.Y <= Math.Max(p1.Y, p2.Y)) { if (point.X <= Math.Max(p1.X, p2.X)) { if (p1.Y != p2.Y) { double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X; if (p1.X == p2.X || point.X <= xinters) counter++; } } } } p1 = p2; } return (counter % 2 == 1) ? Intersection.Containment : Intersection.None; } public static Intersection IntersectionOf(PointF point, Line line) { float bottomY = Math.Min(line.Y1, line.Y2); float topY = Math.Max(line.Y1, line.Y2); bool heightIsRight = point.Y >= bottomY && point.Y <= topY; //Vertical line, slope is divideByZero error! if (line.X1 == line.X2) { if (point.X == line.X1 && heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1); bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X)); if (onLine && heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623/"
]
} |
30,099 | In my browsings amongst the Internet, I came across this post , which includes this "(Well written) C++ goes to great lengths to make stack automatic objects work "just like" primitives, as reflected in Stroustrup's advice to "do as the ints do". This requires a much greater adherence to the principles of Object Oriented development: your class isn't right until it "works like" an int, following the "Rule of Three" that guarantees it can (just like an int) be created, copied, and correctly destroyed as a stack automatic." I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly? Can someone give an example? | Stack objects are handled automatically by the compiler. When the scope is left, it is deleted. { obj a;} // a is destroyed here When you do the same with a 'newed' object you get a memory leak : { obj* b = new obj;} b is not destroyed, so we lost the ability to reclaim the memory b owns. And maybe worse, the object cannot clean itself up. In C the following is common : { FILE* pF = fopen( ... ); // ... do sth with pF fclose( pF );} In C++ we write this : { std::fstream f( ... ); // do sth with f} // here f gets auto magically destroyed and the destructor frees the file When we forget to call fclose in the C sample the file is not closed and may not be used by other programs. (e.g. it cannot be deleted). Another example, demonstrating the object string, which can be constructed, assigned to and which is destroyed on exiting the scope. { string v( "bob" ); string k; v = k // v now contains "bob"} // v + k are destroyed here, and any memory used by v + k is freed | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
]
} |
30,101 | In my work I deal mostly with C# code nowadays, with a sprinkle of java from time to time. What I absolutely love about Eclipse (and I know people using it daily love it even more) is a sophisticated code formatter, able to mould code into any coding standard one might imagine. Is there such a tool for C#? Visual Studio code formatting (Crtl+K, Crtl+D) is subpar and StyleCop only checks the source without fixing it. My dream tool would run from console (for easy inclusion in automated builds or pre-commit hooks and for execution on Linux + Mono), have text-file based configuration easy to store in a project repository and a graphical rule editor with preview - just like the Eclipse Code Formatter does. | For Visual Studio, take a look at ReSharper . It's an awesome tool and a definite must-have. Versions after 4.0 have the code formatting and clean-up feature that you are looking for. There's also plugin integration with StyleCop , including formatting settings file. You'll probably want Agent Smith plugin as well, for spell-checking the identifiers and comments. ReSharper supports per-solution formatting setting files, which can be checked into version control system and shared by the whole team. The keyboard shortcut for code cleanup is Ctrl + E , C . In 'vanilla' Visual Studio, the current file can be automatically formatted with Ctrl + K , Ctrl + D , and Ctrl + K , Ctrl + F formats the selected text. As for a runs-everywhere command line tool to be used with commit hooks, try NArrange . It's free, can process whole directories at once and runs on Mono as well as on Microsoft .NET. Some people also use the Artistic Style command line tool, although it requires Perl and works better with C/C++ code than with C#. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
]
} |
30,121 | After my web form is submitted, a regex will be applied to user input on the server side (via PHP). I'd like to have the identical regex running in real-time on the client side to show the user what the real input will be. This will be pretty much the same as the Preview section on the Ask Question pages on Stack Overflow except with PHP on the back-end instead of .NET. What do I need to keep in mind in order to have my PHP and JavaScript regular expressions act exactly the same as each other? | Hehe this was sort of asked moments ago and Jeff pointed out: http://www.regular-expressions.info/refflavors.html . There is a comparison of regular expression capabilities across tools and languages. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356/"
]
} |
30,183 | When I try to do that I get the following error: Changes to 64-bit applications are not allowed. @Wilka: That option wasn't available until I selected Tools > Options > Projects and Solutions > General and check "Show advanced build configurations". Though I found this hint from your MSDN link. So if you edit your comment, I can make it the accepted answer... Thanks everybody! Please see my first comment on this question, it's not there... Somehow... I can select Target framework though (2.0, 3.0 and 3.5), not that I see any use of that for this particular problem... It doesn't have to be a 64bit program, actually, I rather prefer it to be 32bit anyway since it is more like a utility and it should work on 32bit systems. Also, I'm running Vista at 64bit. Maybe that has something to do with it? @Rob Cooper: Now I think of it, I never had the chance of selecting either a 64bit or a 32bit application when creating the solution/project/application...And according to your link "64-Bit Debugging (X64)" is possible with MS VB2008 express edition. Oh btw, I found the following: If you are debugging a 64-bit application and want to use Edit and Continue, you must change the target platform and compile the application as a 32-bit application. You can change this setting by opening the Project Properties and going to the Compile page. On that page, click Advanced Compile Options and change the Target CPU setting to x86 in the Advanced Compiler Settings dialog box. Link But I dont see the Target CPU setting... | You could try: In Visual Basic 2008 Express Edition: Build menu > Configuration Manager... Change Active solution platform: to "...", choose "x86", save the new platform. Now the "x86" option is available in the Compile settings. You may need to enable "Show advanced build configurations" first, in Tools > Options > Projects and Solutions > General (from this post on MSDN forums) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3228/"
]
} |
30,184 | I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed. How can I implement this behavior? | Microsoft KB Article 320687 has a detailed answer to this question. Basically, you override the WndProc method to return HTCAPTION to the WM_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form. private const int WM_NCHITTEST = 0x84;private const int HTCLIENT = 0x1;private const int HTCAPTION = 0x2;protected override void WndProc(ref Message m){ switch(m.Msg) { case WM_NCHITTEST: base.WndProc(ref m); if ((int)m.Result == HTCLIENT) m.Result = (IntPtr)HTCAPTION; return; } base.WndProc(ref m);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/30184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/507/"
]
} |
30,188 | I am trying to set a javascript date so that it can be submitted via JSON to a .NET type, but when attempting to do this, jQuery sets the date to a full string , what format does it have to be in to be converted to a .NET type? var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear();j("#student_registrationdate").val(regDate); // value to serialize I am using MonoRail on the server to perform the binding to a .NET type, that aside I need to know what to set the form hidden field value to, to get properly sent to .NET code. | Microsoft KB Article 320687 has a detailed answer to this question. Basically, you override the WndProc method to return HTCAPTION to the WM_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form. private const int WM_NCHITTEST = 0x84;private const int HTCLIENT = 0x1;private const int HTCAPTION = 0x2;protected override void WndProc(ref Message m){ switch(m.Msg) { case WM_NCHITTEST: base.WndProc(ref m); if ((int)m.Result == HTCLIENT) m.Result = (IntPtr)HTCAPTION; return; } base.WndProc(ref m);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/30188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
]
} |
30,211 | Is the ZIP compression that is built into Windows XP/Vista/2003/2008 able to be scripted at all? What executable would I have to call from a BAT/CMD file? or is it possible to do it with VBScript? I realize that this is possible using WinZip , 7-Zip and other external applications, but I'm looking for something that requires no external applications to be installed. | There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice. The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory. Unzipping is easier - just treat it as a directory. In case the web pages are lost again, here are a few of the relevant code snippets: ZIP Sub NewZip(sPath)'Create empty Zip File'Changed by keepITcool Dec-12-2005 If Len(Dir(sPath)) > 0 Then Kill sPath Open sPath For Output As #1 Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0) Close #1End SubFunction bIsBookOpen(ByRef szBookName As String) As Boolean' Rob Bovey On Error Resume Next bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)End FunctionFunction Split97(sStr As Variant, sdelim As String) As Variant'Tom Ogilvy Split97 = Evaluate("{""" & _ Application.Substitute(sStr, sdelim, """,""") & """}")End FunctionSub Zip_File_Or_Files() Dim strDate As String, DefPath As String, sFName As String Dim oApp As Object, iCtr As Long, I As Integer Dim FName, vArr, FileNameZip DefPath = Application.DefaultFilePath If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\" End If strDate = Format(Now, " dd-mmm-yy h-mm-ss") FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip" 'Browse to the file(s), use the Ctrl key to select more files FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _ MultiSelect:=True, Title:="Select the files you want to zip") If IsArray(FName) = False Then 'do nothing Else 'Create empty Zip File NewZip (FileNameZip) Set oApp = CreateObject("Shell.Application") I = 0 For iCtr = LBound(FName) To UBound(FName) vArr = Split97(FName(iCtr), "\") sFName = vArr(UBound(vArr)) If bIsBookOpen(sFName) Then MsgBox "You can't zip a file that is open!" & vbLf & _ "Please close it and try again: " & FName(iCtr) Else 'Copy the file to the compressed folder I = I + 1 oApp.Namespace(FileNameZip).CopyHere FName(iCtr) 'Keep script waiting until Compressing is done On Error Resume Next Do Until oApp.Namespace(FileNameZip).items.Count = I Application.Wait (Now + TimeValue("0:00:01")) Loop On Error GoTo 0 End If Next iCtr MsgBox "You find the zipfile here: " & FileNameZip End IfEnd Sub UNZIP Sub Unzip1() Dim FSO As Object Dim oApp As Object Dim Fname As Variant Dim FileNameFolder As Variant Dim DefPath As String Dim strDate As String Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _ MultiSelect:=False) If Fname = False Then 'Do nothing Else 'Root folder for the new folder. 'You can also use DefPath = "C:\Users\Ron\test\" DefPath = Application.DefaultFilePath If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\" End If 'Create the folder name strDate = Format(Now, " dd-mm-yy h-mm-ss") FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\" 'Make the normal folder in DefPath MkDir FileNameFolder 'Extract the files into the newly created folder Set oApp = CreateObject("Shell.Application") oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items 'If you want to extract only one file you can use this: 'oApp.Namespace(FileNameFolder).CopyHere _ 'oApp.Namespace(Fname).items.Item("test.txt") MsgBox "You find the files here: " & FileNameFolder On Error Resume Next Set FSO = CreateObject("scripting.filesystemobject") FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True End IfEnd Sub | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/30211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
]
} |
30,222 | I am writing a query in which I have to get the data for only the last year. What is the best way to do this? SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM' | The following adds -1 years to the current date: SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE()) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/30222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
]
} |
30,239 | I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code? | menutItem.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) }; | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
]
} |
30,251 | Possible Duplicate: Why not use tables for layout in HTML? Under what conditions should you choose tables instead of DIVs in HTML coding? | The whole "Tables vs Divs" thing just barely misses the mark. It's not "table" or "div". It's about using semantic html. Even the div tag plays only a small part in a well laid out page. Don't overuse it. You shouldn't need that many if you put your html together correctly. Things like lists, field sets, legends, labels, paragraphs, etc can replace much of what a div or span is often used to accomplish. Div should be used primarily when it makes sense to indicate a logical div ision, and only appropriated for extra layout when absolutely necessary. The same is true for table; use it when you have tabular data, but not otherwise. Then you have a more semantic page and you don't need quite as many classes defined in your CSS; you can target the tags directly instead. Possibly most importantly, you have a page that will score much better with Google (anecdotally) than the equivalent table or div-heavy page. Most of all it will help you better connect with a portion of your audience. So if we go back and look at it in terms of table vs div, it's my opinion that we've actually come to the point where div is over-used and table is under-used. Why? Because when you really think about it, there are a lot of things out there that fall into the category of "tabular data" that tend to be overlooked. Answers and comments on this very web page, for example. They consist of multiple records, each with the same set of fields. They're even stored in a sql server table, for crying out loud. This is the exact definition of tabular data. This means an html table tag would absolutely be a good semantic choice to layout something like the posts here on Stack Overflow. The same principle applies to many other things as well. It may not be a good idea to use a table tag to set up a three column layout, but it's certainly just fine to use it for grids and lists... except, of course, when you can actually use the ol or ul (list) tags. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/30251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
]
} |
30,281 | I'm using JBoss Seam Framework, but it's seems to me isn't very popular among java developers. I want to know how many java programmers here are using it, and in what kind of projects.Is as good as django, or RoR? | In our JBoss Seam in Action presentation at the Javapolis conference last year, my colleague and I said that 'Seam is the next Struts'. This needed some explanation, which I later wrote-up as Seam is the new Struts . Needless to say, we like Seam. One indication of Seam's popularity is the level of traffic on the Seam Users Forum . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3245/"
]
} |
30,302 | I'd like to ignore multiple wildcard routes. With asp.net mvc preview 4, they ship with: RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); I'd also like to add something like: RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}"); but that seems to break some of the helpers that generate urls in my program. Thoughts? | There are two possible solutions here. Add a constraint to the ignore route to make sure that only requests that should be ignored would match that route. Kinda kludgy, but it should work. RouteTable.Routes.IgnoreRoute("{folder}/{*pathInfo}", new {folder="content"}); What is in your content directory? By default, Routing does not route files that exist on disk (actually checks the VirtualPathProvider). So if you are putting static content in the Content directory, you might not need the ignore route. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
]
} |
30,310 | I'd like to have dashes separate words in my URLs. So instead of: /MyController/MyAction I'd like: /My-Controller/My-Action Is this possible? | You can use the ActionName attribute like so: [ActionName("My-Action")]public ActionResult MyAction() { return View();} Note that you will then need to call your View file "My-Action.cshtml" (or appropriate extension). You will also need to reference "my-action" in any Html.ActionLink methods. There isn't such a simple solution for controllers. Edit: Update for MVC5 Enable the routes globally: public static void RegisterRoutes(RouteCollection routes){ routes.MapMvcAttributeRoutes(); // routes.MapRoute...} Now with MVC5, Attribute Routing has been absorbed into the project. You can now use: [Route("My-Action")] On Action Methods. For controllers, you can apply a RoutePrefix attribute which will be applied to all action methods in that controller: [RoutePrefix("my-controller")] One of the benefits of using RoutePrefix is URL parameters will also be passed down to any action methods. [RoutePrefix("clients/{clientId:int}")]public class ClientsController : Controller ..... Snip.. [Route("edit-client")]public ActionResult Edit(int clientId) // will match /clients/123/edit-client | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/30310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
]
} |
30,319 | Is there a tag in HTML that will only display its content if JavaScript is enabled? I know <noscript> works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it. The only way I know how to do this is with the document.write(); method in a script tag, and it seems a bit messy for large amounts of HTML. | Easiest way I can think of: <html><head> <noscript><style> .jsonly { display: none } </style></noscript></head><body> <p class="jsonly">You are a JavaScript User!</p></body></html> No document.write, no scripts, pure CSS. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/30319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
]
} |
30,328 | How do you OCR an tiff file using Tesseract's interface in c#? Currently I only know how to do it using the executable. | Take a look at tessnet | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3249/"
]
} |
30,337 | Is there an online resource somewhere that maintains statistics on the install-base of Java including JRE version information? If not, is there any recent report that has some numbers? I'm particularly interested in Windows users, but all other OS's are welcome too. | Take a look at tessnet | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2881/"
]
} |
30,373 | I remember first learning about vectors in the STL and after some time, I wanted to use a vector of bools for one of my projects. After seeing some strange behavior and doing some research, I learned that a vector of bools is not really a vector of bools . Are there any other common pitfalls to avoid in C++? | A short list might be: Avoid memory leaks through use shared pointers to manage memory allocation and cleanup Use the Resource Acquisition Is Initialization (RAII) idiom to manage resource cleanup - especially in the presence of exceptions Avoid calling virtual functions in constructors Employ minimalist coding techniques where possible - for example, declaring variables only when needed, scoping variables, and early-out design where possible. Truly understand the exception handling in your code - both with regard to exceptions you throw, as well as ones thrown by classes you may be using indirectly. This is especially important in the presence of templates. RAII, shared pointers and minimalist coding are of course not specific to C++, but they help avoid problems that do frequently crop up when developing in the language. Some excellent books on this subject are: Effective C++ - Scott Meyers More Effective C++ - Scott Meyers C++ Coding Standards - Sutter & Alexandrescu C++ FAQs - Cline Reading these books has helped me more than anything else to avoid the kind of pitfalls you are asking about. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
]
} |
30,379 | We have a Windows Server Web Edition 2003 Web Farm. What can we use that handles replication across the servers for: Content & IIS Configuration (App Pools, Virtual Directories, etc...) We will be moving to Windows 2008 in the near future, so I guess what options are there on Windows 2008 as well. | A short list might be: Avoid memory leaks through use shared pointers to manage memory allocation and cleanup Use the Resource Acquisition Is Initialization (RAII) idiom to manage resource cleanup - especially in the presence of exceptions Avoid calling virtual functions in constructors Employ minimalist coding techniques where possible - for example, declaring variables only when needed, scoping variables, and early-out design where possible. Truly understand the exception handling in your code - both with regard to exceptions you throw, as well as ones thrown by classes you may be using indirectly. This is especially important in the presence of templates. RAII, shared pointers and minimalist coding are of course not specific to C++, but they help avoid problems that do frequently crop up when developing in the language. Some excellent books on this subject are: Effective C++ - Scott Meyers More Effective C++ - Scott Meyers C++ Coding Standards - Sutter & Alexandrescu C++ FAQs - Cline Reading these books has helped me more than anything else to avoid the kind of pitfalls you are asking about. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2349/"
]
} |
30,397 | I am trying to set up dynamic per-item menus (Edit Control Block) in SharePoint 2007. My goal is to have certain features that are available based on the current user's group membership. I know that the CustomAction tag that controls the creation of this menu item has a Rights attribute. The problem that I have with this is that the groups I am using have identical rights in the site (ViewListItems, ManageAlerts, etc). The groups that we have set up deal more with function, such as Manager, Employee, etc. We want to be able to assign a custom feature to a group, and have the menu items associated with that feature visible only to members of that group. Everyone has the same basic site permissions, but will have extra options availble based on their login credentials. I have seen several articles on modifying the Core.js file to hide items in the context menu, but they are an all-or-nothing approach. There is an interesting post at http://blog.thekid.me.uk/archive/2008/04/29/sharepoint-custom-actions-in-a-list-view-webpart.aspx that shows how to dynamically modify the Actions menu. It is trivial to modify this example to check the users group and show or hide the menu based on membership. Unfortunately, this example does not seem to apply to context menu items as evidenced here http://forums.msdn.microsoft.com/en-US/sharepointdevelopment/thread/c2259839-24c4-4a7e-83e5-3925cdd17c44/ . Does anyone know of a way to do this without using javascript? If not, what is the best way to check the user's group from javascript? | A short list might be: Avoid memory leaks through use shared pointers to manage memory allocation and cleanup Use the Resource Acquisition Is Initialization (RAII) idiom to manage resource cleanup - especially in the presence of exceptions Avoid calling virtual functions in constructors Employ minimalist coding techniques where possible - for example, declaring variables only when needed, scoping variables, and early-out design where possible. Truly understand the exception handling in your code - both with regard to exceptions you throw, as well as ones thrown by classes you may be using indirectly. This is especially important in the presence of templates. RAII, shared pointers and minimalist coding are of course not specific to C++, but they help avoid problems that do frequently crop up when developing in the language. Some excellent books on this subject are: Effective C++ - Scott Meyers More Effective C++ - Scott Meyers C++ Coding Standards - Sutter & Alexandrescu C++ FAQs - Cline Reading these books has helped me more than anything else to avoid the kind of pitfalls you are asking about. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
]
} |
30,485 | I have a simple webform that will allow unauthenticated users to input their information, including name. I gave the name field a limit of 50 characters to coincide with my database table where the field is varchar(50) , but then I started to wonder. Is it more appropriate to use something like the Text column type or should I limit the length of the name to something reasonable? I'm using SQL Server 2005, in case that matters in your response. EDIT: I did not see this broader question regarding similar issues. | UK Government Data Standards Catalogue suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/30485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106/"
]
} |
30,494 | Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version. Suggestions or improvements, please! /// <summary> /// Compares two specified version strings and returns an integer that /// indicates their relationship to one another in the sort order. /// </summary> /// <param name="strA">the first version</param> /// <param name="strB">the second version</param> /// <returns>less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB</returns> public static int CompareVersions(string strA, string strB) { char[] splitTokens = new char[] {'.', ','}; string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); int[] versionA = new int[4]; int[] versionB = new int[4]; for (int i = 0; i < 4; i++) { versionA[i] = Convert.ToInt32(strAsplit[i]); versionB[i] = Convert.ToInt32(strBsplit[i]); } // now that we have parsed the input strings, compare them return RecursiveCompareArrays(versionA, versionB, 0); } /// <summary> /// Recursive function for comparing arrays, 0-index is highest priority /// </summary> private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx) { if (versionA[idx] < versionB[idx]) return -1; else if (versionA[idx] > versionB[idx]) return 1; else { Debug.Assert(versionA[idx] == versionB[idx]); if (idx == versionA.Length - 1) return 0; else return RecursiveCompareArrays(versionA, versionB, idx + 1); } } @ Darren Kopp : The version class does not handle versions of the format 1.0.0.5. | The System.Version class does not support versions with commas in it, so the solution presented by Darren Kopp is not sufficient. Here is a version that is as simple as possible (but no simpler). It uses System.Version but achieves compatibility with version numbers like "1, 2, 3, 4" by doing a search-replace before comparing. /// <summary> /// Compare versions of form "1,2,3,4" or "1.2.3.4". Throws FormatException /// in case of invalid version. /// </summary> /// <param name="strA">the first version</param> /// <param name="strB">the second version</param> /// <returns>less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB</returns> public static int CompareVersions(String strA, String strB) { Version vA = new Version(strA.Replace(",", ".")); Version vB = new Version(strB.Replace(",", ".")); return vA.CompareTo(vB); } The code has been tested with: static void Main(string[] args) { Test("1.0.0.0", "1.0.0.1", -1); Test("1.0.0.1", "1.0.0.0", 1); Test("1.0.0.0", "1.0.0.0", 0); Test("1, 0.0.0", "1.0.0.0", 0); Test("9, 5, 1, 44", "3.4.5.6", 1); Test("1, 5, 1, 44", "3.4.5.6", -1); Test("6,5,4,3", "6.5.4.3", 0); try { CompareVersions("2, 3, 4 - 4", "1,2,3,4"); Console.WriteLine("Exception should have been thrown"); } catch (FormatException e) { Console.WriteLine("Got exception as expected."); } Console.ReadLine(); } private static void Test(string lhs, string rhs, int expected) { int result = CompareVersions(lhs, rhs); Console.WriteLine("Test(\"" + lhs + "\", \"" + rhs + "\", " + expected + (result.Equals(expected) ? " succeeded." : " failed.")); } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/30494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
]
} |
30,505 | I frequently work with multiple instances of Visual Studio, often working on different branches of the same solution. Visual C++ 6.0 used to display the full path of the current source file in its title bar, but Visual Studio 2005 doesn't appear to do this. This makes it slightly more awkward than it should be to work out which branch of the solution I'm currently looking at (the quickest way I know of is to hover over a tab so you get the source file's path as a tooltip). Is there a way to get the full solution or file path into the title bar, or at least somewhere that's always visible, so I can quickly tell which branch is loaded into each instance? | There is not a native way to do it, but you can achieve it with a macro. The details are described here in full: How To Show Full File Path (or Anything Else) in VS 2005 Title Bar You just have to add a little Visual Basic macro to the EvironmentEvents macro section and restart Visual Studio. Note: The path will not show up when you first load Visual Studio, but it will whenever you change which file you are viewing. There is probably a way to fix this, but it doesn't seem like a big deal. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/30505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739/"
]
} |
30,569 | Does anyone have the secret formula to resizing transparent images (mainly GIFs) without ANY quality loss - what so ever? I've tried a bunch of stuff, the closest I get is not good enough. Take a look at my main image: http://www.thewallcompany.dk/test/main.gif And then the scaled image: http://www.thewallcompany.dk/test/ScaledImage.gif //Internal resize for indexed colored imagesvoid IndexedRezise(int xSize, int ySize){ BitmapData sourceData; BitmapData targetData; AdjustSizes(ref xSize, ref ySize); scaledBitmap = new Bitmap(xSize, ySize, bitmap.PixelFormat); scaledBitmap.Palette = bitmap.Palette; sourceData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { targetData = scaledBitmap.LockBits(new Rectangle(0, 0, xSize, ySize), ImageLockMode.WriteOnly, scaledBitmap.PixelFormat); try { xFactor = (Double)bitmap.Width / (Double)scaledBitmap.Width; yFactor = (Double)bitmap.Height / (Double)scaledBitmap.Height; sourceStride = sourceData.Stride; sourceScan0 = sourceData.Scan0; int targetStride = targetData.Stride; System.IntPtr targetScan0 = targetData.Scan0; unsafe { byte* p = (byte*)(void*)targetScan0; int nOffset = targetStride - scaledBitmap.Width; int nWidth = scaledBitmap.Width; for (int y = 0; y < scaledBitmap.Height; ++y) { for (int x = 0; x < nWidth; ++x) { p[0] = GetSourceByteAt(x, y); ++p; } p += nOffset; } } } finally { scaledBitmap.UnlockBits(targetData); } } finally { bitmap.UnlockBits(sourceData); }} I'm using the above code, to do the indexed resizing. Does anyone have improvement ideas? | If there's no requirement on preserving file type after scaling I'd recommend the following approach. using (Image src = Image.FromFile("main.gif"))using (Bitmap dst = new Bitmap(100, 129))using (Graphics g = Graphics.FromImage(dst)){ g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(src, 0, 0, dst.Width, dst.Height); dst.Save("scale.png", ImageFormat.Png);} The result will have really nice anti aliased edges removed image shack image that had been replaced by an advert If you must export the image in gif you're in for a ride; GDI+ doesn't play well with gif. See this blog post about it for more information Edit: I forgot to dispose of the bitmaps in the example; it's been corrected | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2972/"
]
} |
30,571 | In Maven, dependencies are usually set up like this: <dependency> <groupId>wonderful-inc</groupId> <artifactId>dream-library</artifactId> <version>1.2.3</version></dependency> Now, if you are working with libraries that have frequent releases, constantly updating the <version> tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)? | NOTE: The mentioned LATEST and RELEASE metaversions have been dropped for plugin dependencies in Maven 3 "for the sake of reproducible builds" , over 6 years ago.(They still work perfectly fine for regular dependencies.)For plugin dependencies please refer to this Maven 3 compliant solution . If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using. When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all. See the POM Syntax section of the Maven book for more details. Or see this doc on Dependency Version Ranges , where: A square bracket ( [ & ] ) means "closed" (inclusive). A parenthesis ( ( & ) ) means "open" (exclusive). Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata: <?xml version="1.0" encoding="UTF-8"?><metadata> <groupId>com.foo</groupId> <artifactId>my-foo</artifactId> <version>2.0.0</version> <versioning> <release>1.1.1</release> <versions> <version>1.0</version> <version>1.0.1</version> <version>1.1</version> <version>1.1.1</version> <version>2.0.0</version> </versions> <lastUpdated>20090722140000</lastUpdated> </versioning></metadata> If a dependency on that artifact is required, you have the following options (other version ranges can be specified of course, just showing the relevant ones here): Declare an exact version (will always resolve to 1.0.1): <version>[1.0.1]</version> Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version): <version>1.0.1</version> Declare a version range for all 1.x (will currently resolve to 1.1.1): <version>[1.0.0,2.0.0)</version> Declare an open-ended version range (will resolve to 2.0.0): <version>[1.0.0,)</version> Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x) <version>LATEST</version> Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x): <version>RELEASE</version> Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the Maven super POM . You can do this with either "-Prelease-profile" or "-DperformRelease=true" It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results). It is therefore generally a good idea to define exact versions in releases. As Tim's answer points out, the maven-versions-plugin is a handy tool for updating dependency versions, particularly the versions:use-latest-versions and versions:use-latest-releases goals. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/30571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709/"
]
} |
30,632 | What is the difference in terms of functionality between the Apache HTTP Server and Apache Tomcat? I know that Tomcat is written in Java and the HTTP Server is in C, but other than that I do not really know how they are distinguished. Do they have different functionality? | Apache Tomcat is used to deploy your Java Servlets and JSPs. So in your Java project you can build your WAR (short for Web ARchive) file, and just drop it in the deploy directory in Tomcat. So basically Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies. Tomcat includes Catalina, which is a servlet container. A servlet, at the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (HttpServlet), which is then compiled to .class files by the server and executed by the Java virtual machine. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/30632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
]
} |
30,651 | I would like to know if I can open 2 different diagrams using MS Visio and each diagram have its own window. I've tried in several ways, but I always end up with 1 Visio window ... I'm using a triple monitor setup and I'd like to put one diagram to each side of my main monitor. []'s André Casteliano PS: I'm using Visio 2007 here. | This allows you to open two or more instances of Visio so that you can view different Visio docs at the same time without going through the process to stretch the Visio window across two screens. I found this to be a simpler method and a bit easier to manipulate. If it doesn't work on your first try recheck the registry setting. It changed back on me a couple of times before it took. To implement the new behaviour, follow the following registry trick: Open Microsoft Visio. Go to Tools -> Options -> Advanced or File -> Options -> Advanced in newer versions. Check the Put all settings in Windows Registry option. Close Microsoft Visio Run Registry Editor (regedit). Navigate to the following registry key: HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Visio\Application\ Note: The value 12.0 in the key can be different.(i.e: for Visio 2010: 14.0 , Visio 2019: 16.0 ) In the right pane, right click on SingleInstanceFileOpen , and then select Modify. Update the value of SingleInstanceFileOpen from 1 to 0 If the value SingleInstanceFileOpen doesn't exist , it can be created as a type REG_SZ. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213/"
]
} |
30,660 | I'm running a master-slave MySQL binary log replication system (phew!) that, for some data, is not in sync (meaning, the master holds more data than the slave). But the slave stops very frequently on the slightest MySQL error, can this be disabled? (perhaps a my.cnf setting for the replicating slave ignore-replicating-errors or some of the sort ;) ) This is what happens, every now and then, when the slave tries to replicate an item that does not exist, the slave just dies. a quick check at SHOW SLAVE STATUS \G; gives Slave-IO-Running: Yes Slave-SQL-Running: No Replicate-Do-DB: Last-Errno: 1062 Last-Error: Error 'Duplicate entry '15218' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO db.table ( FIELDS ) VALUES ( VALUES )' which I promptly fix (once I realize that the slave has been stopped) by doing the following: STOP SLAVE;RESET SLAVE;START SLAVE; ... lately this has been getting kind of tiresome, and before I spit out some sort of PHP which does this for me, i was wondering if there's some my.cnf entry which will not kill the slave on the first error. Cheers, /mp | Yes, with --slave-skip-errors=xxx in my.cnf, where xxx is 'all' or a comma sep list of error codes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
]
} |
30,686 | How can you get the version information from a .dll or .exe file in PowerShell? I am specifically interested in File Version , though other version information (that is, Company , Language , Product Name , etc.) would be helpful as well. | Since PowerShell can call .NET classes, you could do the following: [System.Diagnostics.FileVersionInfo]::GetVersionInfo("somefilepath").FileVersion Or as noted here on a list of files: get-childitem * -include *.dll,*.exe | foreach-object { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion } Or even nicer as a script: https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/ | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/30686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2495/"
]
} |
30,710 | I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files. I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access. | I would suggest mocking out your calls to the database. Mocks are basically objects that look like the object you are trying to call a method on, in the sense that they have the same properties, methods, etc. available to caller. But instead of performing whatever action they are programmed to do when a particular method is called, it skips that altogether, and just returns a result. That result is typically defined by you ahead of time. In order to set up your objects for mocking, you probably need to use some sort of inversion of control/ dependency injection pattern, as in the following pseudo-code: class Bar{ private FooDataProvider _dataProvider; public instantiate(FooDataProvider dataProvider) { _dataProvider = dataProvider; } public getAllFoos() { // instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction return _dataProvider.GetAllFoos(); }}class FooDataProvider{ public Foo[] GetAllFoos() { return Foo.GetAll(); }} Now in your unit test, you create a mock of FooDataProvider, which allows you to call the method GetAllFoos without having to actually hit the database. class BarTests{ public TestGetAllFoos() { // here we set up our mock FooDataProvider mockRepository = MockingFramework.new() mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider); // create a new array of Foo objects testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()} // the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos, // instead of calling to the database and returning whatever is in there // ExpectCallTo and Returns are methods provided by our imaginary mocking framework ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray) // now begins our actual unit test testBar = new Bar(mockFooDataProvider) baz = testBar.GetAllFoos() // baz should now equal the testFooArray object we created earlier Assert.AreEqual(3, baz.length) }} A common mocking scenario, in a nutshell. Of course you will still probably want to unit test your actual database calls too, for which you will need to hit the database. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
30,754 | Reading this question I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way). 100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n* Obviously this is an intellectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies? Edit: I'm sorry, seeing the answers I might have expressed the question badly (English is not my native language). I don't mean performance vs readability only after you've written the code, I ask about before you write it as well. Sometimes you can foresee a performance improvement in the future by making some darker design or providing with some properties that will make your class darker. You may decide you will use multiple threads or just a single one because you expect the scalability that such threads may give you, even when that will make the code much more difficult to understand. | My process for situations where I think performance may be an issue: Make it work. Make it clear. Test the performance. If there are meaningful performance issues: refactor for speed. Note that this does not apply to higher-level design decisions that are more difficult to change at a later stage. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/30754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2695/"
]
} |
30,790 | I can connect with the DataContext to the Oracle database however I get errors in running the query against the oracle database. I looked at the SQL generated and it is for MSSQL and not Oracle PSQL. Does anybody know of a decent easy to use wrapper to use LINQ against an Oracle Database? | No, LINQ to SQL is very much MS SQL only - think of it as a client driver. Microsoft is/was helping Oracle and DataDirect develop providers for Oracle and other non-MS database servers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
]
} |
30,811 | I would like to create a database backed interactive AJAX webapp which has a custom (specific kind of events, editing) calendaring system. This would involve quite a lot of JavaScript and AJAX, and I thought about Google Web Toolkit for the interface and Ruby on Rails for server side. Is Google Web Toolkit reliable and good? What hidden risks might be if I choose Google Web Toolkit? Can one easily combine it with Ruby on Rails on server side? Or should I try to use directly a JavaScript library like jQuery? I have no experience in web development except some HTML, but I am an experienced programmer (c++, java, c#), and I would like to use only free tools for this project. | RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea here . That's not to say that you won't have any problems, but I think the support is definitely out there for it. There's a neat project for making RoR/GWT easy that you can find here (MIT license). I haven't had a chance to try it out yet, but it looks like a good amount of thought has been put into it. One catch is that it looks like it hasn't been fully tested with 2.1 Rails yet, just 2.0, so you may run into a few (probably minor and fixable) errors. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2534/"
]
} |
30,835 | Is there any Visual Studio Express plug ins for source versioning? I am starting a project on my own and only have the Express version of Visual Studio 2008. | Short answer: No. The Express editions support neither the Add-Ins nor Source Control providers (SCC plug-ins). While there are ways to make this work, they are undocumented, violate the license and have caused legal trouble before… | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
]
} |
30,847 | How does one go about authoring a Regular Expression that matches against all strings that are valid URIs, while failing to match against all strings that are invalid URIs? To be specific about what I am referencing when I say URI, I have added a link below for the most current URI RFC standard. It defines the entity that I want to validate using a regular expression. I don't need it to be able to parse the URI. I just need a regular expression for validating. The .Net Regular Expression Format is preferred. (.Net V1.1) My Current Solution: ^([a-zA-Z0-9+.-]+):(//([a-zA-Z0-9-._~!$&'()*+,;=:]*)@)?([a-zA-Z0-9-._~!$&'()*+,;=]+)(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(\#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$ | Does Uri.IsWellFormedUriString work for you? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80/"
]
} |
30,856 | How do I write the results from a mysql query to file? I just need something quick. Output can be CSV, XML, HTML, etc. | SELECT a,b,a+b FROM test_table INTO OUTFILE '/tmp/result.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' (the docs show INTO OUTFILE up in the SELECT .. portion which may work as well, but I've never tried it that way) http://dev.mysql.com/doc/refman/5.0/en/select.html INTO OUTFILE creates a file on the server; if you are on a client and want it there, do: mysql -u you -p -e "SELECT ..." > file_name | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2363/"
]
} |
30,879 | Is there a pattern using Linq to dynamically create a filter? I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq. | Check out the Dynamic Linq Library from ScottGu's blog: For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control: Dim Northwind As New NorthwindDataContextDim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select pGridview1.DataSource = queryGridView1.DataBind() Using the LINQ DynamicQuery library I could re-write the above query expression instead like so Dim Northwind As New NorthwindDataContextDim query = Northwind.Products .where("CategoryID=2 And UnitPrice>3") . OrderBy("SupplierId")Gridview1.DataSource = queryGridView1.DataBind() Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2858/"
]
} |
30,884 | Suppose you have two seperate ASP.NET Web Application projects that both need to use a common MasterPage. What's the best way to share the MasterPage across projects without having to duplicate code? Preferably without having to resort to source control or file system hacks. | I have trying to accomplish the same thing. I look into a couple of solutions but I think using a virtual directory is probably the best way to share master pages. Here are a couple sources that you can look at. Sharing Master Pages amongstApplications by Embedding it in aDll Sharing Master Pages in Visual Studio ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps The third bullets near the end the article tells you of possible ways you can share Masterpages also. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247/"
]
} |
30,903 | Is there a good, native Mac tool to view Mercurial repositories, similar to gitnub for Git? | I know it's pretty old question, however just for sake of completeness, I think it is still worth to mention here the newest kid on the block called Murky . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3071/"
]
} |
30,931 | I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files. How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time. | Use xdg-utils from freedesktop.org Portland . Register the icon for the MIME type: xdg-icon-resource install --context mimetypes --size 48 myicon-file-type.png x-application-mytype Create a configuration file ( freedesktop Shared MIME documentation ): <?xml version="1.0"?><mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> <mime-type type="application/x-mytype"> <comment>A witty comment</comment> <comment xml:lang="it">Uno Commento</comment> <glob pattern="*.myapp"/> </mime-type></mime-info> Install the configuration file: xdg-mime install mytype-mime.xml This gets your files recognized and associated with an icon. xdg-mime default can be used for associating an application with the MIME type after you get a .desktop file installed. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/30931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3306/"
]
} |
30,946 | What is a good, simple encryption scheme for protecting passwords in a database? I don't necessarily need anything that's hyper-secure nor do I need anything that's lightning fast, but those things would be nice. Primarily, I just want something that's easy to implement without being terribly slow or insecure. | As mk says, SHA1 or MD5 are the standard ones, along with SHA2 . Update: As processors have gotten faster over the years, hashes have gotten more brute-forceable. It's now recommended you use bcrypt . Another update: bcrypt is still probably good, but if I was writing a new system today I would use scrypt . What you want is more generally called a cryptographic hash function. Cryptographic hashes are designed to be one-way (given the resulting hash, you shouldn't be able to derive the original input). Also, the likelihood of two arbitrary strings having the same hash (known as a hash collision) should be low (ideally 1/number of hash values). Unfortunately, just because your passwords are hashed doesn't free you from having to try really hard to keep the hashed versions safe. Far too many people will use weak passwords that would be vulnerable to an off-line brute-force attack. Edit - several people have also already pointed out the importance of using a salt. A salt is a constant value that you mix in with the input before using the hash function. Having a unique salt prevents off-line attackers from using pre-computed tables of common passwords (rainbow tables) to brute-force your passwords even faster. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/30946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
30,998 | I like to use static functions in C++ as a way to categorize them, like C# does. Console::WriteLine("hello") Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory? What about static const ? | but is it good or bad The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class? The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/30998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
]
} |
31,031 | What's the best way to allow a user to browse for a file in C#? | using (OpenFileDialog dlg = new OpenFileDialog()){ dlg.Title = "Select a file"; if (dlg.ShowDialog()== DialogResult.OK) { //do something with dlg.FileName }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177/"
]
} |
31,044 | How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something} Is there a more elegant way to approach this? Perhaps a plugin or a function? | In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false , everything else true . So you could write: if ($(selector).length) You don't need that >0 part. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/31044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302/"
]
} |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#? I know to do it using plan String.Replace , like: myStr.Replace("\n", "\r\n");myStr.Replace("\r\r\n", "\r\n"); However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | Will this do? [^\r]\n Basically it matches a '\n' that is preceded with a character that is not '\r'. If you want it to detect lines that start with just a single '\n' as well, then try ([^\r]|$)\n Which says that it should match a '\n' but only those that is the first character of a line or those that are not preceded with '\r' There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea. EDIT: credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes: myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n"); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
]
} |
31,057 | I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question. | I found the answer here: http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/ You just concatenate the string and insert a CHAR(13) where you want your line break. Example: DECLARE @text NVARCHAR(100)SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'SELECT @text This prints out the following: This is line 1. This is line 2. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/31057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
]
} |
31,059 | In VS .NET, when you are selecting a folder for a project, a dialog that looks like an OpenFileDialog or SaveFileDialog is displayed, but is set up to accept only folders. Ever since I've seen this I've wanted to know how it's done. I am aware of the FolderBrowserDialog, but I've never really liked that dialog. It starts too small and doesn't let me take advantage of being able to type a path. I'm almost certain by now there's not a way to do this from .NET, but I'm just as curious how you do it from unmanaged code as well. Short of completely reimplementing the dialog from scratch, how do you modify the dialog to have this behavior? I'd also like to restate that I am aware of the FolderBrowserDialog but sometimes I don't like to use it, in addition to being genuinely curious how to configure a dialog in this manner. Telling me to just use the FolderBrowserDialog helps me maintain a consistent UI experience but doesn't satisfy my curiosity so it won't count as an answer. It's not a Vista-specific thing either; I've been seeing this dialog since VS .NET 2003, so it is doable in Win2k and WinXP. This is less of a "I want to know the proper way to do this" question and more of a "I have been curious about this since I first wanted to do it in VS 2003" question. I understand that Vista's file dialog has an option to do this, but it's been working in XP so I know they did something to get it to work. Vista-specific answers are not answers, because Vista doesn't exist in the question context. Update: I'm accepting Scott Wisniewski's answer because it comes with a working sample, but I think Serge deserves credit for pointing to the dialog customization (which is admittedly nasty from .NET but it does work) and Mark Ransom for figuring out that MS probably rolled a custom dialog for this task. | I have a dialog that I wrote called an OpenFileOrFolder dialog that allows you to open either a folder or a file. If you set its AcceptFiles value to false, then it operates in only accept folder mode. You can download the source from GitHub here | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547/"
]
} |
31,068 | How do I find the 'temp' directory in Linux? I am writing a platform neutral C++ function that returns the temp directory. In Mac and Windows, there is an API that returns these results. In Linux, I'm stumped. | Check following variables: The environment variable TMPDIR The value of the P_tmpdir macro If all fails try to use the directory /tmp . You can also use tempnam function to generate a unique temporary file name. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3313/"
]
} |
31,096 | I'm trying to find out how much memory my own .Net server process is using (for monitoring and logging purposes). I'm using: Process.GetCurrentProcess().PrivateMemorySize64 However, the Process object has several different properties that let me read the memory space used:Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet and then the "peaks": which i'm guessing just store the maximum values these last ones ever took. Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited. So my question is obviously "which one should I use?", and I know the answer is "it depends". This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside. So... Which one should I use and why? | If you want to know how much the GC uses try: GC.GetTotalMemory(true) If you want to know what your process uses from Windows (VM Size column in TaskManager) try: Process.GetCurrentProcess().PrivateMemorySize64 If you want to know what your process has in RAM (as opposed to in the pagefile) (Mem Usage column in TaskManager) try: Process.GetCurrentProcess().WorkingSet64 See here for more explanation on the different sorts of memory. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
]
} |
31,127 | When running a Java app from eclipse my ImageIcon shows up just fine. But after creating a jar the path to the image obviously gets screwed up. Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this? I'd like to distribute a single jar file if possible. | To create an ImageIcon from an image file within the same jars your code is loaded: new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg")) Class.getResource returns a URL of a resource (or null !). ImageIcon has a constructors that load from a URL. To construct a URL for a resource in a jar not on your "classpath", see the documentation for java.net.JarURLConnection . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
} |
31,129 | I want to return StudentId to use elsewhere outside of the scope of the $.getJSON() j.getJSON(url, data, function(result){ var studentId = result.Something;});//use studentId here I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does | Yeah, my previous answer does not work because I didn't pay any attention to your code. :) The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should: var studentId = null;j.getJSON(url, data, function(result){ studentId = result.Something;});// studentId is still null right here, because this line // executes before the line that sets its value to result.Something Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
]
} |
31,163 | In Visual Studio 2005, whenever I would view a file in the main editor, the Solution Explorer would find and highlight that file. Some time ago, this stopped working and the Solution Explorer would do nothing. This has become quite a pain since following a chain of "Go To Definition"s can lead you all over your solution. Where is the setting to turn this back on? | Click on the Tools → Options menu. Select the Projects and Solutions → General option page. Make sure "Track active item in Solution Explorer" is checked. That should do it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.