source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
144,783 | Should each class in my C# project get its own file (in your opinion)? | While the one class per file policy is strictly enforced in Java, it's not required by C#. However, it's generally a good idea. I typically break this rule if I have a very small helper class that is only used by the main class, but I prefer to do that as a nested inner class for clarity's sake. You can however, split a single class into multiple files using the partial keyword . This is useful for separating your code from wizard-generated code. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/144783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7529/"
]
} |
144,807 | Unfortunately, sometimes the only way to debug a program is by going through its long log files. I searched for a decent log viewer for a while now, and haven't found a real solution. The only program that seemed to be most appropriate was Chainsaw with its Socket connector but after a few short uses the program proved to be buggy and unresponsive at best. For my purposes, a log viewer should at least be able to mark log levels (for example with different colors) and perform easy filtering based on packages and free-text. Is there any other (free) log viewer? I'm looking for anything that could work well with log4j. | You didn't mention an OS, so I'll mention this though it is only on Windows. Bare Metal Software makes a product called BareTail that has a nice interface and works well. They have a free version with a startup nag screen, a licensed version with no nag, and a pro version with additional features. It has configurable highlighting based on matching lines against keywords. They also have a BareGrep product too, which provides similar grep capabilities. Both are excellent and very stable and better than anything I've seen on Windows. I liked them so much I bought the bundle with both pro versions for $50. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23094/"
]
} |
144,810 | Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it's pretty easy), and I thought it would be cool if I were able to make a 'console' on my webpage (as in, you press the ` key like you do in FPS games, etc.), and then have it Ajax itself back to the server in-order to do stuff. I originally thought the best way would be to just get the text inside the textarea, and then split it, or should I use the keyup event, convert the keycode returned to an ASCII character, append the character to a string and send the string to the server (then empty the string). I couldn't find any information on getting text from a textarea, all I got was keyup information. Also, how can I convert the keycode returned to an ASCII character? | Why would you want to convert key strokes to text? Add a button that sends the text inside the textarea to the server when clicked. You can get the text using the value attribute as the poster before has pointed out, or using jQuery's API: $('input#mybutton').click(function() { var text = $('textarea#mytextarea').val(); //send to server and process response}); | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/144810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20900/"
]
} |
144,833 | I know that attributes are extremely useful. There are some predefined ones such as [Browsable(false)] which allows you to hide properties in the properties tab. Here is a good question explaining attributes: What are attributes in .NET? What are the predefined attributes (and their namespace) you actually use in your projects? | [DebuggerDisplay] can be really helpful to quickly see customized output of a Type when you mouse over the instance of the Type during debugging. example: [DebuggerDisplay("FirstName={FirstName}, LastName={LastName}")]class Customer{ public string FirstName; public string LastName;} This is how it should look in the debugger: Also, it is worth mentioning that [WebMethod] attribute with CacheDuration property set can avoid unnecessary execution of the web service method. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/144833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
]
} |
144,862 | I am in the process of writing a Bluetooth scanner that locates and identifies mobile devices in the local vicinity. Is this something that I can accomplish using C#, or do I need to drop down into the C/C++ APIs? My application is targeting Windows XP and Vista. Pointers are appreciated. Thanks! | One problem with Bluetooth on the PC is that there are several BT stacks in use and you can never quite know which one is available on a given machine. The most common ones are Widcomm (now Broadcom) and Microsoft (appeared in XP, maybe one of the service packs). However, some BT hardware vendors package BlueSoleil and some use Toshiba. Most dongles will work with the MS stack so the .NET libs I've seen tend to use that. Each of the stacks has a totally different way of doing the discovery part where you browse for nearby devices and inquire their services. If I had to pick one approach today I'd probably do the discovery in C++ and add an interface for .NET. The 32feet.net stuff worked pretty well when I tried it but didn't support the Widcomm stack. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23098/"
]
} |
144,892 | What's the easiest way to centre a java.awt.Window , such as a JFrame or a JDialog ? | From this link If you are using Java 1.4 or newer, you can use the simple method setLocationRelativeTo(null) on the dialog box, frame, or window to center it. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/144892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10433/"
]
} |
144,957 | How have you used the Exception.Data property in C# projects that you've worked on? I'd like answers that suggest a pattern, rather than those that are very specific to your app. | The exception logger I use has been tweaked to write out all the items in the Data collection. Then for every exception we encounter that we cannot diagnose from the exception stack, we add in all the data in that function's scope, send out a new build, and wait for it to reoccur. I guess we're optimists in that we don't put it in every function, but we are pessimists in that we don't take it out once we fix the issue. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7529/"
]
} |
144,959 | How can I copy and paste in irb (Interactive Ruby Shell) on Windows? | To avoid having to open the drop-down menu and clicking, you need to change the command window settings. To do this, right-click the title bar, choose Properties, turn on "QuickEdit Mode" under the Properties tab (and keep "Insert Mode" on), then OK. Now, to copy: drag to select, right-click to copy. To paste: right-click with no selection. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9776/"
]
} |
144,983 | Every time I start Emacs I see a page of help text and a bunch of messages suggesting that I try the tutorial. How do I stop this from happening? | Emacs has a couple of variables which inhibit these actions. If you edit your emacs control file (.emacs) and insert the following: ;; inhibit-startup-echo-area-message MUST be set to a hardcoded ;; string of your login name (setq inhibit-startup-echo-area-message "USERNAME")(setq inhibit-startup-message t) that should solve your problem. They basically set the inhibit parameters to true to prevent the behavior you want to get rid of. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11138/"
]
} |
144,985 | I was reading this answer previously and it got me interested in purchasing a Nintendo DS Lite for learning to program embedded devices. Before I go out and splurge on a DS I had a few questions: Are there any restrictions on what you can program? The post I indicated earlier seemed to say there weren't, but clarification would be nice. Would I be better off buying an arduino (or similar) and going that route? I like the DS because it already has a lot of hardware built in. I'm thinking of getting a CycloDS Evo card, is there a better option for homebrew? What are the best resources to learn about DS development? Thanks for your time, If you have a DS and program on it, I'd love you hear your opinion, or alternatively if you have a better idea, I'd like to hear it too. Thanks =] | No, there really isn't much of alimitation beyond that of thehardware, and even that can beovercome with enough effort. Quakehas been ported to DS, for example, and particle games that utilize both processors have been made. There has also been discussion on how to make higher quality 3D scenes using a double pass renderer. There are multiple resources on the Nintendo DS section of the GBADev forums . I would say that the DS is an excellent route to embedded systems development; there is a large and active community that is willing to answer questions and give support, and there is so much hardware built straight into the thing. It saves you the time of building a system to test on. The CycloDS Evolution is a good card and is fairly common, so it shouldn't be difficult - if necessary at all - to make your homebrew compatable with other cards. However, be aware that other popular choices are the M3 line and the R4 line, which are pretty much the same thing. I have a TTDS, and it works well, but not out of the box. I would reccommend the other three mentioned. As for beginning DS devving, I would reccommend looking at the basic examples found in the examples folder of devkitPro and reading the GBA tutorial TONC , which covers many of the concepts that are used in both GBA and DS development. A more DS oriented tutorial, Patater's Introduction to Nintendo DS Programming , will help beginners get on their way in the DS world. There is also a very comprehensive documentationspec for the GBA and DS known asGBATek . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15534/"
]
} |
144,993 | A lot of literature talks about using inline functions to "avoid the overhead of a function call". However I haven't seen quantifiable data. What is the actual overhead of a function call i.e. what sort of performance increase do we achieve by inlining functions? | On most architectures, the cost consists of saving all (or some, or none) of the registers to the stack, pushing the function arguments to the stack (or putting them in registers), incrementing the stack pointer and jumping to the beginning of the new code. Then when the function is done, you have to restore the registers from the stack. This webpage has a description of what's involved in the various calling conventions. Most C++ compilers are smart enough now to inline functions for you. The inline keyword is just a hint to the compiler. Some will even do inlining across translation units where they decide it's helpful. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
]
} |
145,006 | Very simply put, I have the following code snippet: FILE* test = fopen("C:\\core.u", "w");printf("Filepointer at: %d\n", ftell(test));fwrite(data, size, 1, test);printf("Written: %d bytes.\n", size);fseek(test, 0, SEEK_END);printf("Filepointer is now at %d.\n", ftell(test));fclose(test); and it outputs: Filepointer at: 0Written: 73105 bytes.Filepointer is now at 74160. Why is that? Why does the number of bytes written not match the file pointer? | Since you're opening the file in text mode, it will convert end-of-line markers, such as LF, into CR/LF. This is likely if you're running on Windows (and you probably are, given that your file name starts with "c:\" ). If you open the file in "wb" mode, I suspect you'll find the numbers are identical: FILE* test = fopen("C:\\core.u", "wb"); The C99 standard has this to say in 7.19.5.3 The fopen function : The argument mode points to a string. If the string is one of the following, the file is open in the indicated mode. Otherwise, the behaviour is undefined. r open text file for reading w truncate to zero length or create text file for writing a append; open or create text file for writing at end-of-file rb open binary file for reading wb truncate to zero length or create binary file for writing ab append; open or create binary file for writing at end-of-file r+ open text file for update (reading and writing) w+ truncate to zero length or create text file for update a+ append; open or create text file for update, writing at end-of-file r+b or rb+ open binary file for update (reading and writing) w+b or wb+ truncate to zero length or create binary file for update a+b or ab+ append; open or create binary file for update, writing at end-of-file You can see they distinguish between w and wb . I don't believe an implementation is required to treat the two differently but it's usually safer to use binary mode for binary data. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
145,026 | I believe the architecture type (x86 vs x64) is abstracted away for you when making .Net programs, but are there any other considerations that can cause problems? | Beware of third-party COM libraries or third party .NET libraries that secretly make win32 calls. That's where we had our biggest headaches. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
145,027 | I have some accesses from 192.168.0.71 on my apache logs. I looked up this IP (because my server almost exclusively takes requests from 127.0.0.1, and I saw that it's reserved for "special purposes." What types of purposes might those be? Edit: I didn't tell you, typing 192.168.0.71 brings me straight to my site, just as 127.0.0.1 would. I just wonder how this is different, then from 127.0.0.1. | RFC 1918 reserves addresses starting with 192.168 for private networks. This most likely means that some computer on your local network is accessing the server. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
]
} |
145,053 | I am looking get to grips with functional programming concepts. I've used Javascript for many years for client side scripting in web applications and apart from using prototypes it was all simple DOM manipulation, input validation etc. Of late, I have often read that Javascript is one of the languages that supports functional programming. With my familiarity and experience with Javascript, my preference is to use it to learn functional programming. I expect I would be able to concentrate more on the main functional concepts and not get bogged down or distracted by a completely new syntax. So in summary, is Javascript a good choice to learn functional programming concepts? What capabilities in Javascript are relevant/support functional programming? | JavaScript supports first class functions. See Use functional programming techniques to write elegant JavaScript . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023/"
]
} |
145,096 | I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this? | Overview: It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately. C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function). C++ does change the definition of some terms in C such as structs, although still in a superset way. Examples of why it is not a strict superset: This Wikipedia article has a couple good examples of such a differences: One commonly encountered difference is that C allows implicit conversion from void* to other pointer types, but C++ does not. So, the following is valid C code: int *i = malloc(sizeof(int) * 5); ... but to make it work in both C and C++ one would need to use an explicit cast: int *i = (int *) malloc(sizeof(int) * 5) Another common portability issue is that C++ defines many new keywords, such as new and class, that may be used as identifiers (e.g. variable names) in a C program. This wikipedia article has further differences as well: C++ compilers prohibit goto from crossing an initialization, as in the following C99 code: void fn(void) { goto flack; int i = 1; flack: ; } What should you learn first? You should learn C++ first, not because learning C first will hurt you, not because you will have to unlearn anything (you won't), but because there is no benefit in learning C first. You will eventually learn just about everything about C anyway because it is more or less contained in C++. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/145096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23126/"
]
} |
145,110 | My understanding is that C/C++ produces native code to run on a particular machine architecture. Conversely, languages like Java and C# run on top of a virtual machine which abstracts away the native architecture. Logically it would seem impossible for Java or C# to match the speed of C++ because of this intermediate step, however I've been told that the latest compilers ("hot spot") can attain this speed or even exceed it. Perhaps this is more of a compiler question than a language question, but can anyone explain in plain English how it is possible for one of these virtual machine languages to perform better than a native language? | Generally, C# and Java can be just as fast or faster because the JIT compiler -- a compiler that compiles your IL the first time it's executed -- can make optimizations that a C++ compiled program cannot because it can query the machine. It can determine if the machine is Intel or AMD; Pentium 4, Core Solo, or Core Duo; or if supports SSE4, etc. A C++ program has to be compiled beforehand usually with mixed optimizations so that it runs decently well on all machines, but is not optimized as much as it could be for a single configuration (i.e. processor, instruction set, other hardware). Additionally certain language features allow the compiler in C# and Java to make assumptions about your code that allows it to optimize certain parts away that just aren't safe for the C/C++ compiler to do. When you have access to pointers there's a lot of optimizations that just aren't safe. Also Java and C# can do heap allocations more efficiently than C++ because the layer of abstraction between the garbage collector and your code allows it to do all of its heap compression at once (a fairly expensive operation). Now I can't speak for Java on this next point, but I know that C# for example will actually remove methods and method calls when it knows the body of the method is empty. And it will use this kind of logic throughout your code. So as you can see, there are lots of reasons why certain C# or Java implementations will be faster. Now this all said, specific optimizations can be made in C++ that will blow away anything that you could do with C#, especially in the graphics realm and anytime you're close to the hardware. Pointers do wonders here. So depending on what you're writing I would go with one or the other. But if you're writing something that isn't hardware dependent (driver, video game, etc), I wouldn't worry about the performance of C# (again can't speak about Java). It'll do just fine. One the Java side, @Swati points out a good article: https://www.ibm.com/developerworks/library/j-jtp09275 | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/145110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23126/"
]
} |
145,131 | I work with a lot of web applications that are driven by databases of varying complexity on the backend. Typically, there's an ORM layer separate from the business and presentation logic. This makes unit-testing the business logic fairly straightforward; things can be implemented in discrete modules and any data needed for the test can be faked through object mocking. But testing the ORM and database itself has always been fraught with problems and compromises. Over the years, I have tried a few strategies, none of which completely satisfied me. Load a test database with known data. Run tests against the ORM and confirm that the right data comes back. The disadvantage here is that your test DB has to keep up with any schema changes in the application database, and might get out of sync. It also relies on artificial data, and may not expose bugs that occur due to stupid user input. Finally, if the test database is small, it won't reveal inefficiencies like a missing index. (OK, that last one isn't really what unit testing should be used for, but it doesn't hurt.) Load a copy of the production database and test against that. The problem here is that you may have no idea what's in the production DB at any given time; your tests may need to be rewritten if data changes over time. Some people have pointed out that both of these strategies rely on specific data, and a unit test should test only functionality. To that end, I've seen suggested: Use a mock database server, and check only that the ORM is sending the correct queries in response to a given method call. What strategies have you used for testing database-driven applications, if any? What has worked the best for you? | I've actually used your first approach with quite some success, but in a slightly different ways that I think would solve some of your problems: Keep the entire schema and scripts for creating it in source control so that anyone can create the current database schema after a check out. In addition, keep sample data in data files that get loaded by part of the build process. As you discover data that causes errors, add it to your sample data to check that errors don't re-emerge. Use a continuous integration server to build the database schema, load the sample data, and run tests. This is how we keep our test database in sync (rebuilding it at every test run). Though this requires that the CI server have access and ownership of its own dedicated database instance, I say that having our db schema built 3 times a day has dramatically helped find errors that probably would not have been found till just before delivery (if not later). I can't say that I rebuild the schema before every commit. Does anybody? With this approach you won't have to (well maybe we should, but its not a big deal if someone forgets). For my group, user input is done at the application level (not db) so this is tested via standard unit tests. Loading Production Database Copy: This was the approach that was used at my last job. It was a huge pain cause of a couple of issues: The copy would get out of date from the production version Changes would be made to the copy's schema and wouldn't get propagated to the production systems. At this point we'd have diverging schemas. Not fun. Mocking Database Server: We also do this at my current job. After every commit we execute unit tests against the application code that have mock db accessors injected. Then three times a day we execute the full db build described above. I definitely recommend both approaches. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/145131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20745/"
]
} |
145,154 | My singleton accessor method is usually some variant of: static MyClass *gInstance = NULL;+ (MyClass *)instance{ @synchronized(self) { if (gInstance == NULL) gInstance = [[self alloc] init]; } return(gInstance);} What could I be doing to improve this? | Another option is to use the +(void)initialize method. From the documentation: The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses. So you could do something akin to this: static MySingleton *sharedSingleton;+ (void)initialize{ static BOOL initialized = NO; if(!initialized) { initialized = YES; sharedSingleton = [[MySingleton alloc] init]; }} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/145154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23113/"
]
} |
145,175 | Right now I write expressions in the *scratch* buffer and test them by evaluating with C-x C-e . I would really appreciate having an interactive interpreter like SLIME or irb, in which I could test Emacs Lisp expressions. | It's easy to evaluate Lisp expressions in Inferior Emacs-Lisp Mode: M-x ielm You can read more about this feature in the Emacs manual section on "Lisp Interaction" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/145175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21998/"
]
} |
145,176 | I guess the question is self-explanatory, but I'm wondering whether HTML qualifies as a programming language (obviously the "L" stands for language). The reason for asking is more pragmatic—I'm putting together a resume and don't want to look like a fool for listing things like HTML and XML under languages, but can't figure out how to classify them. | No, HTML is not a programming language. The "M" stands for "Markup". Generally, a programming language allows you to describe some sort of process of doing something, whereas HTML is a way of adding context and structure to text. If you're looking to add more alphabet soup to your CV, don't classify them at all. Just put them in a big pile called "Technologies" or whatever you like. Remember, however, that anything you list is fair game for a question. HTML is so common that I'd expect almost any technology person to already know it (although not stuff like CSS and so on), so you might consider not listing every initialism you've ever come across. I tend to regard CVs listing too many things as suspicious, so I ask more questions to weed out the stuff that shouldn't be listed. :) However, if your HTML experience includes serious web design stuff including Ajax, JavaScript, and so on, you might talk about those in your "Experience" section. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/145176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
145,185 | What's the best way to store tags for a record? Just use a varchar field? What about when selecting rows that contains tag x? Use the like operator? thanks! | Depends on two things: 1) The amount of tags/tagged records 2) Whether or not you have a religious opinion on normalization :-) Unless dealing with very large volumes of data, I'd suggest having a 'Tags' table mapping varchar values to integer identifiers then second table mapping tagged records to their tag ids. I'd suggest implementing this first, then check if it doesn't meet your performance needs. In that case, keep a single table with a id for the tagged row and the actual text of the tag, but in this I'd suggest you use a char column as it will kill your query if the optimizer does a full table scan against a large table with a varchar column. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17648/"
]
} |
145,236 | One thing I've always wondered about is how software patches work. A lot of software seems to just release new versions on their binaries that need to be installed over older versions, but some software (operating systems like Windows in particular) seem to be able to release very small patches that correct bugs or add functionality to existing software. Most of the time the patches I see can't possibly replace entire applications, or even small files that are used within applications. To me it seems like the actual binary is being modified. How are these kinds of patches actually implemented? Could anyone point me to any resources that explain how this works, or is it just as simple as replacing small components such as linked libraries in an application? I'll probably never need to do a deployment in this manner, but I am curious to find out how it works. If I'm correct in my understanding that patches can really modify only portions of binary files, is this possible to do in .NET? If it is I'd like to learn it since that's the framework I'm most familiar with and I'd like to understand how it works. | This is usually implemented using binary diff algorithms -- diff the most recently released version against the new code. If the user's running the most recent version, you only need to apply the diff. Works particularly well against software, because compiled code is usually pretty similar between versions. Of course, if the user's not running the most recent version you'll have to download the whole thing anyway. There are a couple implementations of generic binary diff algorithms: bsdiff and xdelta are good open-source implementations. I can't find any implementations for .NET, but since the algorithms in question are pretty platform-agnostic it shouldn't be too difficult to port them if you feel like a project. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
} |
145,247 | Is there a free software for creating windows help files for your program? I would like something that allows an output of both CHM and HTML files. | Yes. HelpMaker from sourceforge (The original site www.vizacc.com is down). Best free help utility ever. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
145,263 | Wikipedia has this to say: Total functional programming (also known as strong functional programming, to be contrasted with ordinary, or weak functional programming) is a programming paradigm which restricts the range of programs to those which are provably terminating. and These restrictions mean that total functional programming is not Turing-complete. However, the set of algorithms which can be used is still huge. For example, any algorithm which has had an asymptotic upper bound calculated for it can be trivially transformed into a provably-terminating function by using the upper bound as an extra argument which is decremented upon each iteration or recursion. There is also a Lambda The Ultimate Post about a paper on Total Functional Programming . I hadn't come across that until last week on a mailing list. Are there any more resources, references or any example implementations that you know of? | If I understood that correctly, Total Functional Programming means just that: Programming with Total Functions. If I remember my math courses correctly, a Total Function is a function which is defined over its entire domain, a Partial Function is one which has "holes" in its definition. Now, if you have a function which for some input value v goes into an infinite recursion or an infinite loop or in general doesn't terminate in some other fashion, then your function isn't defined for v , and thus partial, i.e. not total. Total Functional Programming doesn't allow you to write such a function. All functions always return a result for all possible inputs; and the type checker ensures that this is the case. My guess is that this vastly simplifies error handling: there aren't any. The downside is already mentioned in your quote: it's not Turing-complete. E.g. an Operating System is essentially a giant infinite loop. Indeed, we do not want an Operating System to terminate, we call this behaviour a "crash" and yell at our computers about it! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
} |
145,270 | What would be the quickest way to construct a Python binding to a C or C++ library? (I am using Windows if this matters.) | ctypes module is part of the standard library, and therefore is more stable and widely available than swig , which always tended to give me problems . With ctypes, you need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against. Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp: #include <iostream>class Foo{ public: void bar(){ std::cout << "Hello" << std::endl; }}; Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C" extern "C" { Foo* Foo_new(){ return new Foo(); } void Foo_bar(Foo* foo){ foo->bar(); }} Next you have to compile this to a shared library g++ -c -fPIC foo.cpp -o foo.og++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o And finally you have to write your python wrapper (e.g. in fooWrapper.py) from ctypes import cdlllib = cdll.LoadLibrary('./libfoo.so')class Foo(object): def __init__(self): self.obj = lib.Foo_new() def bar(self): lib.Foo_bar(self.obj) Once you have that you can call it like f = Foo()f.bar() #and you will see "Hello" on the screen | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/145270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
]
} |
145,272 | Does anyone know where to get the source code for LambdaProbe? Alternatively, does anyone know if the project could be moved to a community repository? Besides the tool not being updated for over a year, the LambdaProbe website has been down since late September 2008. Background: Lambda Probe is a useful tool for viewing stats on a running tomcat server. It used to be found at http://www.lambdaprobe.org . | There seems to be a fork of the project over at http://code.google.com/p/psi-probe/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22935/"
]
} |
145,291 | Can you have smart behavior for the home key in Emacs? By smart I mean that instead of going to the character number 0, it should go to the first non-blank character, and go to 0 on a second pressing, and back to the first non-blank in a third and so on.Having smart end would be nice as well. | (defun smart-beginning-of-line () "Move point to first non-whitespace character or beginning-of-line.Move point to the first non-whitespace character on this line.If point was already at that position, move point to beginning of line." (interactive "^") ; Use (interactive) in Emacs 22 or older (let ((oldpos (point))) (back-to-indentation) (and (= oldpos (point)) (beginning-of-line))))(global-set-key [home] 'smart-beginning-of-line) I'm not quite sure what smart end would do. Do you normally have a lot of trailing whitespace? Note: The major difference between this function and Robert Vuković's is that his always moves to the first non-blank character on the first keypress, even if the cursor was already there. Mine would move to column 0 in that case. Also, he used (beginning-of-line-text) where I used (back-to-indentation) . Those are very similar, but there are some differences between them. (back-to-indentation) always moves to the first non-whitespace character on a line. (beginning-of-line-text) sometimes moves past non-whitespace characters that it considers insignificant. For instance, on a comment-only line, it moves to the first character of the comment's text, not the comment marker. But either function could be used in either of our answers, depending on which behavior you prefer. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/145291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
]
} |
145,304 | I have been trying to learn multi-threaded programming in C# and I am confused about when it is best to use a thread pool vs. create my own threads. One book recommends using a thread pool for small tasks only (whatever that means), but I can't seem to find any real guidelines. What are some pros and cons of thread pools vs creating my own threads? And what are some example use cases for each? | If you have lots of logical tasks that require constant processing and you want that to be done in parallel use the pool+scheduler. If you need to make your IO related tasks concurrently such as downloading stuff from remote servers or disk access, but need to do this say once every few minutes, then make your own threads and kill them once you're finished. Edit: About some considerations, I use thread pools for database access, physics/simulation, AI(games), and for scripted tasks ran on virtual machines that process lots of user defined tasks. Normally a pool consists of 2 threads per processor (so likely 4 nowadays), however you can set up the amount of threads you want, if you know how many you need. Edit: The reason to make your own threads is because of context changes, (thats when threads need to swap in and out of the process, along with their memory). Having useless context changes, say when you aren't using your threads, just leaving them sit around as one might say, can easily half the performance of your program (say you have 3 sleeping threads and 2 active threads). Thus if those downloading threads are just waiting they're eating up tons of CPU and cooling down the cache for your real application | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/145304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
145,312 | What is the maximum number of threads you can create in a C# application? And what happens when you reach this limit? Is an exception of some kind thrown? | There is no inherent limit. The maximum number of threads is determined by the amount of physical resources available. See this article by Raymond Chen for specifics. If you need to ask what the maximum number of threads is, you are probably doing something wrong. [ Update : Just out of interest: .NET Thread Pool default numbers of threads: 1023 in Framework 4.0 (32-bit environment) 32767 in Framework 4.0 (64-bit environment) 250 per core in Framework 3.5 25 per core in Framework 2.0 (These numbers may vary depending upon the hardware and OS)] | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/145312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
145,337 | What is the most efficient way to check if an array is a flat arrayof primitive values or if it is a multidimensional array ? Is there any way to do this without actually looping through anarray and running is_array() on each of its elements? | The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do is_array($arr[0]); But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()): $ more multi.php<?php$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));$b = array(1 => 'a',2 => 'b');$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));function is_multi($a) { $rv = array_filter($a,'is_array'); if(count($rv)>0) return true; return false;}function is_multi2($a) { foreach ($a as $v) { if (is_array($v)) return true; } return false;}function is_multi3($a) { $c = count($a); for ($i=0;$i<$c;$i++) { if (is_array($a[$i])) return true; } return false;}$iters = 500000;$time = microtime(true);for ($i = 0; $i < $iters; $i++) { is_multi($a); is_multi($b); is_multi($c);}$end = microtime(true);echo "is_multi took ".($end-$time)." seconds in $iters times\n";$time = microtime(true);for ($i = 0; $i < $iters; $i++) { is_multi2($a); is_multi2($b); is_multi2($c);}$end = microtime(true);echo "is_multi2 took ".($end-$time)." seconds in $iters times\n";$time = microtime(true);for ($i = 0; $i < $iters; $i++) { is_multi3($a); is_multi3($b); is_multi3($c);}$end = microtime(true);echo "is_multi3 took ".($end-$time)." seconds in $iters times\n";?>$ php multi.phpis_multi took 7.53565130424 seconds in 500000 timesis_multi2 took 4.56964588165 seconds in 500000 timesis_multi3 took 9.01706600189 seconds in 500000 times Implicit looping, but we can't shortcircuit as soon as a match is found... $ more multi.php<?php$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));$b = array(1 => 'a',2 => 'b');function is_multi($a) { $rv = array_filter($a,'is_array'); if(count($rv)>0) return true; return false;}var_dump(is_multi($a));var_dump(is_multi($b));?>$ php multi.phpbool(true)bool(false) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/145337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
]
} |
145,354 | After searching online, the best solution I've found so far is to just make a symbolic link in either "/Library/logs/" or "~/Library/logs/" to get it to show up in the Console application. I'm wondering if it would be possible to add a new directory or log file to the "root" level directly under the "LOG FILES" section in the console. Here's a quick screenshot: | There is one way to get your log files into the console. You can add a symlink to the log file or log directory to one of the directories in the list. The directory ~/Library/Logs seems like the logical choice for adding your own log files. For myself I wanted easy access to apache2 logs. I installed apache2 using macports and the default log file is located at /opt/local/apache2/logs . Thus all I did was create the symlink to that directory. # cd ~/Library/Logs# ln -s /opt/local/apache2/logs/ apache2 Now I can easily use the console.app to get to the logs. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
]
} |
145,371 | I'd like to open the intelligence window without typing a character and then backspacing it. I can't seem to remember the shortcut for this. What is it? | Ctrl + Space ? Also, go to Tools -> Options -> Environment -> Keyboard or Default Keyboard Shortcuts in Visual Studio , you can then search for commands and see what is assigned to that (and remap). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
]
} |
145,400 | How do I dictate the destination folder of a clickOnce application? | This is not possible with ClickOnce. ClickOnce applications are always installed in the Apps subdirectory of local application data. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23149/"
]
} |
145,402 | Can anyone recommend some useful performance analysis tools for PHP scripts? Anything that could help me find problematic or unusually slow blocks of code, details about execution time, etc. would be really helpful. I know there are tools out there, but I'm wondering what people recommend as being the most useful and well-designed. | Try webgrind . It gives you the profiling of CacheGrinder in an easy to read, browser based format. I'm on a Mac and it has made profiling a breeze. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
]
} |
145,480 | Checking the HTML source of a question I see for instance: <a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript> JavaScript is needed to access comments.</noscript> And then in the javascript source: // Setup our click events..$().ready(function() { $("a[id^='comments-link-']").click(function() { comments.show($(this).attr("id").substr("comments-link-".length)); }); }); It seems that all the user click events are binded this way. The downsides of this approach are obvious for people browsing the site with no javascript but, what are the advantages of adding events dynamically whith javascript over declaring them directly? | You don't have to type the same string over and over again in the HTML (which if nothing else would increase the number of typos to debug) You can hand over the HTML/CSS to a designer who need not have any javascript skills You have programmatic control over what callbacks are called and when It's more elegant because it fits the conceptual separation between layout and behaviour It's easier to modify and refactor On the last point, imagine if you wanted to add a "show comments" icon somewhere else in the template. It'd be very easy to bind the same callback to the icon. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
]
} |
145,484 | I used to work with eclipse for nearly all the languages I need. I'm asked to work on a tool developed in C# and so, I would like to stay in the same familiar environment. I've found the improve's plugin but its last release is from 2004 and .NET 1.1 which is quite old. Is there a newer plugin to program in C# within eclipse or am I forced to take a look at VS? | Emonic integrates mono into the eclipse framework, that may be of use. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9396/"
]
} |
145,508 | If you think it shouldn't, explain why. If yes, how deep should the guidelines be in your opinion? For example, indentation of code should be included? | I think a team (rather than a company ) need to agree on a set of guidelines for reasonably consistent style. It makes it more straightforward for maintenance. How deep? As shallow as you can agree on. The shorter and clearer it is the more likely it is that all the team members can agree to it and will abide by it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23034/"
]
} |
145,509 | Title is the entire question. Can someone give me a reason why this happens? | Yes - because it does begin with the empty string. Indeed, the empty string logically occurs between every pair of characters. Put it this way: what definition of "starts with" could you give that would preclude this? Here's a simple definition of "starts with" that doesn't: "x starts with y if the first y.Length characters of x match those of y." An alternative (equivalent) definition: "x starts with y if x.Substring(0, y.Length).Equals(y) " | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/145509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11137/"
]
} |
145,540 | I have Apache running on a public-facing Debian server, and am a bit worried about the security of the installation. This is a machine that hosts several free-time hobby projects, so none of us who use the machine really have the time to constantly watch for upstream patches, stay aware of security issues, etc. But I would like to keep the bad guys out, or if they get in, keep them in a sandbox. So what's the best, easy to set up, easy to maintain solution here? Is it easy to set up a user-mode linux sandbox on Debian? Or maybe a chroot jail? I'd like to have easy access to files inside the sadbox from the outside. This is one of those times where it becomes very clear to me that I'm a programmer, not a sysadmin. Any help would be much appreciated! | Chroot jails can be really insecure when you are running a complete sandbox environment. Attackers have complete access to kernel functionality and for example may mount drives to access the "host" system. I would suggest that you use linux-vserver. You can see linux-vserver as an improved chroot jail with a complete debian installation inside. It is really fast since it is running within one single kernel, and all code is executed natively. I personally use linux-vserver for seperation of all my services and there are only barely noticeable performance differences. Have a look at the linux-vserver wiki for installation instructions. regards, Dennis | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
145,563 | Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job. example: int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2} the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs. | Sort the array and then do a quick pass to count each number. The algorithm has O(N*logN) complexity. Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorithm now depends on the complexity of your hasing function. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8786/"
]
} |
145,565 | Is there any free set of forms, icons, styles, images, etc for building web-based admin interfaces? If yes, which is the best? | A particularly common choice is Silk . It's a very comprehensive free set. There's also the Silk Companion 1 . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16826/"
]
} |
145,586 | Cruisecontrol and Hudson are two popular continuous integration systems. Although both systems are able to do the automated continuous builds nicely, it just seems a lot easier to create a batch or bash build script, then use Windows scheduler or cron to schedule builds. Are there better continuous integration systems available for C++ projects? Or is just using a script and a scheduler the simpler way? | We have been using CruiseControl for CI on a C++ project. While it is the only thing we use ant for, the ant build script for CruiseControl just starts our normal build script, so it is very simple and we haven't really needed to update it in a long while. Therefore the fact that CrusieControl is Java based has not really been an issue at all for us. The main benefits of using something like cruise control are A nice web page showing build status Email after each build or after failed builds Automatically build after a commit to the source control system A firefox plugin to monitor the build status Shows the output for any build errors. Shows what files have changed since the last build (good for seeing which developer broke the buid) Of course you can write a script yourself which does all of this, but why do all that work? In the long run the extra initial cost of setting up CruiseControl (or something similar) is probably much less than the cost of maintaining and updating a custom CI build script. If all you need is to launch a daily build and a simple script started by cron is sufficient for your needs then by all means do that. However, one of the advantages of CI is that you get a build status report after every check in. Writing a script to do that takes more work and CruiseControl already does it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22807/"
]
} |
145,607 | I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not. The implementation can be in c# or python. Thanks. | In Python, there is difflib , as also others have suggested. difflib offers the SequenceMatcher class, which can be used to give you a similarity ratio. Example function: def text_compare(text1, text2, isjunk=None): return difflib.SequenceMatcher(isjunk, text1, text2).ratio() | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
} |
145,617 | The case goes as following:You have a Boolean property called FullScreenEnabled. You enter some method, and the code within this method is executed iff FullScreenEnabled is true. Which of the 2 approaches below do you use in your everyday programming: private bool FullScreenEnabled { get; set; } // Check if FullScreenEnabled is false and return; private void Case1() { if (FullScreenEnabled == false) { return; } // code to be executed goes here! } // Surround the code by an if statement. private void Case2() { if (FullScreenEnabled) { // code to be executed goes here! } } | private void MyMethod(bool arg){ if(arg) return; //do stuff}; (for voting) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113670/"
]
} |
145,651 | How can I use Cron on Google App Engine? | Google has officially enabled cron in the AppEngine, for more details check: Cron for Python: http://code.google.com/appengine/docs/python/config/cron.html Cron for Java: http://code.google.com/appengine/docs/java/config/cron.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
145,657 | I need to compare large count of PDF files for it optical content. Because the PDF files was created on different platforms and with different versions of the software there are structural differences. For example: the chunking of text can be different the write order can be different the position can be differ some pixels It should compare the content like a human people and not the internal structure. I want test for regressions between different versions of the PDF generator that we used. | Because there is no such tool available that we have written one. You can download the i-net PDF content comparer and use it. I hope that help other with the same problem. If you have problems with it or you have feedback for us then you can contact our support. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12631/"
]
} |
145,676 | You know that particular part of your code that is essential for the project but will probably take a lot of time to get it done? Do you ever get the feeling that you'd rather work on something else (probably less important) or not code at all instead of working on that part? That beast you try so hard to avoid and use every lazy trick you know to delay its inevitable implementation? Now, I'm probably just being lazy, but I've always had to deal with code like that. Write something I don't feel like writing (and it's worse if you're doing it for fun and not getting paid!). A large system that will take a lot of time to get it into a stage where you get back any useful results or indication of it working. How do you start coding something like that? Most people would probably suggest divide and conquer and similar architectural techniques, but this isn't about how you do it; it's about how you get yourself started on doing it. What's the very first steps you'd take? | I'll tell a story of a case in which this happened to me. I wanted to implement a new frametype decision algorithm for x264 that used forward dynamic programming (the Viterbi algorithm). But it was going to be complicated, messy, ugly, and so forth. And I really didn't want to do it. I tried to pawn off the project onto Google Summer of Code, but out of some sort of terrible bad luck, the one student that we had that simply bailed on his project... was the student that chose that project. So after two months of complaining about it and dodging it, I finally got to work on the algorithm. And here's how I did it. First, I talked to the other developer, who apparently already had some ideas on how to do it. We talked it over and he explained it to me until I fully understood the process from an algorithmic standpoint. This is the first step of any such project: understand the algorithm behind it so well that you can pseudocode the entire thing. Then, I talked to another coworker of mine. We went up to a whiteboard and I sketched it out until he understood it too. By explaining it to someone else, I gained understanding myself. This is the second step: explain the algorithm to someone else so well that they can pseudocode it. This is an emulation of the programming process, since programming is a form of "explaining" an algorithm to the computer. Then, I wrote a simple Java prototype that used arbitrary fake values for the cost function and was solely being used to test the Viterbi search. I finished it, and checked it against an exhaustive search--it matched perfectly. My dynamic programming was correct. This is the third step: write the simplest possible form of the algorithm in the simplest possible environment. Then I ported it to C, x264's native language. It worked again. This is the fourth step: port that simple form of the algorithm to the full environment. Then, finally, I replaced the fake cost function with the real one. After some bughunting and fixing, it worked. This is the final step: integrate the algorithm completely with the environment. This process took barely a week, but from the perspective of me at the start of the project, it was completely daunting and I couldn't get myself to even get started--yet by breaking it down into such a step by step process, I was able to not only get it done , but get it done much faster than I expected. And the benefits went far beyond x264; I now understand Viterbi so thoroughly that I now can explain it to others... and those others can benefit greatly from it. For example, one of the ffmpeg developers is using an adaptation of my algorithm and code to optimally solve a somewhat different problem: optimal header placement in audio files. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23153/"
]
} |
145,689 | Design patterns are usually related to object oriented design. Are there design patterns for creating and programming relational databases ? Many problems surely must have reusable solutions. Examples would include patterns for table design, stored procedures, triggers, etc... Is there an online repository of such patterns, similar to martinfowler.com ? Examples of problems that patterns could solve: Storing hierarchical data (e.g. single table with type vs multiple tables with 1:1 key and differences...) Storing data with variable structure (e.g. generic columns vs xml vs delimited column...) Denormalize data (how to do it with minimal impact, etc...) | There's a book in Martin Fowler's Signature Series called Refactoring Databases . That provides a list of techniques for refactoring databases. I can't say I've heard a list of database patterns so much. I would also highly recommend David C. Hay's Data Model Patterns and the follow up A Metadata Map which builds on the first and is far more ambitious and intriguing. The Preface alone is enlightening. Also a great place to look for some pre-canned database models is Len Silverston's Data Model Resource Book Series Volume 1 contains universally applicable data models (employees, accounts, shipping, purchases, etc), Volume 2 contains industry specific data models (accounting, healthcare, etc), Volume 3 provides data model patterns. Finally, while this book is ostensibly about UML and Object Modelling, Peter Coad's Modeling in Color With UML provides an "archetype" driven process of entity modeling starting from the premise that there are 4 core archetypes of any object/data model | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/145689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
]
} |
145,728 | Is there a built-in way to escape user input in java using the JDBC ? Something similar to the php version mysql_real_escape() function. What's the best way to validate input? | If you mean how do you make sure user input can't be used in SQL injection attacks, the way to do this (and the way all SQL should be written in JDBC) is using Prepared Statements. JDBC will automatically handle any necessary escaping. http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
]
} |
145,752 | For the most part, you just take whatever Visual Studio sets it for you as a default... I'm referring to the BuildAction property for each file selected in Solution Explorer. There are a number of options and it's difficult to know what each one of them will do. | None : The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file. Compile : The file is compiled into the build output. This setting is used for code files. Content : Allows you to retrieve a file (in the same directory as the assembly) as a stream via Application.GetContentStream(URI). For this method to work, it needs a AssemblyAssociatedContentFile custom attribute which Visual Studio graciously adds when you mark a file as "Content" Embedded resource : Embeds the file in an exclusive assembly manifest resource. Resource (WPF only) : Embeds the file in a shared (by all files in the assembly with similar setting) assembly manifest resource named AppName.g.resources. Page (WPF only) : Used to compile a xaml file into baml . The baml is then embedded with the same technique as Resource (i.e. available as `AppName.g.resources) ApplicationDefinition (WPF only) : Mark the XAML/class file that defines your application. You specify the code-behind with the x:Class="Namespace.ClassName" and set the startup form/page with StartupUri="Window1.xaml" SplashScreen (WPF only) : An image that is marked as SplashScreen is shown automatically when an WPF application loads, and then fades DesignData : Compiles XAML viewmodels so that usercontrols can be previewed with sample data in Visual Studio (uses mock types) DesignDataWithDesignTimeCreatableTypes : Compiles XAML viewmodels so that usercontrols can be previewed with sample data in Visual Studio (uses actual types) EntityDeploy : (Entity Framework) : used to deploy the Entity Framework artifacts CodeAnalysisDictionary : An XML file containing custom word dictionary for spelling rules | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/145752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
]
} |
145,771 | I have tried to find how to create DLL-s on linux using google, but got very confusing information. Is it possible to write dynamic link libraries on linux? If not, are there other means by which I can call code in another module from several running programs? | That's because DLL is a Windows term. In Linux they are called shared libraries. http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
]
} |
145,800 | What is your favorite, lossless image format for games (namely 2d games)? And why? Some things to take into consideration are size on disk, overhead for converting to a usable format, and features of the format (ie alpha support). There is no best answer, but be sure to back yours up the best you can! | I'd suggest PNG. Most software supports writing it, most libraries support reading it, it's lossless and supports alpha transparency. And it's a standard format. And, maybe important for hobbyist 2D games, very small images also result in very small files (i.e. a 16x16 icon can be 1KB or less). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23175/"
]
} |
145,802 | Clicking through to the download-page if see that the last version of the download is over one year old and it's also "just" a Release Candidate of version 1.0. There are really no news on any development. Yes, you can find newer versions from the nightly builds, but that's not a real serious option. Also, the "getting-started" and description-pages are sometimes not even started and some not completed. What's the deal? Any C# 3.0 features on the way or what? | I'd suggest PNG. Most software supports writing it, most libraries support reading it, it's lossless and supports alpha transparency. And it's a standard format. And, maybe important for hobbyist 2D games, very small images also result in very small files (i.e. a 16x16 icon can be 1KB or less). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
]
} |
145,803 | I have a little dilemma on how to set up my visual studio builds for multi-targeting. Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project. Right now, the platform target is set to x86 so it can be run on Windows x64. The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program. This raises some questions which I haven't got the answers to yet.I want to have the exact same code base.I must build with references to either the 32bit set of DLL's or 64bit DLL's.(Both 3rd party and SQL Server Compact) Can this be solved with 2 new sets of configurations (Debug64 and Release64) ? Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi? Any ideas and/or recommendations would be welcomed. | Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are: References to outside managed assemblies with the same name but their own specific bitness (this also applies to COM interop assemblies) The MSI package (which, as has already been noted, will need to target either x86 or x64) Any custom .NET Installer Class-based actions in your MSI package The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like: <Reference Include="Filename, ..., processorArchitecture=x86"> <HintPath>C:\path\to\x86\DLL</HintPath></Reference> Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g: <ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> <Reference ...>....</Reference></ItemGroup> Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.: <ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' "> <Reference Include="Filename, ..., processorArchitecture=AMD64"> <HintPath>C:\path\to\x64\DLL</HintPath> </Reference></ItemGroup> After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine. Solving the MSI issue is up next, and unfortunately this will require a non-VS.NET tool: I prefer Caphyon's Advanced Installer for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well. You can probably achieve the same results using other tools or the Windows Installer XML (WiX) toolset , but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives. One thing you may still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines. This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework. Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk... Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example): <ItemGroup Condition="'$(Platform)' == 'x86'"> <Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86" /></ItemGroup><ItemGroup Condition="'$(Platform)' == 'x64'"> <Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64" /></ItemGroup> The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/145803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584/"
]
} |
145,838 | What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today? | Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger. Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people. Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it. I could see a situation like this making a detectable difference: inline int aplusb_pow2(int a, int b) { return (a + b)*(a + b) ;}for(int a = 0; a < 900000; ++a) for(int b = 0; b < 900000; ++b) aplusb_pow2(a, b); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/145838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22040/"
]
} |
145,842 | I'm interested in finding out what people would consider the most useful data structures to know in programming. What data structure do you find yourself using all the time? Answers to this post should help new programmers interested in finding a useful data structure for their problem. Answers should probably include the data structure, information about it or a relevant link, the situation it is being used in and why it is a good choice for this problem (e.g ideal computation complexities, simplicity and understanding etc.) Each answer should be about one data structure only. Thanks for any pearls of wisdom and experience people can share. | One of the data structures I use the most (beyond vectors, of course) is the Hashtable.Its about the only choise if you need to be able to search large quantities of data in O(1) time, that means the time to search does not grow as the size of the collection grows. The catch is that the insertion and deletion times are larger than in other data strutures, and you need to have some sort of key with which to search the collection. Every element must have a key.The algorithm takes the key of each element and computes an hash code that indicates the slot in the hash table in which to search.Then depending on the implementation it either follows a list of items that fell on that bucket to find your item or it searches nearby buckets.The size of the hastable is determinant to the efficiency of the hash that is quite affected by the ammount of collisions of hash codes between keys. Use it whenever you need a map and the expected number of elements of the map exceed about 10. Its a bit more more memory intensive than other structures since it needs lots of unused slots in the table to be efficient. C# has a great implementation of it with Dictionary<keytype, valuetype> and even has a HybridDictionary that decides internally when to use a hashtable or a vector.Any good programming book describes it but you will be well served by wikipedia: http://en.wikipedia.org/wiki/Hashtable | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20388/"
]
} |
145,856 | I have an array of integers: int[] number = new int[] { 2,3,6,7 }; What is the easiest way of converting these into a single string where the numbers are separated by a character (like: "2,3,6,7" )? I'm using C# and .NET 3.5. | var ints = new int[] {1, 2, 3, 4, 5};var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());Console.WriteLine(result); // prints "1,2,3,4,5" As of (at least) .NET 4.5, var result = string.Join(",", ints.Select(x => x.ToString()).ToArray()); is equivalent to: var result = string.Join(",", ints); I see several solutions advertise usage of StringBuilder. Someone complains that the Join method should take an IEnumerable argument. I'm going to disappoint you :) String.Join requires an array for a single reason - performance. The Join method needs to know the size of the data to effectively preallocate the necessary amount of memory. Here is a part of the internal implementation of String.Join method: // length computed from length of items in input array and length of separatorstring str = FastAllocateString(length);fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here{ UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length); buffer.AppendString(value[startIndex]); for (int j = startIndex + 1; j <= num2; j++) { buffer.AppendString(separator); buffer.AppendString(value[j]); }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/145856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298/"
]
} |
145,863 | What's the best cross platform Java Swing browser component at least able to play nicely in a swing interface (lightweight component ?) and able to run on MacOSX and Windows ? Things like : FlyingSaucer , JDIC , maybe others ? | i belive this could help: http://djproject.sourceforge.net/ns/index.html | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2512/"
]
} |
145,880 | The Objective Caml language will only produce stack traces if you ask for them just right - what are the requirements for both bytecode and native code? | Compile with -g and set environment variable OCAMLRUNPARAM=b | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12874/"
]
} |
145,922 | I've managed to get a memory 'leak' in a java application I'm developing. When running my JUnit test suite I randomly get out of memory exceptions (java.lang.OutOfMemoryError). What tools can I use to examine the heap of my java application to see what's using up all my heap so that I can work out what's keeping references to objects which should be able to be garbage collected. | VisualVM is included in the most recent releases of Java. You can use this to create a heap dump, and look at the objects in it. Alternatively, you can also create a heapdump commandine using jmap (in your jdk/bin dir): jmap -dump:format=b,file=heap.bin <pid> You can even use this to get a quick histogram of all objects jmap -histo <pid> I can recommend Eclipse Memory Analyzer ( http://eclipse.org/mat ) for advanced analysis of heap dumps. It lets you find out exactly why a certain object or set of objects is alive. Here's a blog entry showing you what Memory Analyzer can do: http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/ | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/145922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849/"
]
} |
145,951 | What is the first thing you do when you install Visual Studio? I am talking about anything customization-wise (so we don't get answers based on 'I create a new project'). Do you have a favorite font? Do you have a must have extension you couldn't possibly live without? Do you have a keyboard shortcut you like to set? I am interested to know your favorites. For me, I only change the font to Calibri, I find it is easier to read, and I can fit more text on the screen. | I install ReSharper (sold by JetBrains) because it adds a lot of IDE behaviors/features that I became dependent on using Java IDEs. The first thing I make others do is turn on line numbers for all file types, because it is impossible to pair with someone if you can't tell then what line of code you are looking at. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/145951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20900/"
]
} |
146,020 | I'm doing some Android development, and I much prefer Visual Studio, but I'll have to use Eclipse for this. Has anyone made a tool which can make Eclipse look and behave more like visual studio? I mainly can't stand its clippyesqe suggestions on how I should program (Yes, I know I have not yet used that private field! Thanks Eclipse!), or its incredibly lousy intellisense . For example, in eclipse, if I don't type this first, its intellisense won't realise I want to look for locally scoped members. Also, the TAB to complete VS convention is drilled into my head, and Eclipse is ENTER to complete, I could switch everything by hand but that would take hours, and I was hoping someone had some sort of theme or something that has already done it. | There are also other choices for Java IDEs. You've obviously found Eclipse, but you also may want to check out IntelliJ and NetBeans . IntelliJ is not free, but has a 30 day evaluation period and a Visual Studio key map :) Shop around, find one that you like and start to use it heavily. They are all very good IDEs, and I'm sure once you use one for a while you'll get comfortable with it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
146,106 | This question is about organizing the actual CSS directives themselves within a .css file. When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can. After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout. Does anyone have advice for how to organize the directives? Should I try to organize top-down, mimicking the DOM? Should I organize functionally, putting directives for elements that support the same parts of the UI together? Should I just sort everything alphabetically by selector? Some combination of these approaches? Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files? Say, 1000 lines? Or is it always a good idea to keep the whole thing in one place? Related Question: What's the best way to organize CSS rules? | Have a look at these three slideshare presentations to start: Beautiful Maintainable CSS Maintainable CSS Efficient, maintainable, modular CSS Firstly, and most importantly, document your CSS. Whatever method you use to organize your CSS, be consistent and document it. Describe at the top of each file what is in that file, perhaps providing a table of contents, perhaps referencing easy to search for unique tags so you jump to those sections easily in your editor. If you want to split up your CSS into multiple files, by all means do so. Oli already mentioned that the extra HTTP requests can be expensive, but you can have the best of both worlds. Use a build script of some sort to publish your well-documented, modular CSS to a compressed, single CSS file. The YUI Compressor can help with the compression. In contrast with what others have said so far, I prefer to write each property on a separate line, and use indentation to group related rules. E.g. following Oli's example: #content { /* css */} #content div { /* css */ } #content span { /* css */ } #content etc { /* css */ }#header { /* css */} #header etc { /* css */ } That makes it easy to follow the file structure, especially with enough whitespace and clearly marked comments between groups, (though not as easy to skim through quickly) and easy to edit (since you don't have to wade through single long lines of CSS for each rule). Understand and use the cascade and specificity (so sorting your selectors alphabetically is right out). Whether I split up my CSS into multiple files, and in what files depends on the size and complexity of the site and the CSS. I always at least have a reset.css . That tends to be accompanied by layout.css for general page layout, nav.css if the site navigation menus get a little complicated and forms.css if I've got plenty of CSS to style my forms. Other than that I'm still figuring it out myself too. I might have colors.css and type.css/fonts.css to split off the colors/graphics and typography, base.css to provide a complete base style for all HTML tags... | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/146106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
]
} |
146,134 | I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing? using System;using System.IO;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?"; illegal = illegal.Trim(Path.GetInvalidFileNameChars()); illegal = illegal.Trim(Path.GetInvalidPathChars()); Console.WriteLine(illegal); Console.ReadLine(); } }} | Try something like this instead; string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());foreach (char c in invalid){ illegal = illegal.Replace(c.ToString(), ""); } But I have to agree with the comments, I'd probably try to deal with the source of the illegal paths, rather than try to mangle an illegal path into a legitimate but probably unintended one. Edit: Or a potentially 'better' solution, using Regex's. string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));illegal = r.Replace(illegal, ""); Still, the question begs to be asked, why you're doing this in the first place. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/146134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
]
} |
146,146 | This is what my browser sent, when logging into some site: POST http://www.some.site/login.php HTTP/1.0User-Agent: Opera/8.26 (X2000; Linux i686; Z; en)Host: www.some.siteAccept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1Accept-Language: en-US,en;q=0.9Accept-Charset: iso-8859-1, utf-8, utf-16, *;q=0.1Accept-Encoding: deflate, gzip, x-gzip, identity, *;q=0Referer: http://www.some.site/Proxy-Connection: closeContent-Length: 123Content-Type: application/x-www-form-urlencodedlots_of_stuff=here&e2ad811= my_login_name &e327696= my_password &lots_of_stuff=here Can I state that anyone can sniff my login name and password for that site?Maybe just on my LAN? If so (even only on LAN ) then I'm shocked. I thought using <input type="password"> did something more than make all characters look like ' * ' p.s. If it matters I played with netcat (on linux) and made connection browser <=> netcat (loged here) <=> proxy <=> remote_site | Every data sent trought a http connection can be seen by someone in your route to the server (man in the middle attack). type="password" only hides the character on-screen, and even other programs on your computer can read the data. The only way to protect the data is to send it trought SSL (HTTPS instead of HTTP) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15453/"
]
} |
146,159 | From time to time I read that Fortran is or can be faster then C for heavy calculations. Is that really true? I must admit that I hardly know Fortran, but the Fortran code I have seen so far did not show that the language has features that C doesn't have. If it is true, please tell me why. Please don't tell me what languages or libs are good for number crunching, I don't intend to write an app or lib to do that, I'm just curious. | The languages have similar feature-sets. The performance difference comes from the fact that Fortran says aliasing is not allowed, unless an EQUIVALENCE statement is used. Any code that has aliasing is not valid Fortran, but it is up to the programmer and not the compiler to detect these errors. Thus Fortran compilers ignore possible aliasing of memory pointers and allow them to generate more efficient code. Take a look at this little example in C: void transform (float *output, float const * input, float const * matrix, int *n){ int i; for (i=0; i<*n; i++) { float x = input[i*2+0]; float y = input[i*2+1]; output[i*2+0] = matrix[0] * x + matrix[1] * y; output[i*2+1] = matrix[2] * x + matrix[3] * y; }} This function would run slower than the Fortran counterpart after optimization. Why so? If you write values into the output array, you may change the values of matrix. After all, the pointers could overlap and point to the same chunk of memory (including the int pointer!). The C compiler is forced to reload the four matrix values from memory for all computations. In Fortran the compiler can load the matrix values once and store them in registers. It can do so because the Fortran compiler assumes pointers/arrays do not overlap in memory. Fortunately, the restrict keyword and strict-aliasing have been introduced to the C99 standard to address this problem. It's well supported in most C++ compilers these days as well. The keyword allows you to give the compiler a hint that the programmer promises that a pointer does not alias with any other pointer. The strict-aliasing means that the programmer promises that pointers of different type will never overlap, for example a double* will not overlap with an int* (with the specific exception that char* and void* can overlap with anything). If you use them you will get the same speed from C and Fortran. However, the ability to use the restrict keyword only with performance critical functions means that C (and C++) programs are much safer and easier to write. For example, consider the invalid Fortran code: CALL TRANSFORM(A(1, 30), A(2, 31), A(3, 32), 30) , which most Fortran compilers will happily compile without any warning but introduces a bug that only shows up on some compilers, on some hardware and with some optimization options. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/146159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18687/"
]
} |
146,204 | Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like: Dictionary<string, List<object>> But this is quite irritating to actually use. In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET. | If you're using .NET 3.5, use the Lookup class. EDIT: You generally create a Lookup using Enumerable.ToLookup . This does assume that you don't need to change it afterwards - but I typically find that's good enough. If that doesn't work for you, I don't think there's anything in the framework which will help - and using the dictionary is as good as it gets :( | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/146204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
146,269 | I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected). I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas. | The easiest way to do this is to supply a template for the "ItemContainerStyle" and NOT the "ItemTemplate" property. In the code below I create 2 data templates: one for the "unselected" and one for the "selected" states. I then create a template for the "ItemContainerStyle" which is the actual "ListBoxItem" that contains the item. I set the default "ContentTemplate" to the "Unselected" state, and then supply a trigger that swaps out the template when the "IsSelected" property is true. (Note: I am setting the "ItemsSource" property in the code behind to a list of strings for simplicity) <Window.Resources><DataTemplate x:Key="ItemTemplate"> <TextBlock Text="{Binding}" Foreground="Red" /></DataTemplate><DataTemplate x:Key="SelectedTemplate"> <TextBlock Text="{Binding}" Foreground="White" /></DataTemplate><Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle"> <Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" /> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" /> </Trigger> </Style.Triggers></Style></Window.Resources><ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource ContainerStyle}" /> | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/146269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23222/"
]
} |
146,271 | EDIT: This question is more about language engineering than C++ itself. I used C++ as an example to show what I wanted, mostly because I use it daily. I didn't want to know how it works on C++ but open a discussion on how it could be done. That's not the way it works right now, that's the way I wish it could be done, and that would break C compability for sure, but that's what I think extern "C" is all about. I mean, in every function or method that you declare right now you have to explicit write that the object will be sent by reference prefixing the reference operator on it. I wish that every non-POD type would be automatically sent by reference, because I use that a lot, actually for every object that is more than 32 bits in size, and that's almost every class of mine. Let's exemplify how it's right now, assume a , b and c to be classes: class example { public: int just_use_a(const a &object); int use_and_mess_with_b(b &object); void do_nothing_on_c(c object);}; Now what I wish: class example { public: int just_use_a(const a object); int use_and_mess_with_b(b object); extern "C" void do_nothing_on_c(c object);}; Now, do_nothing_on_c() could behave just like it is today. That would be interesting at least for me, feels much more clear, and also if you know every non-POD parameter is coming by reference I believe the mistakes would be the same that if you had to explicit declare it. Another point of view for this change, from someone coming from C, the reference operator seems to me a way to get the variable address , that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too? | I guess you're missing the point of C++, and C++ semantics. You missed the fact C++ is correct in passing (almost) everything by value, because it's the way it's done in C. Always . But not only in C, as I'll show you below... Parameters Semantics on C In C, everything is passed by value. "primitives" and "PODs" are passed by copying their value. Modify them in your function, and the original won't be modified. Still, the cost of copying some PODs could be non-trivial. When you use the pointer notation (the * ), you're not passing by reference. You're passing a copy of the address. Which is more or less the same, with but one subtle difference: typedef struct { int value ; } P ;/* p is a pointer to P */void doSomethingElse(P * p){ p->value = 32 ; p = malloc(sizeof(P)) ; /* Don't bother with the leak */ p->value = 45 ;}void doSomething(){ P * p = malloc(sizeof(P)) ; p->value = 25 ; doSomethingElse(p) ; int i = p->value ; /* Value of p ? 25 ? 32 ? 42 ? */} The final value of p->value is 32. Because p was passed by copying the value of the address. So the original p was not modified (and the new one was leaked). Parameters Semantics on Java and C Sharp It can be surprising for some, but in Java, everything is copied by value, too. The C example above would give exactly the same results in Java. This is almost what you want, but you would not be able to pass primitive "by reference/pointer" as easily as in C. In C#, they added the "ref" keyword. It works more or less like the reference in C++. The point is, on C#, you have to mention it both on the function declaration, and on each and every call. I guess this is not what you want, again. Parameters Semantics on C++ In C++, almost everything is passed by copying the value. When you're using nothing but the type of the symbol, you're copying the symbol (like it is done in C). This is why, when you're using the *, you're passing a copy of the address of the symbol. But when you're using the &, then assume you are passing the real object (be it struct, int, pointer, whatever): The reference. It is easy to mistake it as syntaxic sugar (i.e., behind the scenes, it works like a pointer, and the generated code is the same used for a pointer). But... The truth is that the reference is more than syntaxic sugar. Unlike pointers, it authorizes manipulating the object as if on stack. Unline pointers, when associatied with the const keyword, it authorizes implicit promotion from one type to another (through constructors, mainly). Unlike pointers, the symbol is not supposed to be NULL/invalid. Unlike the "by-copy", you are not spending useless time copying the object Unlike the "by-copy", you can use it as an [out] parameter Unlike the "by-copy", you can use the full range of OOP in C++ (i.e. you pass a full object to a function waiting an interface). So, references has the best of both worlds. Let's see the C example, but with a C++ variation on the doSomethingElse function: struct P { int value ; } ;// p is a reference to a pointer to Pvoid doSomethingElse(P * & p){ p->value = 32 ; p = (P *) malloc(sizeof(P)) ; // Don't bother with the leak p->value = 45 ;}void doSomething(){ P * p = (P *) malloc(sizeof(P)) ; p->value = 25 ; doSomethingElse(p) ; int i = p->value ; // Value of p ? 25 ? 32 ? 42 ?} The result is 42, and the old p was leaked, replaced by the new p. Because, unlike C code, we're not passing a copy of the pointer, but the reference to the pointer, that is, the pointer itself. When working with C++, the above example must be cristal clear. If it is not, then you're missing something. Conclusion C++ is pass-by-copy/value because it is the way everything works, be it in C, in C# or in Java (even in JavaScript... :-p ...). And like C#, C++ has a reference operator/keyword, as a bonus . Now, as far as I understand it, you are perhaps doing what I call half-jockingly C+ , that is, C with some limited C++ features. Perhaps your solution is using typedefs (it will enrage your C++ colleagues, though, to see the code polluted by useless typedefs...), but doing this will only obfuscate the fact you're really missing C++ there. As said in another post, you should change your mindset from C development (of whatever) to C++ development, or you should perhaps move to another language. But do not keep programing the C way with C++ features, because by consciously ignoring/obfuscating the power of the idioms you use, you'll produce suboptimal code. Note: And do not pass by copy anything else than primitives. You'll castrate your function from its OO capacity, and in C++, this is not what you want. Edit The question was somewhat modified (see https://stackoverflow.com/revisions/146271/list ). I let my original answer, and answer the new questions below. What you think about default pass-by-reference semantics on C++? Like you said, it would break compatibility, and you'll have different pass-by for primitives (i.e. built-in types, which would still be passed by copy) and structs/objects (which would be passed as references). You would have to add another operator to mean "pass-by-value" (the extern "C" is quite awful and already used for something else quite different). No, I really like the way it is done today in C++. [...] the reference operator seems to me a way to get the variable address, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too? Yes and no. Operator >> changed its semantic when used with C++ streams, too. Then, you can use operator += to replace strcat. I guess the operator & got used because its signification as "opposite of pointer", and because they did not want to use yet another symbol (ASCII is limited, and the scope operator :: as well as pointer -> shows that few other symbols are usable). But now, if & bothers you, && will really unnerve you, as they added an unary && in C++0x (a kind of super-reference...). I've yet to digest it myself... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623/"
]
} |
146,275 | I have a templated class defined (in part) as template <class T> MyClass{public: void DoSomething(){}}; If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way. My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place. Has anyone any suggestions? | Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those. Something like this: class Base { public: virtual ~Base(){} virtual void DoSomething() = 0;}template <class T> class MyClass : public Base {public: void DoSomething(){}};std::vector<Base *> objects;objects.push_back(new MyClass<int>);objects.push_back(new MyClass<char>); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23167/"
]
} |
146,297 | With a huge influx of newbies to Xcode, I'm sure there are lots of Xcode tips and tricks to be shared. What are yours? | Switch to Header/Source File Option ⌥ Command ⌘ Up Arrow ↑ View > Switch to Header/Source File Switches between the .m and .h files. In Xcode 4 this is ctrl Command ⌘ Up Arrow ↑ | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/146297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23113/"
]
} |
146,316 | What number of classes do you think is ideal per one namespace "branch"? At which point would one decide to break one namespace into multiple ones? Let's not discuss the logical grouping of classes (assume they are logically grouped properly), I am, at this point, focused on the maintainable vs. not maintainable number of classes. | "42? No, it doesn't work..." Ok, let's put our programming prowess to work and see what is Microsoft's opinion: # IronPythonimport Systemexported_types = [ (t.Namespace, t.Name) for t in System.Int32().GetType().Assembly.GetExportedTypes()]import itertoolsget_ns = lambda (ns, typename): nssorted_exported_types = sorted(exported_types, key=get_ns)counts_per_ns = dict( (ns, len(list(typenames))) for ns, typenames in itertools.groupby(sorted_exported_types, get_ns))counts = sorted(counts_per_ns.values())print 'Min:', counts[0]print 'Max:', counts[-1]print 'Avg:', sum(counts) / len(counts)print 'Med:',if len(counts) % 2: print counts[len(counts) / 2]else: # ignoring len == 1 case print (counts[len(counts) / 2 - 1] + counts[len(counts) / 2]) / 2 And this gives us the following statistics on number of types per namespace: C:\tools\nspop>ipy nspop.pyMin: 1Max: 173Avg: 27Med: 15 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
]
} |
146,354 | I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server. So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically? $database = 'live';if (some staging environment variable is true) { $database = 'testing'; // and not live} If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile Hope this makes sense many thanks Ian | Yep...you can do this: SetEnv DATABASE_NAME testing and then in PHP: $database = $_SERVER["DATABASE_NAME"]; or $database = getenv("DATABASE_NAME"); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
]
} |
146,358 | I'm using .NET 3.5. I have two string arrays, which may share one or more values: string[] list1 = new string[] { "apple", "orange", "banana" };string[] list2 = new string[] { "banana", "pear", "grape" }; I'd like a way to merge them into one array with no duplicate values: { "apple", "orange", "banana", "pear", "grape" } I can do this with LINQ: string[] result = list1.Concat(list2).Distinct().ToArray(); but I imagine that's not very efficient for large arrays. Is there a better way? | string[] result = list1.Union(list2).ToArray(); from msdn : "This method excludes duplicates from the return set. This is different behavior to the Concat(TSource) method, which returns all the elements in the input sequences including duplicates." | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/146358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5142/"
]
} |
146,359 | I am trying to figure out this: c = 1def f(n): print c + n def g(n): c = c + nf(1) # => 2g(1) # => UnboundLocalError: local variable 'c' referenced before assignment Thanks! | Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global statement: def g(n): global c c = c + n This is one of the quirky areas of Python that has never really sat well with me. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/146359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462204/"
]
} |
146,381 | I keep reading about C99 and C++11 and all these totally sweet things that are getting added to the language standard that might be nice to use someday. However, we currently languish in the land of writing C++ in Visual Studio. Will any of the new stuff in the standard ever get added to visual studio, or is Microsoft more interested in adding new C# variants to do that? Edit: In addition to the accepted answer, I found the Visual C++ team blog: http://blogs.msdn.com/vcblog/ And specifically, this post in it: https://web.archive.org/web/20190109064523/https://blogs.msdn.microsoft.com/vcblog/2008/02/22/tr1-slide-decks/ Very useful. Thanks! | MS has a series of public replies to this, most of them blaming their users. Like this one: https://devblogs.microsoft.com/cppblog/iso-c-standard-update/ Now, the Visual C++ compiler team receives the occasionally question as to why we haven’t implemented C99. It’s really based on interest from our users. Where we’ve received many requests for certain C99 features, we’ve tried to implement them (or analogues). A couple examples are variadic macros, long long , __pragma , __FUNCTION__ , and __restrict . If there are other C99 features that you’d find useful in your work, let us know! We don’t hear much from our C users, so speak up and make yourselves heard http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=345360 Hi: unfortunately the overwhelming feadback we get from the majority of our users is that they would prefer that we focus on C++-0x instead of on C-99. We have "cherry-picked" certain popular C-99 features (variadic macros, long long ) but beyond this we are unlikely to do much more in the C-99 space (at least in the short-term). Jonathan Caves Visual C++ Compiler Team. This is a pretty sad state of affairs, but also makes sense if you suspect MS wants to lock users in: it makes it very hard to port modern gcc-based code into MSVC, which at least I find extremely painful. A workaround exists, though: Note that Intel is much more enlightened on this. the Intel C compiler can handle C99 code and even has the same flags as gcc, making it much easier to port code between platforms. Also, the Intel compiler works in visual studio. So by scrapping MS COMPILER you can still use the MS IDE that you seem to think has some kind of value, and use C99 to your hearts content. A more sensible approach is honestly to move over to Intel CC or gcc, and use Eclipse for your programming environment. Portability of code across Windows-Linux-Solaris-AIX-etc is usually important in my experience, and that is not at all supported by MS tools, unfortunately. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/146381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13500/"
]
} |
146,390 | In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string. For example: >>> a = (1,"Hello",7.2)>>> print "these are the values %d, %s, %f" % athese are the values 1, Hello, 7.200000 Is there some way to use any array or collection in a java printf statement in a similar way? I've looked at the documentation and it appears to have built in support for some types like Calendar, but I don't see anything for collections. If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)? | printf will have a declaration along the lines of: public PrintString printf(String format, Object... args); ... means much the same as [] . The difference is ... allows the caller to omit explicitly creating an array. So consider: out.printf("%s:%s", a, b); That is the equivalent of: out.printf("%s:%s", new Object[] { a, b }); So, getting back to your question, for an array, you can just write: out.printf("%s:%s", things); For a collection: out.printf("%s:%s", things.toArray()); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4138/"
]
} |
146,391 | I can't figure out a use case for being able to annotate interfaces in Java. Maybe someone could give me an example? | I've used it in Spring to annotate interfaces where the annotation should apply to all subclasses. For example, say you have a Service interface and you might have multiple implementations of the interface but you want a security annotation to apply regardless of the annotation. In that case, it makes the most sense to annotate the interface. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
} |
146,435 | I have a file temp.txt, that I want to sort with the sort command in bash. I want the sorted results to replace the original file. This doesn't work for example (I get an empty file): sortx temp.txt > temp.txt Can this be done in one line without resorting to copying to temporary files? EDIT: The -o option is very cool for sort . I used sort in my question as an example. I run into the same problem with other commands: uniq temp.txt > temp.txt. Is there a better general solution? | sort temp.txt -o temp.txt | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/146435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
]
} |
146,452 | I've come across this term POD-type a few times. What does it mean? | POD stands for Plain Old Data - that is, a class (whether defined with the keyword struct or the keyword class ) without constructors, destructors and virtual members functions. Wikipedia's article on POD goes into a bit more detail and defines it as: A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type. Greater detail can be found in this answer for C++98/03 . C++11 changed the rules surrounding POD, relaxing them greatly, thus necessitating a follow-up answer here . | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/146452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
]
} |
146,466 | I have a Nintendo Wii , and I've got devkitpro working to load some simple programs. The example source code that I've been able to find is very simplistic, such as drawing and rotating a simple shape. I've been looking for more in depth tutorials, and I haven't been able to find much. Most of the applications available on wiibrew are open source, so I could look through those. However, I'd rather have something that's a little more geared towards teaching certain techniques, rather than have to browse through someone else's code to find the answer. What are some good tutorials? Currently I'm stuck at just getting alpha (translucent) colours to work, but I'm also interested in getting lighting and other more advanced graphics techniques working. | I'm going to provide you with some nice links: Getting started (dead) Wii Programming (dead) Wii Wiki about Homebrew A Blogger who talks about Wii Programming A big resource on Wii Development (dead) Another very good resource is WiiBrew , here are some development specific links: Tutorials Debugging Development Tools DevkitPro Getting started with Development Developer Tips I know you've been to WiiBrew before but it's a very good resource, even if you want to go advanced.Good luck and have fun programming for Wii! (But please, don't make another Fitness-game ;) ) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
]
} |
146,486 | I'm looking for: documentation blogs books ready-to-use pre-configured slice images services wrappers libraries tutorials ...anything that would make it easier to start using EC2 to host a Rails application. | There is a Rails image for EC2 at http://ec2onrails.rubyforge.org/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
]
} |
146,522 | I’ve got a brand new Django project. I’ve added one minimal view function to views.py , and one URL pattern to urls.py , passing the view by function reference instead of a string: # urls.py# -------# coding=utf-8from django.conf.urls.defaults import *from myapp import viewsurlpatterns = patterns('', url(r'^myview/$', views.myview),)# views.py----------# coding=utf-8from django.http import HttpResponsedef myview(request): return HttpResponse('MYVIEW LOL', content_type="text/plain") I’m trying to use reverse() to get the URL, by passing it a function reference. But I’m not getting a match, despite confirming that the view function I’m passing to reverse is the exact same view function I put in the URL pattern: >>> from django.core.urlresolvers import reverse>>> import urls>>> from myapp import views>>> urls.urlpatterns[0].callback is views.myviewTrue>>> reverse(views.myview)Traceback (most recent call last): File "<console>", line 1, in <module> File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse *args, **kwargs))) File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse "arguments '%s' not found." % (lookup_view, args, kwargs))NoReverseMatch: Reverse for '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found. As far as I can tell from the documentation, function references should be fine in both the URL pattern and reverse() . URL patterns with function references reverse with function references I’m using the Django trunk, revision 9092. | Got it!! The problem is that some of the imports are of myproject.myapp.views , and some are just of myapp.views . This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main settings.py probably has a line like: ROOT_URLCONF = `myproject.urls` To solve this, try using the full import in your shell session: >>> from django.core.urlresolvers import reverse>>> from myproject.myapp import views>>> reverse(views.myview)'/myview/' Here's a log of the debugging session, for any interested future readers: >>> from django.core import urlresolvers>>> from myapp import myview>>> urlresolvers.get_resolver (None).reverse_dict{None: ([(u'myview/', [])], 'myview/$'), <function myview at 0x845d17c>: ([(u'myview/', [])], 'myview/$')}>>> v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0]>>> reverse(v1)'/myview/'>>> v1 is myviewFalse>>> v1.__module__'testproject.myapp.views'>>> myview.__module__'myapp.views' What happens if you change the URL match to be r'^myview/$' ? Have you tried it with the view name? Something like reverse ('myapp.myview') ? Is urls.py the root URLconf, or in the myapp application? There needs to be a full path from the root to a view for it to be resolved. If that's myproject/myapp/urls.py , then in myproject/urls.py you'll need code like this: from django.conf.urls.defaults import patternsurlpatterns = patterns ('', (r'^/', 'myapp.urls'),) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578/"
]
} |
146,543 | What is the best way to version control my database objects? I'm using Visual studio 2005/2008 and SQL server 2005. I would prefer a solution which can be used with SVN. | Same as your other code, add a "Database project" to your application solution and keep the sql files used to build the database objects in there. Use the same version control for those code files as you do for the application. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22016/"
]
} |
146,557 | I was reading a question about the Python global statement ( "Python scope" ) and I was remembering about how often I used this statement when I was a Python beginner (I used global a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic". Do you use this statement in Python ? Has your usage of it changed with time ? | I use 'global' in a context such as this: _cached_result = Nonedef myComputationallyExpensiveFunction(): global _cached_result if _cached_result: return _cached_result # ... figure out result _cached_result = result return result I use 'global' because it makes sense and is clear to the reader of the function what is happening. I also know there is this pattern, which is equivalent, but places more cognitive load on the reader: def myComputationallyExpensiveFunction(): if myComputationallyExpensiveFunction.cache: return myComputationallyExpensiveFunction.cache # ... figure out result myComputationallyExpensiveFunction.cache = result return resultmyComputationallyExpensiveFunction.cache = None | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20037/"
]
} |
146,575 | I'm writing a program (for Mac OS X, using Objective-C) and I need to create a bunch of .webloc files programmatically. The .webloc file is simply file which is created after you drag-n-drop an URL from Safari's location bar to some folder. Generally speaking, I need an approach to create items in a filesystem which point to some location in the Web. As I understand .webloc files should be used for this on Mac OS X. So, is it possible to craft a .webloc file having a valid url and some title for it? | It is little known - but there is also a simple plist based file format for weblocs. When creating webloc files you DO NOT NEED to save them using the resource method the other three posters describe. You can also write a simple plist: <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict> <key>URL</key> <string>http://apple.com</string></dict></plist> The binary resource format is still in active use and if you want to read a plist file - then sure you need to read both file formats. But when writing the file - use the plist based format - it is a lot easier. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20294/"
]
} |
146,576 | The method signature of a Java main method is: public static void main(String[] args) { ...} Is there a reason why this method must be static? | The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this: public class JavaClass{ protected JavaClass(int x){} public void main(String[] args){ }} Should the JVM call new JavaClass(int) ? What should it pass for x ? If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called. There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why main is static. I have no idea why main is always marked public though. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/146576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
]
} |
146,607 | My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this: This input: The Web Should produce this output: The Web This Is A Test Variable I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.) This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with. def stripMatchedQuotes(item): MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE) MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE) item = MatchedSingleQuotes.sub(r'\1', item, 1) item = MatchedDoubleQuotes.sub(r'\1', item, 1) return itemdef processVariables(item): VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE) VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE) Variables={} while VariableDefinition.search(item): VarName, VarDef = VariableDefinition.search(item).groups() VarName = stripMatchedQuotes(VarName).upper().strip() VarDef = stripMatchedQuotes(VarDef.strip()) Variables[VarName] = VarDef item = VariableDefinition.sub('', item, 1) while VariableUse.search(item): VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip() item = VariableUse.sub(Variables[VarName], item, 1) return item | The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled. Another possibility is to use a single regex as below: MatchedQuotes = re.compile(r"(['\"])(.*)\1", re.LOCALE)item = MatchedQuotes.sub(r'\2', item, 1) Finally, you can combine this into the regex in processVariables. Taking Torsten Marek's suggestion to use a function for re.sub, this improves and simplifies things dramatically. VariableDefinition = re.compile(r'<%(["\']?)(.*?)\1=(["\']?)(.*?)\3%>', re.LOCALE)VarRepl = re.compile(r'<%(["\']?)(.*?)\1%>', re.LOCALE)def processVariables(item): vars = {} def findVars(m): vars[m.group(2).upper()] = m.group(4) return "" item = VariableDefinition.sub(findVars, item) return VarRepl.sub(lambda m: vars[m.group(2).upper()], item)print processVariables('<%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%>') Here are my timings for 100000 runs: Original : 13.637Global regexes : 12.771Single regex : 9.095Final version : 1.846 [Edit] Add missing non-greedy specifier [Edit2] Added .upper() calls so case insensitive like original version | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19207/"
]
} |
146,622 | I'm in the process of learning Erlang. As an exercise I picked up the Sieve of Eratosthenes algorithm of generating prime numbers. Here is my code: -module(seed2).-export([get/1]).get(N) -> WorkList = lists:duplicate(N, empty), get(2, N, WorkList, []).get(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);get(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList), NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList), get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime), markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked), markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).findNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;findNextPrime(Iterator, N, WorkList) -> I = lists:nth(Iterator, WorkList), if I =:= empty -> Iterator; true -> findNextPrime(Iterator + 1, N, WorkList) end.replace(N, L, New)-> {L1, [_H|L2]} = lists:split(N - 1, L), lists:append(L1, [New|L2]). This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation. My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes" EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that? | Here's a simple (but not terribly fast) sieve implementation: -module(primes).-export([sieve/1]).-include_lib("eunit/include/eunit.hrl").sieve([]) -> [];sieve([H|T]) -> List = lists:filter(fun(N) -> N rem H /= 0 end, T), [H|sieve(List)];sieve(N) -> sieve(lists:seq(2,N)). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13635/"
]
} |
146,657 | I have a couple of header files, which boil down to: tree.h: #include "element.h"typedef struct tree_{ struct *tree_ first_child; struct *tree_ next_sibling; int tag; element *obj; ....} tree; and element.h: #include "tree.h"typedef struct element_{ tree *tree_parent; char *name; ...} element; The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included. This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known. How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)? | I think the problem here is not the missing include guard but the fact that the two structures need each other in their definition. So it's a type define hann and egg problem. The way to solve these in C or C++ is to do forward declarations on the type. If you tell the compiler that element is a structure of some sort, the compiler is able to generate a pointer to it. E.g. Inside tree.h: // tell the compiler that element is a structure typedef:typedef struct element_ element;typedef struct tree_ tree;struct tree_{ tree *first_child; tree *next_sibling; int tag; // now you can declare pointers to the structure. element *obj;}; That way you don't have to include element.h inside tree.h anymore. You should also put include-guards around your header-files as well. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19214/"
]
} |
146,659 | I know this would be easy with position:fixed, but unfortanately I'm stuck with supporting IE 6. How can I do this? I would rather use CSS to be clean, but if I have to use Javascript, that's not the end of the world. In my current implementation I have a "floating footer" that floats above the main content area and is positioned with Javascript. The implementation I have right now is not particular elegant even with the Javascript, so my questions are: Is there a way to do this without Javascript? If I have to use Javascript, are there any "nice" solutions to this floating footer problem? By "nice" I mean something that will work across browsers, doesn't overload the browser's resources (since it will have to recalculate often), and is elegant/easy to use (i.e. it would be nice to write something like new FloatingFooter("floatingDiv") ). I'm going to guess there is no super easy solution that has everything above, but something I can build off of would be great. Finally, just a more general question. I know this problem is a big pain to solve, so what are other UI alternatives rather than having footer content at the bottom of every page? On my particular site, I use it to show transitions between steps. Are there other ways I could do this? | This may work for you. It works on IE6 and Firefox 2.0.0.17 for me. Give it a shot. I made the footer's height very tall, just for effect. You would obviously change it to what you need. I hope this works for you. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>Liquid Footer</title> <style type="text/css"> .footer {background-color: #cdcdcd;height: 180px;text-align: center;font-size:10px;color:#CC0000;font-family:Verdana;padding-top: 10px;width: 100%;position:fixed;left: 0px;bottom: 0px;} </style> <!--[if lte IE 6]> <style type="text/css"> body {height:100%; overflow-y:auto;} html {overflow-x:auto; overflow-y:hidden;} * html .footer {position:absolute;} </style> <![endif]--></head><body> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> <div class="footer">-- This is your liquid footer --</div></body></html> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
]
} |
146,668 | In ruby I am parsing a date in the following format: 24092008.I want to convert each section (year, month, date) into a number. I have split them up using a regex which produces three Strings which I am passing into the Integer constructor. date =~ /^([\d]{2})([\d]{2})([\d]{4})/ year = Integer($3) month = Integer($2) day = Integer($1) When it hits the month line it crashes as follows: `Integer': invalid value for Integer: "09" (ArgumentError) It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07"). Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first? Thanks. | I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are strings. Here's what I did in IRB to replicate the problem: irb(main):003:0> Integer("04")=> 4irb(main):004:0> Integer("09")ArgumentError: invalid value for Integer: "09" from (irb):4:in `Integer' from (irb):4 from :0 But it looks like .to_i doesn't have the same issues: irb(main):005:0> "04".to_i=> 4irb(main):006:0> "09".to_i=> 9 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151/"
]
} |
146,704 | Puzzled by the Lua 5.0 documentation references to things like _LOADED , LUA_PATH , _ALERT and so on (that I could not use in Lua 5.1), I discovered all of those have been removed and the functionality put elsewhere. Am I right in thinking that the only one global variable left in Lua 5.1 is _VERSION ? | I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are strings. Here's what I did in IRB to replicate the problem: irb(main):003:0> Integer("04")=> 4irb(main):004:0> Integer("09")ArgumentError: invalid value for Integer: "09" from (irb):4:in `Integer' from (irb):4 from :0 But it looks like .to_i doesn't have the same issues: irb(main):005:0> "04".to_i=> 4irb(main):006:0> "09".to_i=> 9 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12291/"
]
} |
146,715 | I want to create a class that, for example, extends HttpServlet? My compiler warns me that my class should have a serialVersionUID. If I know that this object will never be serialized, should I define it or add an annotation to suppress those warnings? What would you do and why? | I don't know Java best practices, but it occurs to me that if you are claiming that serialization will never happen, you could add a writeObject method which throws. Then suppress the warning, safe in the knowledge that it cannot possibly apply to you. Otherwise someone might in future serialize your object through the parent class, and end up with a default serialized form where: the form isn't compatible between different versions of your code. you've suppressed the warning that this is the case. Adding an ID sounds like a bodge, since what you really want to do is not serialize. Expecting callers not to serialize your object means that you expect them to "know" when their HttpServlet is of your class. That breach of polymorphism is on your head for having a Serializable object which must not be serialized, and the least you can do is make sure unwary callers know about it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11450/"
]
} |
146,730 | Lifehacker had a post a couple days ago asking people about the best mouse you've ever had and it appears some people have traded their mouse for a tablet. I'm curious if anyone here has traded their mouse in for a tablet? Does it work well for development? Looking for pros and cons from people who have tried it or are using it. Thanks. | I don't know Java best practices, but it occurs to me that if you are claiming that serialization will never happen, you could add a writeObject method which throws. Then suppress the warning, safe in the knowledge that it cannot possibly apply to you. Otherwise someone might in future serialize your object through the parent class, and end up with a default serialized form where: the form isn't compatible between different versions of your code. you've suppressed the warning that this is the case. Adding an ID sounds like a bodge, since what you really want to do is not serialize. Expecting callers not to serialize your object means that you expect them to "know" when their HttpServlet is of your class. That breach of polymorphism is on your head for having a Serializable object which must not be serialized, and the least you can do is make sure unwary callers know about it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/519/"
]
} |
146,737 | So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures? | PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The RFC for closures gives a good example: function replace_spaces ($text) { $replacement = function ($matches) { return str_replace ($matches[1], ' ', ' ').' '; }; return preg_replace_callback ('/( +) /', $replacement, $text);} This lets you define the replacement function locally inside replace_spaces() , so that it's not: 1) cluttering up the global namespace 2) making people three years down the line wonder why there's a function defined globally that's only used inside one other function It keeps things organized. Notice how the function itself has no name, it's simply defined and assigned as a reference to $replacement . But remember, you have to wait for PHP 5.3 :) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/146737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11252/"
]
} |
146,777 | Specifically, when you create an interface/implementor pair, and there is no overriding organizational concern (such as the interface should go in a different assembly ie, as recommended by the s# architecture) do you have a default way of organizing them in your namespace/naming scheme? This is obviously a more opinion based question but I think some people have thought about this more and we can all benefit from their conclusions. | The answer depends on your intentions. If you intend the consumer of your namespaces to use the interfaces over the concrete implementations, I would recommend having your interfaces in the top-level namespace with the implementations in a child namespace If the consumer is to use both, have them in the same namespace. If the interface is for predominantly specialized use, like creating new implementations, consider having them in a child namespace such as Design or ComponentModel. I'm sure there are other options as well, but as with most namespace issues, it comes down to the use-cases of the project, and the classes and interfaces it contains. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
} |
146,789 | This question is related to (but perhaps not quite the same as): Does Django have HTML helpers? My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example: I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective models.py ) class Person(models.Model): ...class Address(models.Model): contact = models.ForeignKey(Person) Now, whenever I look at a Person, I want to see all their Addresses. So suppose Persons/views.py has something likeso: def detail(request, person_id): person = get_object_or_404( Person, pk=person_id ) return render_to_response('persons/details.html', { 'title' : unicode(person), 'addresses': person.address_set.all() } ) And, I have a template, persons/details.html , with code, for example, like-so: {% extends "base.html" %}{% for address in addresses %}<b>{{ address.name }}</b> {{ address.type }} <br> {{ address.street_1 }}<br> {{ address.street_2 }}<br> {{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br> {{ address.country }} <hr>{{ endfor }} I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy! What I want is a persons/details.html with, for example, the following: {% extends "base.html" %}{% for address in addresses %} {% address.as_html4 %}{% endfor %} And if I want inline table, something likeso (I guess!): {% extends "base.html" %}<table><tr>{% for address in addresses %} <tr><td> {% address.as_html4 </td><td> %} </td></tr>{% endfor %}</table> The question is, then: Where is the best place to put the formatting? The logic? Django seem to have the following (plausible) options: Put the formatting in models.py Put the logic/formatting in views.py Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py) Create custom tags Help / insight much appreciated! | Sounds like an inclusion tag is what you're looking for. You could have a template and tag for each major variation and use the tag's arguments to customise the context for each template as required. Basic tag definition: @register.inclusion_tag('person/address.html')def display_address(address): return {'address': address} Use in templates (assuming the templatetag module containing it has already been {% load %} -ed): {% display_address address %} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212/"
]
} |
146,850 | Is the D language a credible alternative to Java and C++? What will it take to become a credible alternative? Should I bother learning it? Does it deserve evangelizing? The main reason I ask is that with the new C++ standard (c++0x) almost here, it's clear to me that the language has gone well past the point of no return with respect to anyone ever understanding it. I know that C/C++ will never die but at some point we need to move on. Even COBOL had its day and Java has in many respects undone C++. So what's next? Does D fill the bill? | What determines the success and popularity of a programming language for real-world software development is only partially related to the quality of the language itself. As a pure language, D arguably has many advantages over C++ and Java. At the very least it is a credible alternative as a pure language, all other things being equal. However, other things matter for software development - almost more than the language itself: portability (how many platforms does it run on), debugger support, IDE support, standard library quality, dynamic library support, bindings for common APIs, documentation, the developer community, momentum, and commercial support, just to name a few. In every one of those regards, D is hopelessly behind Java, C++, and C#. In fact, I'd argue it's even behind so-called "scripting" languages like Python, Perl, PHP, Ruby, and even JavaScript in these regards. To be blunt, you simply can't build a large-scale, cross-platform application using D. With an immature standard library, no support in any modern IDEs (there are plugins for both Visual Studio and Xamarin Studio/MonoDevelop), limited dynamic/shared library support, and few bindings to other languages, D is simply not an option today. If you like what you see of D, by all means, learn it - it shouldn't take long if you already know Java and C++. I don't think evangelism would be helpful - at this point if D is going to succeed, what it really needs is more people quietly using it and addressing its major shortcomings like standard library and IDE support. Finally, as for C++, while most agree the language is too complex, thousands of companies are successfully using C++ as part of a healthy mix of languages by allowing only a smaller, well-defined subset of the language. It's still hard to beat C++ when both raw performance and small memory usage are required. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/146850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14788/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.