source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
112,248 | I've always been interested in developing a web search engine. What's a good place to start? I've heard of Lucene, but I'm not a big Java guy. Any other good resources or open source projects? I understand it's a huge under-taking, but that's part of the appeal. I'm not looking to create the next Google, just something I can use to search a sub-set of sites that I might be interested in. | There are several parts to a search engine. Broadly speaking, in a hopelessly general manner (folks, feel free to edit if you feel you can add better descriptions, links, etc): The crawler . This is the part that goes through the web, grabs the pages, and stores information about them into some central data store. In addition to the text itself, you will want things like the time you accessed it, etc. The crawler needs to be smart enough to know how often to hit certain domains, to obey the robots.txt convention, etc. The parser . This reads the data fetched by the crawler, parses it, saves whatever metadata it needs to, throws away junk, and possibly makes suggestions to the crawler on what to fetch next time around. The indexer . Reads the stuff the parser parsed, and creates inverted indexes into the terms found on the webpages. It can be as smart as you want it to be -- apply NLP techniques to make indexes of concepts, cross-link things, throw in synonyms, etc. The ranking engine . Given a few thousand URLs matching "apple", how do you decide which result is the best? Jut the index doesn't give you that information. You need to analyze the text, the linking structure, and whatever other pieces you want to look at, and create some scores. This may be done completely on the fly (that's really hard), or based on some pre-computed notions of "experts" (see PageRank, etc). The front end . Something needs to receive user queries, hit the central engine, and respond; this something needs to be smart about caching results, possibly mixing in results from other sources, etc. It has its own set of problems. My advice -- choose which of these interests you the most, download Lucene or Xapian or any other open source project out there, pull out the bit that does one of the above tasks, and try to replace it. Hopefully, with something better :-). Some links that may prove useful: "Agile web-crawler" , a paper from Estonia (in English) Sphinx Search engine , an indexing and search api. Designed for large DBs, but modular and open-ended. "Information Retrieval , a textbook about IR from Manning et al. Good overview of how the indexes are built, various issues that come up, as well as some discussion of crawling, etc. Free online version (for now)! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/112248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20062/"
]
} |
112,277 | Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example: #include <iostream>using namespace std;template< int n >struct factorial { enum { ret = factorial< n - 1 >::ret * n }; };template<>struct factorial< 0 > { enum { ret = 1 }; };int main() { cout << "7! = " << factorial< 7 >::ret << endl; // 5040 return 0;} If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)? | [Answering my own question] The best introductions I've found so far are chapter 10, "Static Metaprogramming in C++" from Generative Programming, Methods, Tools, and Applications by Krzysztof Czarnecki and Ulrich W. Eisenecker, ISBN-13: 9780201309775; and chapter 17, "Metaprograms" of C++ Templates: The Complete Guide by David Vandevoorder and Nicolai M. Josuttis, ISBN-13: 9780201734843. Todd Veldhuizen has an excellent tutorial here . A good resource for C++ programming in general is Modern C++ Design by Andrei Alexandrescu, ISBN-13: 9780201704310. This book mixes a bit of metaprogramming with other template techniques. For metaprogramming in particular, see sections 2.1 "Compile-Time Assertions", 2.4 "Mapping Integral Constants to Types", 2.6 "Type Selection", 2.7 "Detecting Convertibility and Inheritance at Compile Time", 2.9 " NullType and EmptyType " and 2.10 "Type Traits". The best intermediate/advanced resource I've found is C++ Template Metaprogramming by David Abrahams and Aleksey Gurtovoy, ISBN-13: 9780321227256 If you'd prefer just one book, get C++ Templates: The Complete Guide since it is also the definitive reference for templates in general. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/112277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
]
} |
112,320 | I am a fan of static metaprogramming in C++ . I know Java now has generics. Does this mean that static metaprogramming (i.e., compile-time program execution) is possible in Java? If so, can anyone recommend any good resources where one can learn more about it? | No, this is not possible. Generics are not as powerful as templates. For instance, a template argument can be a user-defined type, a primitive type, or a value; but a generic template argument can only be Object or a subtype thereof. Edit: This is an old answer; since 2011 we have Java 7, which has Annotations that can be used for such trickery . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
]
} |
112,396 | I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit ( Git and SVN ) to a remote location over SSH many times in an hour. One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys? | Short answer: $ ssh-keygen -p This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase). If you would like to do it all on one line without prompts do: $ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile] Important: Beware that when executing commands they will typically be logged in your ~/.bash_history file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise. Notice though that you can still use -f keyfile without having to specify -P nor -N , and that the keyfile defaults to ~/.ssh/id_rsa , so in many cases, it's not even needed. You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/112396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14191/"
]
} |
112,433 | In a C++ project I'm working on, I have a flag kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be: new record deleted record modified record existing record Now, for each record I wish to keep this attribute, so I could use an enum: enum { xNew, xDeleted, xModified, xExisting } However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like: showRecords(xNew | xDeleted); So, it seems I have three possible appoaches: #define X_NEW 0x01#define X_DELETED 0x02#define X_MODIFIED 0x04#define X_EXISTING 0x08 or typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType; or namespace RecordType { static const uint8 xNew = 1; static const uint8 xDeleted = 2; static const uint8 xModified = 4; static const uint8 xExisting = 8;} Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with enum I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With const I think I also lose type safety since a random uint8 could get in by mistake. Is there some other cleaner way? If not, what would you use and why? P.S. The rest of the code is rather clean modern C++ without #define s, and I have used namespaces and templates in few spaces, so those aren't out of question either. | Combine the strategies to reduce the disadvantages of a single approach. I work in embedded systems so the following solution is based on the fact that integer and bitwise operators are fast, low memory & low in flash usage. Place the enum in a namespace to prevent the constants from polluting the global namespace. namespace RecordType { An enum declares and defines a compile time checked typed. Always use compile time type checking to make sure arguments and variables are given the correct type. There is no need for the typedef in C++. enum TRecordType { xNew = 1, xDeleted = 2, xModified = 4, xExisting = 8, Create another member for an invalid state. This can be useful as error code; for example, when you want to return the state but the I/O operation fails. It is also useful for debugging; use it in initialisation lists and destructors to know if the variable's value should be used. xInvalid = 16 }; Consider that you have two purposes for this type. To track the current state of a record and to create a mask to select records in certain states. Create an inline function to test if the value of the type is valid for your purpose; as a state marker vs a state mask. This will catch bugs as the typedef is just an int and a value such as 0xDEADBEEF may be in your variable through uninitialised or mispointed variables. inline bool IsValidState( TRecordType v) { switch(v) { case xNew: case xDeleted: case xModified: case xExisting: return true; } return false;} inline bool IsValidMask( TRecordType v) { return v >= xNew && v < xInvalid ;} Add a using directive if you want to use the type often. using RecordType ::TRecordType ; The value checking functions are useful in asserts to trap bad values as soon as they are used. The quicker you catch a bug when running, the less damage it can do. Here are some examples to put it all together. void showRecords(TRecordType mask) { assert(RecordType::IsValidMask(mask)); // do stuff;}void wombleRecord(TRecord rec, TRecordType state) { assert(RecordType::IsValidState(state)); if (RecordType ::xNew) { // ...} in runtimeTRecordType updateRecord(TRecord rec, TRecordType newstate) { assert(RecordType::IsValidState(newstate)); //... if (! access_was_successful) return RecordType ::xInvalid; return newstate;} The only way to ensure correct value safety is to use a dedicated class with operator overloads and that is left as an exercise for another reader. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/112433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
]
} |
112,482 | For <script> HTML tags, what is the technical difference between lang=Javascript and type=text/javascript ? I usually use both, because I've always assumed that older browsers need one or the other. | Per the HTML 4.01 Spec : type : This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute. language : Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/112482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16398/"
]
} |
112,503 | Given an array of n Objects, let's say it is an array of strings , and it has the following values: foo[0] = "a";foo[1] = "cc";foo[2] = "a";foo[3] = "dd"; What do I have to do to delete/remove all the strings/objects equal to "a" in the array? | [If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.] To flesh out Dustman's idea : List<String> list = new ArrayList<String>(Arrays.asList(array));list.removeAll(Arrays.asList("a"));array = list.toArray(array); Edit: I'm now using Arrays.asList instead of Collections.singleton : singleton is limited to one entry, whereas the asList approach allows you to add other strings to filter out later: Arrays.asList("a", "b", "c") . Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead: array = list.toArray(new String[0]); Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class: private static final String[] EMPTY_STRING_ARRAY = new String[0]; Then the function becomes: List<String> list = new ArrayList<>();Collections.addAll(list, array);list.removeAll(Arrays.asList("a"));array = list.toArray(EMPTY_STRING_ARRAY); This will then stop littering your heap with useless empty string arrays that would otherwise be new ed each time your function is called. cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it: array = list.toArray(new String[list.size()]); I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling size() on the wrong list). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/112503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358/"
]
} |
112,603 | I am using jProfiler to find memory leaks in a Java swing application. I have identified instances of a JFrame which keeps growing in count. This frame is opened, and then closed. Using jProfiler, and viewing the Paths to GC Root there is only one reference, 'JNI Global reference'. What does this mean? Why is it hanging on to each instance of the frame? | Wikipedia has a good overview of Java Native Interface , essentially it allows communication between Java and native operating system libraries writen in other languages. JNI global references are prone to memory leaks, as they are not automatically garbage collected, and the programmer must explicitly free them. If you are not writing any JNI code yourself, it is possible that the library you are using has a memory leak. edit here is a bit more info on local vs. global references, and why global references are used (and how they should be freed) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18445/"
]
} |
112,613 | running git instaweb in my repository opens a page that says "403 Forbidden - No projects found". What am I missing? | looks like the debian install of git sets $projectroot globally in a way that confuses instaweb . I removed the $projectroot line from /etc/gitweb.conf and the error went away. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13195/"
]
} |
112,625 | So, when I was a comparative novice to the novice I am right now, I used to think that these two things were syntactic sugar for each other, i.e. that using one over the other was simply a personal preference. Over time, I'm come to find that these two are not the same thing, even in a default implementation (see this and this ). To further confuse the matter, each can be overridden/overloaded separately to have completely different meanings. Is this a good thing, what are the differences, and when/why should you use one over the other? | MSDN has clear and solid descriptions of both things. object.Equals method operator == Overloadable Operators Guidelines for Overriding Equals() and Operator == Is this a good thing, what are the differences, and when/why should you use one over the other? How can it be "good" or "bad" thing? One - method, another - operator. If reference equality is not sufficient, overload them, otherwise leave them as is. For primitive types they just work out of box. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
]
} |
112,643 | I know how to create a SEL at compile time using @selector(MyMethodName:) but what I want to do is create a selector dynamically from an NSString . Is this even possible? What I can do: SEL selector = @selector(doWork:);[myobj respondsToSelector:selector]; What I want to do: (pseudo code, this obviously doesn't work) SEL selector = selectorFromString(@"doWork");[myobj respondsToSelector:selector]; I've been searching the Apple API docs, but haven't found a way that doesn't rely on the compile-time @selector(myTarget:) syntax. | I'm not an Objective-C programmer, merely a sympathizer, but maybe NSSelectorFromString is what you need. It's mentioned explicity in the Runtime Reference that you can use it to convert a string to a selector. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/112643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18590/"
]
} |
112,698 | I thought I heard that py2exe was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used? Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs. | PyInstaller will create a single .exe file with no dependencies; use the --onefile option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see minty's answer ) I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/112698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
]
} |
112,721 | I've got the following situation A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality Lot of nice javascript written using jQuery (for a separate application) I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and Scriptaculous clashing (they both define the $() function, etc). What is my easiest option to bring the two together? Thanks! | jQuery.noConflict(); Then use jQuery instead of $ to refer to jQuery. e.g., jQuery('div.foo').doSomething() If you need to adapt jQuery code that uses $, you can surround it with this: (function($) {...your code here...})(jQuery); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16779/"
]
} |
112,738 | Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented? | I like this piece of the bind source: template<class R, class F, class L> class bind_t{public: typedef bind_t this_type; bind_t(F f, L const & l): f_(f), l_(l) {}#define BOOST_BIND_RETURN return#include <boost/bind/bind_template.hpp>#undef BOOST_BIND_RETURN}; Tells you almost all you need to know, really. The bind_template header expands to a list of inline operator() definitions. For example, the simplest: result_type operator()(){ list0 a; BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);} We can see the BOOST_BIND_RETURN macro expands to return at this point so the line is more like return l_(type...) . The one parameter version is here: template<class A1> result_type operator()(A1 & a1){ list1<A1 &> a(a1); BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);} It's pretty similar. The listN classes are wrappers for the parameter lists. There is a lot of deep magic going on here that I don't really understand too much though. They have also overloaded operator() that calls the mysterious unwrap function. Ignoring some compiler specific overloads, it doesn't do a lot: // unwraptemplate<class F> inline F & unwrap(F * f, long){ return *f;}template<class F> inline F & unwrap(reference_wrapper<F> * f, int){ return f->get();}template<class F> inline F & unwrap(reference_wrapper<F> const * f, int){ return f->get();} The naming convention seems to be: F is the type of the function parameter to bind . R is the return type. L tends to be a list of parameter types. There are also a lot of complications because there are no less than nine overloads for different numbers of parameters. Best not to dwell on that too much. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/112738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
112,739 | What is the easiest way, preferably using recursion, to find the shortest root-to-leaf path in a BST (Binary Search Tree). Java prefered, pseudocode okay. Thanks! | General description: Use a Breadth-first search (BFS) as opposed to a Depth-first search (DFS) . Find the first node with no children. Using a DFS you might get lucky on some input trees (but there is no way to know you got lucky so you still need to search the whole tree), but using the BFS method is much faster and you can find a solution without touching all nodes. To find the root to leaf path, you could follow the first found childless node all the way back up to the root using the parent reference. If you have no parent reference stored in each node, you can keep track of the parent nodes as you recurse down. If you have your list in reverse order you could push it all on a stack and then pop it off. Pseudo-code: The problem is very simple; here is pseudo code to find the smallest length: Put the root node on the queue. Repeat while the queue is not empty, and no result was found: Pull a node from the beginning of the queue and check if it has no children. If it has no children you are done you found the shortest path. Otherwise push all the children (left, right) onto the queue. Finding all shortest paths: To find all shortest paths you can store the depth of the node along with node inside the queue. Then you would continue the algorithm for all nodes in the queue with the same depth. Alternative: If instead you decided to use a DFS, you would have to search the entire tree to find the shortest path. But this could be optimized by keeping a value for the shortest so far, and only checking the depth of future nodes up until you find a new shortest, or until you reach the shortest so far. The BFS is a much better solution though. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83819/"
]
} |
112,770 | Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository? | Example: svn switch --relocate \ http://svn.example.com/path/to/repository/path/within/repository \ http://svnnew.example.com/new/repository/path/within/repository One thing which is to remember, lets assume you checked out the project "path/within/repository" then you have to go to the root of your working copy , and execute the above command. it is NOT enough just to use the repository root (as in svn switch --relocate http://svn.example.com/path/to/repository/ http://svnnew.example.com/new/repository/ ), because that wouldn't work. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20150/"
]
} |
112,796 | Is there a way to view the key/value pairs of a NSDictionary variable through the Xcode debugger? Here's the extent of information when it is fully expanded in the variable window: Variable Value SummaryjsonDict 0x45c540 4 key/value pairs NSObject {...} isa 0xa06e0720 I was expecting it to show me each element of the dictionary (similar to an array variable). | In the gdb window you can use po to inspect the object. given: NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];[dict setObject:@"foo" forKey:@"bar"];[dict setObject:@"fiz" forKey:@"buz"]; setting a breakpoint after the objects are added you can inspect what is in the dictionary (gdb) po dict{ bar = foo; buz = fiz;} Of course these are NSString objects that print nicely. YMMV with other complex objects. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/112796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11292/"
]
} |
112,839 | What is the best way to resolve a conflict when doing a git svn rebase , and the git branch you are on becomes "(no-branch)"? | While doing a git svn rebase , if you have merge conflicts here are some things to remember: 1) If anything bad happens while performing a rebase you will end up on a (no-branch) branch. 2) If you run git status , you'll see a .dotest file in your working directory. This is safe to ignore. 3) If you want to abort the rebase use the following command. 1 git rebase --abort 4) If you have a merge conflict: Manually edit the files to resolve the conflicts Stage any changes with git add [file] Continue the rebase with git rebase --continue 2 If git asks: "did you forget to call git add ?", then the edits turned the conflict into a no-op change 3 . Continue with git rebase --skip You may have to repeat this process until the rebase is complete. At any point you can git rebase --abort to cancel and abandon the rebase. 1: There is no --abort option for git svn rebase . 2: There is no --continue option for git svn rebase . 3: This is very strange, but the files are in a state where git thinks they are the same after that particular patch. The solution is to "skip" that patch on the rebase. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/112839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19839/"
]
} |
112,932 | I really like Araxis Merge for a graphical DIFF program for the PC. I have no idea what's available for linux , though. We're running SUSE linux on our z800 mainframe.I'd be most grateful if I could get a few pointers to what programs everyone else likes. | I know of two graphical diff programs: Meld and KDiff3 . I haven't used KDiff3, but Meld works well for me. It seems that both are in the standard package repositories for openSUSE 11.0 | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/112932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20158/"
]
} |
112,941 | I'm a web-guy stuck in "application world" in VS 2005. I created my windows forms program and want to give my end users the ability to install it (and some of it's resources) into a standard Program Files/App Directory location along with a start menu/desktop launcher. The help files don't give any instructions (that I can find). This seems like such a trivial task to create an installer - but it's eluding me. Any hints would be greatly appreciated! | You're looking for a "Setup Project" which should be under the "Other Project Types" -> "Setup and Deployment" category in the "New Project" dialog. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20153/"
]
} |
112,969 | At work I am responsible for writing specifications quite often and I am also the person who insisted on getting specifications in the first place. The problem is I am unsure how specifications should look and what they should contain. A lot of the time when my boss is writing the specifications (we are both inexperienced in it) they put in table names and things that I don't think belong there. So what is a good way to learn to write a good spec? EDIT: Should a functional spec include things like assuming I am specifying a web application, the input types (a textbox, dropdown list, etc)? | The most important part of development documentation in my opinion, is having the correct person do it. Requirements Docs - Users + Business Analyst Functional Spec - Business Analyst + developer Technical Spec (how the functionality will actually be implemented) - Sr. Developer /Architect Time estimates for scheduling purposes - The specific developer assigned to the task Having anyone besides the Sr. Developer / Architect define table structures / interfaces etc. is an exercise in futility - as the more experienced developer will generally throw most of it out. Wikipedia is actually a good start for the Functional Spec, which seems similar to your Spec - http://en.wikipedia.org/wiki/Functional_specification . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18926/"
]
} |
112,970 | What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5) | You should always use open() . As the documentation states: When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)"). Also, file() has been removed since Python 3.0. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/112970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
]
} |
112,983 | I want to display data like the following: Title Subject Summary Date So my HTML looks like: <div class="title"></div><div class="subject"></div><div class="summary"></div><div class="date"></div> The problem is, all the text doesn't appear on a single line. I tried adding display="block" but that doesn't seem to work. What am I doing wrong here? Important: In this instance I dont want to use a table element but stick with div tags. | It looks like you're wanting to display a table, right? So go ahead and use the <table> tag. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/112983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
} |
113,045 | SELECT GETDATE() Returns: 2008-09-22 15:24:13.790 I want that date part without the time part: 2008-09-22 00:00:00.000 How can I get that? | SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date)) for example SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) gives me 2008-09-22 00:00:00.000 Pros: No varchar<->datetime conversions required No need to think about locale | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/113045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5769/"
]
} |
113,077 | I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times. Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)? Thanks! | Don't panic, every fresh Web programmer face this problem. You HAVE TO separate your program logic from your display. First, try to make your own solution using two files for each Web page : one with only PHP code (no HTML) that fills variables another with HTML and very few PHP : this is your page design Then include where / when you need it. E.G : myPageLogic.php <?php// pure PHP code, no HTML$name = htmlspecialchars($_GET['name']);$age = date('Y') - htmlspecialchars($_GET['age']);?> myPageView.php // very few php code// just enought to print variables// and some if / else, or foreach to manage the data stream<h1>Hello, <?php $name ?> !</h1><p>So your are <?php $age?>, hu ?</p> (You may want to use the alternative PHP syntax for this one. But don't try to hard to make it perfect the first time, really.) myPage.php <?phprequire('myPageLogic.php');require('myPageView.php');?> Don't bother about performance issues for now . This is not your priority as a newbie. This solution is imperfect, but will help you to solve the problem with your programming level and will teach you the basics. Then, once your are comfortable with this concept, buy a book about the MVC pattern (or look for stack overflow entries about it). That what you want to do the NEXT TIME . Then you'll try some templating systems and frameworks, but LATER . For now, just code and learn from the beginning. You can perfectly code a project like that, as a rookie, it's fine. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
]
} |
113,150 | I have the following situation: class A{public: A(int whichFoo); int foo1(); int foo2(); int foo3(); int callFoo(); // cals one of the foo's depending on the value of whichFoo}; In my current implementation I save the value of whichFoo in a data member in the constructor and use a switch in callFoo() to decide which of the foo's to call. Alternatively, I can use a switch in the constructor to save a pointer to the right fooN() to be called in callFoo() . My question is which way is more efficient if an object of class A is only constructed once, while callFoo() is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a switch ? Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :) | How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference? In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually measure the different choices. You may be surprised! More info: There is an excellent article Member Function Pointers and the Fastest Possible C++ Delegates which goes into very deep detail about the implementation of member function pointers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13313/"
]
} |
113,170 | It appears the Python signal module doesn't have anything similar to the sighold and sigrelse functions found in C, using signal.h. Are there Python equivalents of any sort? Many thanks! | How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference? In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually measure the different choices. You may be surprised! More info: There is an excellent article Member Function Pointers and the Fastest Possible C++ Delegates which goes into very deep detail about the implementation of member function pointers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
113,224 | What is the highest port number one can use? | The port number is an unsigned 16-bit integer, so 65535. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/113224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4939/"
]
} |
113,267 | In Visual Studio, when I type the line " Implements IDisposable ", the IDE automatically adds: a disposedValue member variable a Sub Dispose() Implements IDisposable.Dispose a Sub Dispose(ByVal disposing As Boolean) The Dispose() should be left alone, and the clean up code should be put in Dispose(disposing) . However the Dispose Finalize Pattern says you should also override Sub Finalize() to call Dispose(False) . Why doesn't the IDE also add this? Must I add it myself, or is it somehow called implicitly? EDIT: Any idea why the IDE automatically adds 80% of the required stuff but leaves out the Finalize method? Isn't the whole point of this kind of feature to help you not forget these things? EDIT2: Thank you all for your excellent answers, this now makes perfect sense! | If you actually are holding non-managed resources that will not be automatically cleaned up by the garbage collector and cleaning those up in your Dispose(), then yes, you should do the same in Finalize(). If you're implementing IDisposable for some other reason, implementing Finalize() isn't required. The basic question is this: If Dispose() wasn't called and your object garbage collected, would memory leak? If yes, implement Finalize. If no, you don't need to. Also, avoid implementing Finalize "just because it's safer". Objects with custom finalizers can potentially need two GC passes to free them -- once to put them on the pending finalizers queue, and a second pass to actually free their memory. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10786/"
]
} |
113,293 | Is it always possible to ping localhost and it resolves to 127.0.0.1? I know Windows Vista, XP, Ubuntu and Debian do it but does everyone do it? | Any correct implementation of TCP/IP will reserve the address 127.0.0.1 to refer to the local machine. However, the mapping of the name "localhost" to that address is generally dependent on the system hosts file. If you were to remove the localhost entry from hosts , then the localhost name may no longer resolve properly at all. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19929/"
]
} |
113,376 | How do you impose a character limit on a text input in HTML? | There are 2 main solutions: The pure HTML one: <input type="text" id="Textbox" name="Textbox" maxlength="10" /> The JavaScript one (attach it to a onKey Event): function limitText(limitField, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } } But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/113376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5509/"
]
} |
113,384 | I have a marker interface defined as public interface IExtender<T>{} I have a class that implements IExtender public class UserExtender : IExtender<User> At runtime I recieve the UserExtender type as a parameter to my evaluating method public Type Evaluate(Type type) // type == typeof(UserExtender) How do I make my Evaluate method return typeof(User) based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it. (I was unsure how to word this question. I hope it is clear enough.) | There are 2 main solutions: The pure HTML one: <input type="text" id="Textbox" name="Textbox" maxlength="10" /> The JavaScript one (attach it to a onKey Event): function limitText(limitField, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } } But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/113384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884/"
]
} |
113,385 | Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class. | You can't do something like this: class A { B b;};class B { A a;}; The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A! You can, however, do this: class B; // this is a "forward declaration"class A { B *b;};class B { A a;}; Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229/"
]
} |
113,395 | Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this: [TestMethod][ExpectedException(typeof(CriticalException))]public void GetOrganisation_MultipleOrganisations_ThrowsException() You can also check for the message contained within the ExpectedException like this: [TestMethod][ExpectedException(typeof(CriticalException), "An error occured")]public void GetOrganisation_MultipleOrganisations_ThrowsException() But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this: [TestMethod][ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)]public void GetOrganisation_MultipleOrganisations_ThrowsException() The compiler will give the following error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute Does anybody know how to test for an exception that has a message from a resource file? One option I have considered is using custom exception classes, but based on often heard advice such as: "Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exception. Otherwise, throw one of the existing exceptions." Source I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions? | I would recommend using a helper method instead of an attribute. Something like this: public static class ExceptionAssert{ public static T Throws<T>(Action action) where T : Exception { try { action(); } catch (T ex) { return ex; } Assert.Fail("Exception of type {0} should be thrown.", typeof(T)); // The compiler doesn't know that Assert.Fail // will always throw an exception return null; }} Then you can write your test something like this: [TestMethod]public void GetOrganisation_MultipleOrganisations_ThrowsException(){ OrganizationList organizations = new Organizations(); organizations.Add(new Organization()); organizations.Add(new Organization()); var ex = ExceptionAssert.Throws<CriticalException>( () => organizations.GetOrganization()); Assert.AreEqual(MyRes.MultipleOrganisationsNotAllowed, ex.Message);} This also has the benefit that it verifies that the exception is thrown on the line you were expecting it to be thrown instead of anywhere in your test method. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5790/"
]
} |
113,423 | What is a good, secure, method to do backups, for programmers who do research & development at home and cannot afford to lose any work? Conditions: The backups must ALWAYS be within reasonably easy reach. Internet connection cannot be guaranteed to be always available. The solution must be either FREE or priced within reason, and subject to 2 above. Status Report This is for now only considering free options. The following open-source projects are suggested in the answers (here & elsewhere): BackupPC is a high-performance,enterprise-grade system for backingup Linux, WinXX and MacOSX PCs andlaptops to a server's disk. Storebackup is a backup utilitythat stores files on other disks. mybackware : These scripts weredeveloped to create SQL dump filesfor basic disaster recovery of smallMySQL installations. Bacula is [...] to managebackup, recovery, and verificationof computer data across a network ofcomputers of different kinds. Intechnical terms, it is a networkbased backup program. AutoDL 2 and Sec-Bk : AutoDL 2is a scalable transport independantautomated file transfer system. Itis suitable for uploading files froma staging server to every server ona production server farm [...] Sec-Bk is a set of simple utilitiesto securely back up files to aremote location, even a publicstorage location. rsnapshot is a filesystemsnapshot utility for making backupsof local and remote systems. rbme : Using rsync for backups[...] you get perpetual incrementalbackups that appear as full backups(for each day) and thus allow easyrestore or further copying to tapeetc. Duplicity backs directories byproducing encrypted tar-formatvolumes and uploading them to aremote or local file server. [...]uses librsync, [for] incrementalarchives simplebup , to do real-time backup of files under active development, as they are modified. This tool can also be used for monitoring of other directories as well. It is intended as on-the-fly automated backup, and not as a version control. It is very easy to use. Other Possibilities: Using a Distributed Version Control System (DVCS) such as Git (/ Easy Git ), Bazaar , Mercurial answers the need to have the backup available locally. Use free online storage space as a remote backup, e.g.: compress your work/backup directory and mail it to your gmail account. Strategies See crazyscot's answer | usb hard disk + rsync works for me (see here for a Win32 build) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
]
} |
113,424 | Is there any way to interpret Reverse Polish Notation into "normal" mathematical notation when using either C++ or C#? I work for an engineering firm, so they use RPN occasionally and we need a way to convert it. Any suggestions? | Yes. Think of how a RPN calculator works. Now, instead of calculating the value, instead you add the operation to the tree. So, for example, 2 3 4 + * , when you get to the +, then rather than putting 7 on the stack, you put (+ 3 4) on the stack. And similarly when you get to the * (your stack will look like 2 (+ 3 4) * at that stage), it becomes (* 2 (+ 3 4)) . This is prefix notation, which you then have to convert to infix. Traverse the tree left-to-right, depth first. For each "inner level", if the precedence of the operator is lower, you will have to place the operation in brackets. Here, then, you will say, 2 * (3 + 4) , because the + has lower precedence than *. Hope this helps! Edit: There's a subtlety (apart from not considering unary operations in the above): I assumed left-associative operators. For right-associative (e.g., ** ), then you get different results for 2 3 4 ** ** ⇒ (** 2 (** 3 4)) versus 2 3 ** 4 ** ⇒ (** (** 2 3) 4) . When reconstructing infix from the tree, both cases show that the precedence doesn't require bracketing, but in reality the latter case needs to be bracketed ( (2 ** 3) ** 4 ). So, for right-associative operators, the left-hand branch needs to be higher-precedence (instead of higher-or-equal) to avoid bracketing. Also, further thoughts are that you need brackets for the right-hand branch of - and / operators too. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5509/"
]
} |
113,427 | I use the screen command for command-line multitasking in Linux and I set my scrollback buffer length to a very large value. Is there a key combination to clear the buffer for a certain tab when I don't want it sitting there anymore? | This thread has the following suggestion: In the window whose scrollback you want to delete, set the scrollback to zero, then return it to its normal value (in your case, 15000). If you want, you can bind this to a key: bind / eval "scrollback 0" "scrollback 15000" You can issue the scrollback 0 command from the session as well, after typing C-a : .HTH. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/113427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
113,479 | I generaly disable viewstate for my ASP.net controls unless I explicitly know I am going to require view state for them. I have found that this can significantly reduce the page size of the HTML generated. Is this good practice? When should be enabled or disabled? | Yes it is a very good idea. One could argue that it should have been disabled by default by Microsoft, just like caching. To see how bad Viewstate is in terms of size increased you can use a tool called Viewstate Analyzer . This is particularly useful when you have an existing application developed with Viewstate enabled. Another good reason to disable Viewstate is that it is really hard to disable at a later stage, when you have loads of components depending on it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4665/"
]
} |
113,511 | How do we decide on the best implementation of hashCode() method for a collection (assuming that equals method has been overridden correctly) ? | The best implementation? That is a hard question because it depends on the usage pattern. A for nearly all cases reasonable good implementation was proposed in Josh Bloch 's Effective Java in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is good. A short version Create a int result and assign a non-zero value. For every field f tested in the equals() method, calculate a hash code c by: If the field f is a boolean : calculate (f ? 0 : 1) ; If the field f is a byte , char , short or int : calculate (int)f ; If the field f is a long : calculate (int)(f ^ (f >>> 32)) ; If the field f is a float : calculate Float.floatToIntBits(f) ; If the field f is a double : calculate Double.doubleToLongBits(f) and handle the return value like every long value; If the field f is an object : Use the result of the hashCode() method or 0 if f == null ; If the field f is an array : see every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next. Combine the hash value c with result : result = 37 * result + c Return result This should result in a proper distribution of hash values for most use situations. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/113511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
]
} |
113,531 | Is it good, bad, or indifferent to run SQL Server on your webserver? I'm using Server 2008 and SQL Server 2005, but I don't think that matters to this question. | For small sites, it doesn't make a bit of a difference.As the load grows, though, this scales really badly, and quicker than you think: Database servers are built on the premise they "own" the server. They trade memory for speed and they easily use all available RAM for internal caching. Once resources start to be scarce, profiling becomes very difficult -- it is clear that IIS and SQL are both suffering, less clear where the bottleneck is. IIS needs CPU, SQL Server needs RAM or CPU etc etc No matter how many layers you put in your code, it all runs on the same CPU, therefore a single layered application will run better in this context -- less overhead -- but it will not scale. Security is really bad, usually you isolate SQL behind a firewall! If you can afford it, it's probably better to shell out a few bucks and get a second server, maybe using PostgreSQL. One IIS server and one PostgreSQL cost about as much as on IIS + SQL Server because of licensing costs... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
]
} |
113,534 | Is there a function in Python to split a string without ignoring the spaces in the resulting list? E.g: s="This is the string I want to split".split() gives me >>> s['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split'] I want something like ['This',' ','is',' ', 'the',' ','string', ' ', .....] | >>> import re>>> re.split(r"(\s+)", "This is the string I want to split")['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split'] Using the capturing parentheses in re.split() causes the function to return the separators as well. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20211/"
]
} |
113,542 | Is there a simple way to hook into the standard ' Add or Remove Programs ' functionality using PowerShell to uninstall an existing application ? Or to check if the application is installed? | $app = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -match "Software Name" }$app.Uninstall() Edit: Rob found another way to do it with the Filter parameter: $app = Get-WmiObject -Class Win32_Product ` -Filter "Name = 'Software Name'" | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/113542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11571/"
]
} |
113,543 | Is there any open-source, PHP based , role-based access control system that can be used for CodeIgniter ? | Brandon Savage gave a presentation on his PHP package " ApplicationACL " that may or may not accomplish role-based access. PHPGACL might work as well, but I can't tell you for sure. What I can tell you, however, is the Zend_ACL component of the Zend Framework will do role-based setups (however you'll have to subclass to check multiple roles at once). Granted the pain of this is you'll have to pull out Zend_ACL, I do not believe it has any external dependencies, from the monolithic download (or SVN checkout). The nice thing about Zend_ACL is though its storage agnostic. You can either rebuild it every time or it's designed to be serialized (I use a combination of both, serialize for the cache and rebuild from the DB). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/950778/"
]
} |
113,565 | I've seen the following code many times: try{ ... // some code}catch (Exception ex){ ... // Do something throw new CustomException(ex); // or // throw; // or // throw ex;} Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?) | Rethrowing the same exception is useful if you want to, say, log the exception, but not handle it. Throwing a new exception that wraps the caught exception is good for abstraction. e.g., your library uses a third-party library that throws an exception that the clients of your library shouldn't know about. In that case, you wrap it into an exception type more native to your library, and throw that instead. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14611/"
]
} |
113,592 | Is there any API to get the currently logged in user's name and password in Windows? Thank you in advance. | Password: No, this is not retained for security reasons - it's used, then discarded. You could retrieve the encrypted password for this user from the registry, given sufficient privileges, then decrypt it using something like rainbow tables , but that's extremely resource intensive and time consuming using current methods. Much better to prompt the user. Alternatively, if you want to implement some sort of 'single signon' system as Novell does, you should do it via either a GINA (pre-Vista) or a Credential Provider (Vista), which will result in your code being given the username and password at login, the only time at which the password is available. For username, getting the current username (the one who is running your code) is easy: the GetUserName function in AdvApi32.dll does exactly this for you. If you're running as a service, you need to remember there is no one "logged in user": there are several at any time, such as LocalSystem, NetworkService, SYSTEM and other accounts, in addition to any actual people. This article provides some sample code and documentation for doing that. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20208/"
]
} |
113,609 | I just ran a "PROCEDURE ANALYSE ( )" on one of my tables. And I have this column that is of type INT and it only ever contains values from 0 to 12 (category IDs).And MySQL said that I would be better of with a ENUM('0','1','2',...,'12'). This category's are basically static and won't change in the future, but if they do I can just alter that column and add it to the ENUM list... So why is ENUM better in this case? edit: I'm mostly interested in the performance aspect of this... | Put simply, it's because it's indexed in a different way. In this case, ENUM says "It's one of these 13 values" whereas INT is saying "It could be any integer." This means that indexing is easier, as it doesn't have to take into account indexing for those integers you don't use "just in case" you ever use them. It's all to do with the algorithms. I'd be interested myself though when it gets to a point where the INT would be quicker than the ENUM . Using numbers in an ENUM might be a little dangerous though... as if you send this number unquoted to SQL - you might end up getting the wrong value back! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/185527/"
]
} |
113,640 | I want to create a box like this with title: Can any one please let me know if there is a default CSS tag to do this? Or do I need to create my custom style? | I believe you are looking for the fieldset HTML tag, which you can then style with CSS. E.g., <fieldset style="border: 1px black solid"> <legend style="border: 1px black solid;margin-left: 1em; padding: 0.2em 0.8em ">title</legend> Text within the box <br /> Etc </fieldset> | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/113640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20165/"
]
} |
113,655 | Is there a function in python to split a word into a list of single letters? e.g: s = "Word to Split" to get wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't'] | >>> list("Word to Split")['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't'] | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/113655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20211/"
]
} |
113,723 | I need to build a simple, single user database application for Windows. Main requirements are independence from windows version and installed software. What technologies (language/framework) would you recommend? My preference for language is the Visual Basic. EDIT: What about VB.Net and SQL Server Compact Edition? | I would recommend Sqlite . It's completely self-contained, and public domain so there are no license issues at all. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692070/"
]
} |
113,755 | I have an application that is installed and updated via ClickOnce. The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall. Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also. What would be the best way to have the changes made to the firewall so that it's invisible to the end user? (The application is written in C#) | I found this article, which has a complete wrapper class included for manipulating the windows firewall. Adding an Application to the Exception list on the Windows Firewall /// /// Allows basic access to the windows firewall API./// This can be used to add an exception to the windows firewall/// exceptions list, so that our programs can continue to run merrily/// even when nasty windows firewall is running.////// Please note: It is not enforced here, but it might be a good idea/// to actually prompt the user before messing with their firewall settings,/// just as a matter of politeness./// /// /// To allow the installers to authorize idiom products to work through/// the Windows Firewall./// public class FirewallHelper{ #region Variables /// /// Hooray! Singleton access. /// private static FirewallHelper instance = null; /// /// Interface to the firewall manager COM object /// private INetFwMgr fwMgr = null; #endregion #region Properties /// /// Singleton access to the firewallhelper object. /// Threadsafe. /// public static FirewallHelper Instance { get { lock (typeof(FirewallHelper)) { if (instance == null) instance = new FirewallHelper(); return instance; } } } #endregion #region Constructivat0r /// /// Private Constructor. If this fails, HasFirewall will return /// false; /// private FirewallHelper() { // Get the type of HNetCfg.FwMgr, or null if an error occurred Type fwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); // Assume failed. fwMgr = null; if (fwMgrType != null) { try { fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType); } // In all other circumnstances, fwMgr is null. catch (ArgumentException) { } catch (NotSupportedException) { } catch (System.Reflection.TargetInvocationException) { } catch (MissingMethodException) { } catch (MethodAccessException) { } catch (MemberAccessException) { } catch (InvalidComObjectException) { } catch (COMException) { } catch (TypeLoadException) { } } } #endregion #region Helper Methods /// /// Gets whether or not the firewall is installed on this computer. /// /// public bool IsFirewallInstalled { get { if (fwMgr != null && fwMgr.LocalPolicy != null && fwMgr.LocalPolicy.CurrentProfile != null) return true; else return false; } } /// /// Returns whether or not the firewall is enabled. /// If the firewall is not installed, this returns false. /// public bool IsFirewallEnabled { get { if (IsFirewallInstalled && fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled) return true; else return false; } } /// /// Returns whether or not the firewall allows Application "Exceptions". /// If the firewall is not installed, this returns false. /// /// /// Added to allow access to this metho /// public bool AppAuthorizationsAllowed { get { if (IsFirewallInstalled && !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed) return true; else return false; } } /// /// Adds an application to the list of authorized applications. /// If the application is already authorized, does nothing. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// This is the name of the application, purely for display /// puposes in the Microsoft Security Center. /// /// /// When applicationFullPath is null OR /// When appName is null. /// /// /// When applicationFullPath is blank OR /// When appName is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed OR /// If the firewall does not allow specific application 'exceptions' OR /// Due to an exception in COM this method could not create the /// necessary COM types /// /// /// If no file exists at the given applicationFullPath /// public void GrantAuthorization(string applicationFullPath, string appName) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (appName == null) throw new ArgumentNullException("appName"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("appName must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot grant authorization: Firewall is not installed."); if (!AppAuthorizationsAllowed) throw new FirewallHelperException("Application exemptions are not allowed."); #endregion if (!HasAuthorization(applicationFullPath)) { // Get the type of HNetCfg.FwMgr, or null if an error occurred Type authAppType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false); // Assume failed. INetFwAuthorizedApplication appInfo = null; if (authAppType != null) { try { appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType); } // In all other circumnstances, appInfo is null. catch (ArgumentException) { } catch (NotSupportedException) { } catch (System.Reflection.TargetInvocationException) { } catch (MissingMethodException) { } catch (MethodAccessException) { } catch (MemberAccessException) { } catch (InvalidComObjectException) { } catch (COMException) { } catch (TypeLoadException) { } } if (appInfo == null) throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance."); appInfo.Name = appName; appInfo.ProcessImageFileName = applicationFullPath; // ... // Use defaults for other properties of the AuthorizedApplication COM object // Authorize this application fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo); } // otherwise it already has authorization so do nothing } /// /// Removes an application to the list of authorized applications. /// Note that the specified application must exist or a FileNotFound /// exception will be thrown. /// If the specified application exists but does not current have /// authorization, this method will do nothing. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// When applicationFullPath is null /// /// /// When applicationFullPath is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed. /// /// /// If the specified application does not exist. /// public void RemoveAuthorization(string applicationFullPath) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); #endregion if (HasAuthorization(applicationFullPath)) { // Remove Authorization for this application fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath); } // otherwise it does not have authorization so do nothing } /// /// Returns whether an application is in the list of authorized applications. /// Note if the file does not exist, this throws a FileNotFound exception. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// When applicationFullPath is null /// /// /// When applicationFullPath is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed. /// /// /// If the specified application does not exist. /// public bool HasAuthorization(string applicationFullPath) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist.", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); #endregion // Locate Authorization for this application foreach (string appName in GetAuthorizedAppPaths()) { // Paths on windows file systems are not case sensitive. if (appName.ToLower() == applicationFullPath.ToLower()) return true; } // Failed to locate the given app. return false; } /// /// Retrieves a collection of paths to applications that are authorized. /// /// /// /// If the Firewall is not installed. /// public ICollection GetAuthorizedAppPaths() { // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); ArrayList list = new ArrayList(); // Collect the paths of all authorized applications foreach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications) list.Add(app.ProcessImageFileName); return list; } #endregion}/// /// Describes a FirewallHelperException./// /// ////// public class FirewallHelperException : System.Exception{ /// /// Construct a new FirewallHelperException /// /// public FirewallHelperException(string message) : base(message) { }} The ClickOnce sandbox did not present any problems. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6389/"
]
} |
113,780 | I don’t think I’ve grokked currying yet. I understand what it does, and how to do it. I just can’t think of a situation I would use it. Where are you using currying in JavaScript (or where are the main libraries using it)? DOM manipulation or general application development examples welcome. One of the answers mentions animation. Functions like slideUp , fadeIn take an element as an arguments and are normally a curried function returning the high order function with the default “animation function” built-in. Why is that better than just applying the higher-up function with some defaults? Are there any drawbacks to using it? As requested here are some good resources on JavaScript currying: http://www.dustindiaz.com/javascript-curry/ Crockford, Douglas (2008) JavaScript: The Good Parts http://www.svendtofte.com/code/curried_javascript/ (Takes a detour into ML so skip the whole section from “A crash course in ML” and start again at “How to write curried JavaScript”) http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies How do JavaScript closures work? http://ejohn.org/blog/partial-functions-in-javascript (Mr. Resig on the money as per usual) http://benalman.com/news/2010/09/partial-application-in-javascript/ I’ll add more as they crop up in the comments. So, according to the answers, currying and partial application in general are convenience techniques. If you are frequently “refining” a high-level function by calling it with same configuration, you can curry (or use Resig’s partial) the higher-level function to create simple, concise helper methods. | Here's an interesting AND practical use of currying in JavaScript that uses closures : function converter(toUnit, factor, offset, input) { offset = offset || 0; return [((offset + input) * factor).toFixed(2), toUnit].join(" ");}var milesToKm = converter.curry('km', 1.60936, undefined);var poundsToKg = converter.curry('kg', 0.45460, undefined);var farenheitToCelsius = converter.curry('degrees C', 0.5556, -32);milesToKm(10); // returns "16.09 km"poundsToKg(2.5); // returns "1.14 kg"farenheitToCelsius(98); // returns "36.67 degrees C" This relies on a curry extension of Function , although as you can see it only uses apply (nothing too fancy): Function.prototype.curry = function() { if (arguments.length < 1) { return this; //nothing to curry with - return function } var __method = this; var args = toArray(arguments); return function() { return __method.apply(this, args.concat([].slice.apply(null, arguments))); }} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/113780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9474/"
]
} |
113,829 | How do I get timestamp from e.g. 22-09-2008 ? | This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates . If you don't care about timezone, or want to use the time zone your server uses: $d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');if ($d === false) { die("Incorrect date string");} else { echo $d->getTimestamp();} 1222093324 (This will differ depending on your server time zone...) If you want to specify in which time zone, here EST. (Same as New York.) $d = DateTime::createFromFormat( 'd-m-Y H:i:s', '22-09-2008 00:00:00', new DateTimeZone('EST'));if ($d === false) { die("Incorrect date string");} else { echo $d->getTimestamp();} 1222093305 Or if you want to use UTC . (Same as " GMT ".) $d = DateTime::createFromFormat( 'd-m-Y H:i:s', '22-09-2008 00:00:00', new DateTimeZone('UTC'));if ($d === false) { die("Incorrect date string");} else { echo $d->getTimestamp();} 1222093289 Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/113829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205368/"
]
} |
113,830 | Is there a runtime performance penalty when using interfaces (abstract base classes) in C++? | Short Answer: No. Long Answer:It is not the base class or the number of ancestors a class has in its hierarchy that affects it speed. The only thing is the cost of a method call. A non virtual method call has a cost (but can be inlined) A virtual method call has a slightly higher cost as you need to look up the method to call before you call it (but this is a simple table look up not a search). Since all methods on an interface are virtual by definition there is this cost. Unless you are writing some hyper speed sensitive application this should not be a problem. The extra clarity that you will recieve from using an interface usually makes up for any perceived speed decrease. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/113830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
]
} |
113,866 | Name of the option tells something but what Visual Studio/compiler really do and what are the real consequences? Edit: If you search google you can find this address , but that is not really I am looking for. I wonder the real things happening. For example why do the loops get less time, etc. | Without optimizations the compiler produces very dumb code - each command is compiled in a very straightforward manner, so that it does the intended thing. The Debug builds have optimizations disabled by default, because without the optimizations the produced executable matches the source code in a straightforward manner. Variables kept in registers Once you turn on the optimizations, the compiler applies many different techniques to make the code run faster while still doing the same thing. The most obvious difference between optimized and unoptimized builds in Visual C++ is the fact the variable values are kept in registers as long as possible in optimized builds, while without optimizations they are always stored into the memory. This affects not only the code speed, but it also affects debugging. As a result of this optimization the debugger cannot reliably obtain a variable value as you are stepping through the code. Other optimizations There are multiple other optimizations applied by the compiler, as described in /O Options (Optimize Code) MSDN docs . For a general description of various optimizations techniques see Wikipedia Compiler Optimization article . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/113866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11374/"
]
} |
113,886 | I'm trying to ftp a folder using the command line ftp client, but so far I've only been able to use 'get' to get individual files. | You could rely on wget which usually handles ftp get properly (at least in my own experience). For example: wget -r ftp://user:[email protected]/ You can also use -m which is suitable for mirroring. It is currently equivalent to -r -N -l inf . If you've some special characters in the credential details, you can specify the --user and --password arguments to get it to work. Example with custom login with specific characters: wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/ As pointed out by @asmaier, watch out that even if -r is for recursion, it has a default max level of 5: -r--recursive Turn on recursive retrieving.-l depth--level=depth Specify recursion maximum depth level depth. The default maximum depth is 5. If you don't want to miss out subdirs, better use the mirroring option, -m : -m--mirror Turn on options suitable for mirroring. This option turns on recursion and time-stamping, sets infinite recursion depth and keeps FTP directory listings. It is currently equivalent to -r -N -l inf --no-remove-listing. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/113886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11708/"
]
} |
113,901 | In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation. How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace? | SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'example' SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE' SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe' Don't assume the default collation will be case sensitive, just specify a case sensitive one every time (using the correct one for your language of course) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152/"
]
} |
113,923 | We help our clients to manage and publish their media online - images, video, audio, whatever. They always ask my boss whether they can stop users from copying their media, and he asks me, and I always tell him the same thing: no. If the users can view the media, then a sufficiently determined user will always be able to make a copy. But am I right? I've been asked again today, and I promised my boss I'd ask about it online. So - is there a DRM scheme that will work? One that will stop users making copies without stopping legitimate viewing of the media? And if there isn't, how do I convince my boss? | No. If you let them view it, they can always make a copy of what they saw. You can make it harder for this to happen, but in the end, you can't stop a suitably determined attacker. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
]
} |
113,928 | When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how. | After you commit your object into the db the object receives a value in its ID field. So: myObject.Field1 = "value";// Db is the datacontextdb.MyObjects.InsertOnSubmit(myObject);db.SubmitChanges();// You can retrieve the id from the objectint id = myObject.ID; | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/113928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14777/"
]
} |
113,930 | I would like to display some memory statistics (working set, GCs etc.) on a web page using the .NET/Process performance counters. Unfortunately, if there are multiple application pools on that server, they are differentiated using an index (#1, #2 etc.) but I don't know how to match a process ID (which I have) to that #xx index. Is there a programmatic way (from an ASP.NET web page)? | The first hit on Google: Multiple CLR performance counters appear that have names that resemble "W3wp#1" When multiple ASP.NET worker processes are running, Common Language Runtime (CLR) performance counters will have names that resemble "W3wp#1" or "W3sp#2"and so on. This was remedied in .NET Framework 2.0 to include a counter named Process ID in the .NET CLR Memory performance object. This counter displays the process ID for an instance. You can use this counter to determine the CLR performance counter that is associated with a process. Also KB 281884 : By default, Performance Monitor (Perfmon.msc) displays multiple processes that have the same name by enumerating the processes in the following way: Process#1 Process#2 Process#3 Performance Monitor can also display these processes by appending the process ID (PID) to the name in the following way: Process_PID | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/113930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
113,989 | Is there an easy way (in .Net) to test if a Font is installed on the current machine? | string fontName = "Consolas";float fontSize = 12;using (Font fontTester = new Font( fontName, fontSize, FontStyle.Regular, GraphicsUnit.Pixel)) { if (fontTester.Name == fontName) { // Font exists } else { // Font doesn't exist }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/113989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11492/"
]
} |
114,029 | What is the best way of dynamically writing LINQ queries and Lambda expressions? I am thinking of applications where the end user can design business logic rules, which then must be executed. I am sorry if this is a newbie question, but it would be great to get best practices out of experience. | I cannot recommend higher than you reading through the postings of Bart De Smet ( http://community.bartdesmet.net/blogs/bart/ ), he is really brilliant when it comes to Lambda. His recent series covered dynamic Lambda, starting with http://community.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-0.aspx Absolutely beautiful code. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
]
} |
114,085 | I have lots of unrelated named things that I'd like to do quick searches against. An "aardvark" is always an "aardvark" everywhere, so hashing the string and reusing the integer would work well to speed up comparisons. The entire set of names is unknown (and changes over time). What is a fast string hashing algorithm that will generate small (32 or 16) bit values and have a low collision rate? I'd like to see an optimized implementation specific to C/C++. | One of the FNV variants should meet your requirements. They're fast, and produce fairly evenly distributed outputs. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10945/"
]
} |
114,149 | The point of const-correctness is to be able to provide a view of an instance that can't be altered or deleted by the user. The compiler supports this by pointing out when you break constness from within a const function, or try to use a non-const function of a const object. So without copying the const approach, is there a methodology I can use in C# that has the same ends? I'm aware of immutability, but that doesn't really carry over to container objects to name but one example. | I've come across this issue a lot of times too and ended up using interfaces. I think it's important to drop the idea that C# is any form, or even an evolution of C++. They're two different languages that share almost the same syntax. I usually express 'const correctness' in C# by defining a read-only view of a class: public interface IReadOnlyCustomer{ String Name { get; } int Age { get; }}public class Customer : IReadOnlyCustomer{ private string m_name; private int m_age; public string Name { get { return m_name; } set { m_name = value; } } public int Age { get { return m_age; } set { m_age = value; } }} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/114149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11801/"
]
} |
114,163 | I want to perform cascade delete for some tables in my database, but I'm interested in what happens in case there's a failure when deleting something. Will everything rollback? | In general¹, yes, cascade deletes are done in the same transaction (or subtransaction) as your original delete. You should read the documentation of your SQL server, though. ¹ The exception is if you're using a database that doesn't support transactions, like MySQL with MyISAM tables. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
]
} |
114,165 | At work we use WiX for building installation packages. We want that installation of product X would result in uninstall of the previous version of that product on that machine. I've read on several places on the Internet about a major upgrade but couldn't get it to work.Can anyone please specify the exact steps that I need to take to add uninstall previous version feature to WiX? | In the newest versions (from the 3.5.1315.0 beta), you can use the MajorUpgrade element instead of using your own. For example, we use this code to do automatic upgrades. It prevents downgrades, giving a localised error message, and also prevents upgrading an already existing identical version (i.e. only lower versions are upgraded): <MajorUpgrade AllowDowngrades="no" DowngradeErrorMessage="!(loc.NewerVersionInstalled)" AllowSameVersionUpgrades="no" /> | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/114165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11361/"
]
} |
114,180 | What would be better practice when giving a function the original variable to work with: unsigned long x = 4;void func1(unsigned long& val) { val = 5; }func1(x); or: void func2(unsigned long* val) { *val = 5;}func2(&x); IOW: Is there any reason to pick one over another? | My rule of thumb is: Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer. Use references otherwise. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/114180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20349/"
]
} |
114,196 | I'm using httpc:request to post some data to a remote service. I have the post working but the data in the body() of the post comes through as is, without any URL-encoding which causes the post to fail when parsed by the remote service. Is there a function in Erlang that is similar to CGI.escape in Ruby for this purpose? | I encountered the lack of this feature in the HTTP modules as well. It turns out that this functionality is actually available in the erlang distribution, you just gotta look hard enough. > edoc_lib:escape_uri("[email protected]")."luca%2bmore%40here.com" This behaves like CGI.escape in Ruby, there is also URI.escape which behaves slightly differently: > CGI.escape("[email protected]") => "luca%2Bmore%40here.com" > URI.escape("[email protected]") => "[email protected]" edoc_lib | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20345/"
]
} |
114,214 | What is the difference between the following class methods? Is it that one is static and the other is not? class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two"a_test = Test()a_test.method_one()a_test.method_two() | In Python, there is a distinction between bound and unbound methods. Basically, a call to a member function (like method_one ), a bound function a_test.method_one() is translated to Test.method_one(a_test) i.e. a call to an unbound method. Because of that, a call to your version of method_two will fail with a TypeError >>> a_test = Test() >>> a_test.method_two()Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: method_two() takes no arguments (1 given) You can change the behavior of a method using a decorator class Test(object): def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method two" The decorator tells the built-in default metaclass type (the class of a class, cf. this question ) to not create bound methods for method_two . Now, you can invoke static method both on an instance or on the class directly: >>> a_test = Test()>>> a_test.method_one()Called method_one>>> a_test.method_two()Called method_two>>> Test.method_two()Called method_two | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/114214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16070/"
]
} |
114,229 | I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes. How can I achieve something similar to array_map or array_walk with objects? | use get_object_vars() to get an associative array of the members, and use the functions you mentioned. btw, you can also do a foreach on an object like you would on an array, which is sometimes useful as well. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12534/"
]
} |
114,236 | I use pstack to analyze core dump files in Solaris How else can I analyze the core dump from solaris? What commands can be used to do this? What other information will be available from the dump? | You can use Solaris modular debugger,mdb, or dbx. mdb comes with SUNWmdb (or SUNWmdb x for the 64 bits version) package. A core file is the image of your running process at the time it crashed. Depending on whether your application was compiled with debug flags or not,you will be able to view an image of the stack, hence to know which function caused the core, to get the value of the parameters that were passed to that function, the value of the variables, the allocated memory zones ... On recent solaris versions, you can configure what the core file will contain with the coreadm command ; for instance, you can have the mapped memory segments the process were attached to. Refer to MDB documentation and dbx documentation . The GDB quick reference card is also helpful once you know the basics of GDB. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357/"
]
} |
114,238 | The second question is: When do I use what of these two? | When not specified, C++ is unmanaged C++, compiled to machine code. In unmanaged C++ you must manage memory allocation manually. Managed C++ is a language invented by Microsoft, that compiles to bytecode run by the .NET Framework. It uses mostly the same syntax as C++ (hence the name) but is compiled in the same way as C# or VB.NET; basically only the syntax changes, e.g. using '->' to point to a member of an object (instead of '.' in C#), using '::' for namespaces, etc. Managed C++ was made to ease transition from classic C++ to the .NET Framework. It is not intended to be used to start new projects (C# is preferred). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/114238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5334/"
]
} |
114,272 | I am working with some CSS that is poorly written to say the least. I am not a design/CSS expert, but I at least understand the C in CSS. While the builtin CSS support inside of VS-2008 is far improved over previous versions, it still doesn't quite do what I am looking for. I was wondering if anyone know of a good program or utility that will help me to refactor and clean up my CSS like what ReSharper allows to do with C#. Some features that would be nice to have: Examine CSS files and determine ways to extract common styles like font-style, color, etc... Plugin to VS-2008 would be awesome! Examine markup files and make some suggestions on improving the current use of classes and styles. | The Dust-Me Selectors Firefox extension can scan a website and tell you what CSS is used and what is not. Removing unused CSS is one good first step in refactoring. I have often found that when some section is removed from a website, the HTML is removed but the CSS is not. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11702/"
]
} |
114,332 | I've had a serious issue with my Visual Studio 2008 setup. I receive the ever-so-useful error 'A problem has been encountered while loading the setup components. Canceling setup.' whenever I try to uninstall, reinstall or repair Visual Studio 2008 (team system version). If I can't resolve this issue I have no choice but to completely wipe my computer and start again which will take all day long! I've recently received very strange errors when trying to build projects regarding components running out of memory (despite having ~2gb physical memory free at the time) which has rendered my current VS install useless. Note I installed VS2005 shell version using the vs_setup.msi file in the SQL Server folder after I had installed VS2008, in order to gain access to the SQL Server 2005 Reporting Services designer in Business Intelligence Development Studio (this is inexplicably unavailable in VS2008). Does anyone have any solutions to this problem? P.S. : I know this isn't directly related to programming, however I feel this is appropriate to SO as it is directly related to my ability to program at all! Note : A colleague found a solution to this problem, hopefully this should help others with this problem. | A colleague found this MS auto-uninstall tool which has successfully uninstalled VS2008 for me and saved me hours of work!! Hopefully this might be useful to others. Doesn't speak highly of MS's faith in their usual VS maintenance tools that they have to provide this as well! | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/114332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
]
} |
114,419 | The following two C# code snippets produce different results (assuming the variable level is used both before and after the recursive call). Why? public DoStuff(int level){ // ... DoStuff(level++); // ...} , public DoStuff(int level){ // ... DoStuff(level+1); // ...} After reading some of the responses below I thought it would be worthwhile posting the stack traces for level++, ++level and level+1 to highlight how deceiving this problem is. I've simplified them for this post. The recursive call sequence starts with DoStuff(1). // level++ DoStuff(int level = 1)DoStuff(int level = 2)DoStuff(int level = 2)DoStuff(int level = 2) // ++level DoStuff(int level = 4)DoStuff(int level = 4)DoStuff(int level = 3)DoStuff(int level = 2) // level+1 DoStuff(int level = 4)DoStuff(int level = 3)DoStuff(int level = 2)DoStuff(int level = 1) | level++ will pass level into DoStuff and then increment level for use in the rest of the function. This could be a fairly nasty bug as the recursion will never end (from what is shown DoStuff is always being passed the same value). Perhaps ++level is meant instead, as this is the opposite of level++ (increments level and passes the incremented value into DoStuff )? level+1 will pass level+1 into DoStuff and leave level unchanged for the rest of the function. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199234/"
]
} |
114,431 | I am trying to display a live word count in the vim statusline. I do this by setting my status line in my .vimrc and inserting a function into it. The idea of this function is to return the number of words in the current buffer. This number is then displayed on the status line. This should work nicely as the statusline is updated at just about every possible opportunity so the count will always remain 'live'. The problem is that the function I have currently defined is slow and so vim is obviously sluggish when it is used for all but the smallest files; due to this function being executed so frequently. In summary, does anyone have a clever trick for producing a function that is blazingly fast at calculating the number of words in the current buffer and returning the result? | Here's a usable version of Rodrigo Queiro's idea. It doesn't change the status bar, and it restores the statusmsg variable. function WordCount() let s:old_status = v:statusmsg exe "silent normal g\<c-g>" let s:word_count = str2nr(split(v:statusmsg)[11]) let v:statusmsg = s:old_status return s:word_countendfunction This seems to be fast enough to include directly in the status line, e.g.: :set statusline=wc:%{WordCount()} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20388/"
]
} |
114,493 | I know the range name of the start of a list - 1 column wide and x rows deep. How do I calculate x ? There is more data in the column than just this list. However, this list is contiguous - there is nothing in any of the cells above or below or either side beside it. | Sheet1.Range("myrange").Rows.Count | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10326/"
]
} |
114,501 | I want to set a background image for a div, in a way that it is in the upper RIGHT of the div, but with a fixed 10px distance from top and right. Here is how I would do that if wanted it in the upper LEFT of the div: background: url(images/img06.gif) no-repeat 10px 10px; Is there anyway to achieve the same result, but showing the background on the upper RIGHT ? | Use the previously mentioned rule along with a top and right margin: background: url(images/img06.gif) no-repeat top right;margin-top: 10px;margin-right: 10px; Background images only appear within padding, not margins. If adding the margin isn't an option you may have to resort to another div, although I'd recommend you only use that as a last resort to try and keep your markup as lean and sementic as possible. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6476/"
]
} |
114,504 | Eg. can I write something like this code: public void InactiveCustomers(IEnumerable<Guid> customerIDs){ //... myAdoCommand.CommandText = "UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)"; myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs; //...} The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string. | Generally the way that you do this is to pass in a comma-separated list of values, and within your stored procedure, parse the list out and insert it into a temp table, which you can then use for joins. As of Sql Server 2005 , this is standard practice for dealing with parameters that need to hold arrays. Here's a good article on various ways to deal with this problem: Passing a list/array to an SQL Server stored procedure But for Sql Server 2008 , we finally get to pass table variables into procedures, by first defining the table as a custom type. There is a good description of this (and more 2008 features) in this article: Introduction to New T-SQL Programmability Features in SQL Server 2008 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547/"
]
} |
114,525 | Possible Duplicate: JavaScript: var functionName = function() {} vs function functionName() {} What's the difference between: function sum(x, y) { return x+y;}// and var sum = function (x, y) { return x+y;} Why is one used over the other? | The first is known as a named function where the second is known as an anonymous function. The key practical difference is in when you can use the sum function. For example:- var z = sum(2, 3);function sum(x, y) { return x+y;} z is assigned 5 whereas this:- var z = sum(2, 3);var sum = function(x, y) { return x+y;} Will fail since at the time the first line has executed the variable sum has not yet been assigned the function. Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition. Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/114525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3983/"
]
} |
114,527 | I'm really new to .NET, and I still didn't get the hang about how configuration files work. Every time I search on Google about it I get results about web.config, but I'm writing a Windows Forms application. I figured out that I need to use the System.Configuration namespace, but the documentation isn't helping. How do I define that my configuration file is XYZ.xml? Or does it have a "default" name for the configuration file? I still didn't get that. Also, how do I define a new section? Do I really need to create a class which inherits from ConfigurationSection? I would like to just have a configuration file with some values like this: <MyCustomValue>1</MyCustomValue><MyCustomPath>C:\Some\Path\Here</MyCustomPath> Is there a simple way to do it? Can you explain in a simple way how to read and write from/to a simple configuration file? | You want to use an App.Config. When you add a new item to a project there is something called Applications Configuration file. Add that. Then you add keys in the configuration/appsettings section Like: <configuration> <appSettings> <add key="MyKey" value="false"/> Access the members by doing System.Configuration.ConfigurationSettings.AppSettings["MyKey"]; This works in .NET 2 and above. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/114527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
]
} |
114,543 | How can I horizontally center a <div> within another <div> using CSS? <div id="outer"> <div id="inner">Foo foo</div></div> | You can apply this CSS to the inner <div> : #inner { width: 50%; margin: 0 auto;} Of course, you don't have to set the width to 50% . Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering. If you are targeting Internet Explorer 8 (and later), it might be better to have this instead: #inner { display: table; margin: 0 auto;} It will make the inner element center horizontally and it works without setting a specific width . Working example here: #inner { display: table; margin: 0 auto; border: 1px solid black;}#outer { border: 1px solid red; width:100%} <div id="outer"> <div id="inner">Foo foo</div></div> EDIT With flexbox it is very easy to style the div horizontally and vertically centered. #inner { border: 0.05em solid black;}#outer { border: 0.05em solid red; width:100%; display: flex; justify-content: center;} <div id="outer"> <div id="inner">Foo foo</div></div> To align the div vertically centered, use the property align-items: center . | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/114543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20403/"
]
} |
114,581 | To all the people who know lambda calculus : What benefit has it bought you, regarding programming? Would you recommend that people learn it? | If you want to program in any functional programming language , it's essential. I mean, how useful is it to know about Turing machines? Well, if you write C, the language paradigm is quite close to Turing machines -- you have an instruction pointer and a current instruction, and the machine takes some action in the current state, and then ambles along to the next instruction. In a functional language, you simply can't think like that -- that's not the language paradigm. You have to think back to lambda calculus, and how terms are evaluated there. It will be much harder for you to be effective in a functional language if you don't know lambda calculus. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18658/"
]
} |
114,586 | What is the smartest way to design a math parser? What I mean is a function that takes a math string (like: "2 + 3 / 2 + (2 * 5)") and returns the calculated value? I did write one in VB6 ages ago but it ended up being way to bloated and not very portable (or smart for that matter...). General ideas, psuedo code or real code is appreciated. | A pretty good approach would involve two steps. The first step involves converting the expression from infix to postfix (e.g. via Dijkstra's shunting yard ) notation. Once that's done, it's pretty trivial to write a postfix evaluator . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/114586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
114,658 | I keep hearing that catch (Exception ex) Is bad practise, however, I often use it in event handlers where an operation may for example go to network, allowing the possibility of many different types of failure. In this case, I catch all exceptions and display the error message to the user in a message box. Is this considered bad practise? There's nothing more I can do with the exception: I don't want it to halt the application, the user needs to know what happened, and I'm at the top level of my code. What else should I be doing? EDIT: People are saying that I should look through the stack of calls and handle errors specifically, because for example a StackOverflow exception cannot be handled meaningfully. However, halting the process is the worst outcome, I want to prevent that at all costs. If I can't handle a StackOverflow, so be it - the outcome will be no worse than not catching exceptions at all, and in 99% of cases, informing the user is the least bad option as far as I'm concerned. Also, despite my best efforts to work out all of the possible exceptions that can be thrown, in a large code-base it's likely that I would miss some. And for most of them the best defense is still to inform the user. | The bad practice is catch (Exception ex){} and variants: catch (Exception ex){ return false; } etc. Catching all exceptions on the top-level and passing them on to the user (by either logging them or displaying them in a message-box, depending on whether you are writing a server- or a client-application), is exactly the right thing to do. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448/"
]
} |
114,698 | We have a lot of spreadsheets (xls) in our source code repository. These are usually edited with gnumeric or openoffice.org, and are mostly used to populate databases for unit testing with dbUnit . There are no easy ways of doing diffs on xls files that I know of, and this makes merging extremely tedious and error prone. I've tried to converting the spreadsheets to xml and doing a regular diff, but it really feels like it should be a last resort. I'd like to perform the diffing (and merging) with git as I do with text files. How would I do this, e.g. when issuing git diff ? | We faced the exact same issue in our co. Our tests output excel workbooks. Binary diff was not an option. So we rolled out our own simple command line tool. Check out the ExcelCompare project . Infact this allows us to automate our tests quite nicely. Patches / Feature requests quite welcome! | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/114698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13365/"
]
} |
114,707 | I need to present the user with a matrix of which one column is editable. What is the most appropriate control to use? I can't use a ListView because you can only edit the first column (the label) and that's no good to me. Is the DataGridView the way to go, or are there third party alternative components that do a better job? | DataGridView is the best choice as it is free and comes with .NET WinForms 2.0. You can define editable columns or read-only. Plus you can customize the appearance if required. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/826/"
]
} |
114,804 | I want to write a real-time analysis tool for wireless traffic. Does anyone know how to read from a promiscuous (or sniffing) device in C? I know that you need to have root access to do it. I was wondering if anyone knows what functions are necessary to do this. Normal sockets don't seem to make sense here. | On Linux you use a PF_PACKET socket to read data from a raw device, such as an ethernet interface running in promiscuous mode: s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)) This will send copies of every packet received up to your socket. It is quite likely that you don't really want every packet, though. The kernel can perform a first level of filtering using BPF, the Berkeley Packet Filter . BPF is essentially a stack-based virtual machine: it handles a small set of instructions such as: ldh = load halfword (from packet) jeq = jump if equal ret = return with exit code BPF's exit code tells the kernel whether to copy the packet to the socket or not. It is possible to write relatively small BPF programs directly, using setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER, ). (WARNING: The kernel takes a struct sock_fprog, not a struct bpf_program, do not mix those up or your program will not work on some platforms). For anything reasonably complex, you really want to use libpcap. BPF is limited in what it can do, in particular in the number of instructions it can execute per packet. libpcap will take care of splitting a complex filter up into two pieces, with the kernel performing a first level of filtering and the more-capable user-space code dropping the packets it didn't actually want to see. libpcap also abstracts the kernel interface out of your application code. Linux and BSD use similar APIs, but Solaris requires DLPI and Windows uses something else. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/542226/"
]
} |
114,807 | I am a .NET webdev using ASP.NET, C# etc... I "learned" javascript in college 5+ years ago and can do basic jobs with it. But I wonder if it is useful to become proficient in it. Why should I learn Javascript?Is it more advantageous then learning JQuery or a different library ? | Yes, definitely learn Javascript before you learn one of the libraries about. It's the whole walk-before-you-can-run thing. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18821/"
]
} |
114,814 | In Bash, how do I count the number of non-blank lines of code in a project? | cat foo.c | sed '/^\s*$/d' | wc -l And if you consider comments blank lines: cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l Although, that's language dependent. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/114814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10176/"
]
} |
114,819 | Consider these classes. class Base{ ...};class Derived : public Base{ ...}; this function void BaseFoo( std::vector<Base*>vec ){ ...} And finally my vector std::vector<Derived*>derived; I want to pass derived to function BaseFoo , but the compiler doesn't let me. How do I solve this, without copying the whole vector to a std::vector<Base*> ? | vector<Base*> and vector<Derived*> are unrelated types, so you can't do this. This is explained in the C++ FAQ here . You need to change your variable from a vector<Derived*> to a vector<Base*> and insert Derived objects into it. Also, to avoid copying the vector unnecessarily, you should pass it by const-reference, not by value: void BaseFoo( const std::vector<Base*>& vec ){ ...} Finally, to avoid memory leaks, and make your code exception-safe, consider using a container designed to handle heap-allocated objects, e.g: #include <boost/ptr_container/ptr_vector.hpp>boost::ptr_vector<Base> vec; Alternatively, change the vector to hold a smart pointer instead of using raw pointers: #include <memory>std::vector< std::shared_ptr<Base*> > vec; or #include <boost/shared_ptr.hpp>std::vector< boost::shared_ptr<Base*> > vec; In each case, you would need to modify your BaseFoo function accordingly. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
]
} |
114,830 | One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it? | Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here . That's why you can't use something 'not hashable' as a dict key, like a list: >>> a = {}>>> b = ['some', 'list']>>> hash(b)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: list objects are unhashable>>> a[b] = 'some'Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: list objects are unhashable You can read more about hash tables or check how it has been implemented in python and why it is implemented that way . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/114830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11575/"
]
} |
114,851 | I have the following code: ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match")ListBox.DisplayMember = "name" The DataTable.Select() method returns an array of System.Data.DataRow objects. No matter what I specify in the ListBox.DisplayMember property, all I see is the ListBox with the correct number of items all showing as System.Data.DataRow instead of the value I want which is in the "name" column! Is it possible to bind to the resulting array from DataTable.Select() , instead of looping through it and adding each one to the ListBox ? (I've no problem with looping, but doesn't seem an elegant ending!) | Use a DataView instead. ListBox.DataSource = new DataView(DataSet.Tables("table_name"), "some_criteria = match", "name", DataViewRowState.CurrentRows);ListBox.DisplayMember = "name" | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
]
} |
114,872 | Given some JS code like that one here: for (var i = 0; i < document.getElementsByName('scale_select').length; i++) { document.getElementsByName('scale_select')[i].onclick = vSetScale; } Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that? I am not sure how large the effect is in real life, with the result from getElementsByName typically having < 10 items. I'd like to understand the underlying mechanics anyway. Also, if there's anything else noteworthy about the two options, please tell me. | Definitely. The memory required to store that would only be a pointer to a DOM object and that's significantly less painful than doing a DOM search each time you need to use something! Idealish code: var scale_select = document.getElementsByName('scale_select');for (var i = 0; i < scale_select.length; i++) scale_select[i].onclick = vSetScale; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
} |
114,874 | How should I determine what to use for a listening socket's backlog parameter? Is it a problem to simply specify a very large number? | There's a very long answer to this in the Winsock Programmer's FAQ . It details the standard setting, and the dynamic backlog feature added in a hotfix to NT 4.0. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/114874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
114,884 | I've googled the hell out of it, and it seems like there is no way to install gcc on OS X without installing Xcode (which takes at leats 1.5GB of space). All I need is gcc and none of the other junk that comes with Xcode. And at this point, I'll take any other kind of C compiler. I know I could simply install Xcode, but that is beside the point since I neither have my original installation disc nor a quick internet connection. So... does anyone have any suggestions? EDIT: Sorry if I was unclear, but I need the headers as well. I'm currently installing gcc4 via fink and it's downloading the shared libraries as well. I'll update on the progress. EDIT 2: Ok, so I successfully installed gcc using fink. BUT, it's pretty much useless: "error: C compiler cannot create executables". After googling around, I found that not having Apple's Developer Tools installed is the cause of the error. Probably because I need all the libraries, headers, etc that are only available through Xcode. | Try the osx-gcc-installer on github. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/114884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17998/"
]
} |
114,928 | I'm firing off a Java application from inside of a C# .NET console application. It works fine for the case where the Java application doesn't care what the "default" directory is, but fails for a Java application that only searches the current directory for support files. Is there a process parameter that can be set to specify the default directory that a process is started in? | Yes!ProcessStartInfo Has a property called WorkingDirectory , just use: ...using System.Diagnostics;...var startInfo = new ProcessStartInfo(); startInfo.WorkingDirectory = // working directory // set additional properties Process proc = Process.Start(startInfo); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/114928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15689/"
]
} |
114,983 | Given: DateTime.UtcNow How do I get a string which represents the same value in an ISO 8601 -compliant format? Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is: yyyy-MM-ddTHH:mm:ssZ | Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information. DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz", CultureInfo.InvariantCulture); Using custom date-time formatting , this gives you a date similar to 2008-09-22T13:57:31.2311892-04:00 . Another way is: DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); which uses the standard "round-trip" style (ISO 8601) to give you 2008-09-22T14:01:54.9571247Z . To get the specified format, you can use: DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/114983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20457/"
]
} |
115,008 | How to print line numbers to the log. Say when outputting some information to the log, I also want to print the line number where that output is in the source code. As we can see in the stack trace, it displays the line number where the exception has occurred. Stack trace is available on the exception object. Other alternative could be like manually including the line number when printing to the log. Is there any other way? | From Angsuman Chakraborty (archived) : /** Get the current line number. * @return int - Current line number. */public static int getLineNumber() { return Thread.currentThread().getStackTrace()[2].getLineNumber();} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/115008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15177/"
]
} |
115,115 | Has anyone had success automating testing directly on embedded hardware? Specifically, I am thinking of automating a battery of unit tests for hardware layer modules. We need to have greater confidence in our hardware layer code. A lot of our projects use interrupt driven timers, ADCs, serial io, serial SPI devices (flash memory) etc.. Is this even worth the effort? We typically target: Processor: 8 or 16 bit microcontrollers (some DSP stuff) Language: C (sometimes c++). | Sure. In the automotive industry we use $100,000 custom built testers for each new product to verify the hardware and software are operating correctly. The developers, however, also build a cheaper (sub $1,000) tester that includes a bunch of USB I/O, A/D, PWM in/out, etc and either use scripting on the workstation, or purpose built HIL/SIL test software such as MxVDev. Hardware in the Loop (HIL) testing is probably what you mean, and it simply involves some USB hardware I/O connected to the I/O of your device, with software on the computer running tests against it. Whether it's worth it depends. In the high reliability industry (airplane, automotive, etc) the customer specifies very extensive hardware testing, so you have to have it just to get the bid. In the consumer industry, with non complex projects it's usually not worth it. With any project where there's more than a few programmers involved, though, it's really nice to have a nightly regression test run on the hardware - it's hard to correctly simulate the hardware to the degree needed to satisfy yourself that the software testing is enough. The testing then shows immediately when a problem has entered the build. Generally you perform both black box and white box testing - you have diagnostic code running on the device that allows you to spy on signals and memory in the hardware (which might just be a debugger, or might be code you wrote that reacts to messages on a bus, for instance). This would be white box testing where you can see what's happening internally (and even cause some things to happen, such as critical memory errors which can't be tested without introducing the error yourself). We also run a bunch of 'black box' tests where the diagnostic path is ignored and only the I/O is stimulated/read. For a much cheaper setup, you can get $100 microcontroller boards with USB and/or ethernet (such as the Atmel UC3 family) which you can connect to your device and run basic testing. It's especially useful for product maintenance - when the project is done, store a few working boards, the tester, and a complete set of software on CD. When you need to make a modification or debug a problem, it's easy to set it all back up and work on it with some knowledge (after testing) that the major functionality was not affected by your changes. -Adam | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
]
} |
115,116 | If I create a test suite for a development project, should those classes be kept under version control with the rest of the project code? | Yes, there is no reason not to put them in source control. What if the tests change? What if the interfaces change, necessitating that the tests change? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20473/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.