source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
81,520 | How can you suppress the Terminated message that comes up after you kill aprocess in a bash script? I tried set +bm , but that doesn't work. I know another solution involves calling exec 2> /dev/null , but is thatreliable? How do I reset it back so that I can continue to see stderr? | In order to silence the message, you must be redirecting stderr at the time the message is generated . Because the kill command sends a signal and doesn't wait for the target process to respond, redirecting stderr of the kill command does you no good. The bash builtin wait was made specifically for this purpose. Here is very simple example that kills the most recent background command. ( Learn more about $! here. ) kill $!wait $! 2>/dev/null Because both kill and wait accept multiple pids, you can also do batch kills. Here is an example that kills all background processes (of the current process/script of course). kill $(jobs -rp)wait $(jobs -rp) 2>/dev/null I was led here from bash: silently kill background function process . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/81520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14437/"
]
} |
81,521 | I have settled a web synchronization between SQLSERVER 2005 as publisher and SQLEXPRESS as suscriber. Web synchro has to be launched manually through IE interface (menu tools/synchronize) and to be selected among available synchronizations. Everything is working fine except that I did not find a way to automate the synchro, which I still have to launch manually. Any idea? I have no idea if this synchro can be launched from SQLEXPRESS by running a specific T-SQL code (in this case my problem could be solved indirectly). | In order to silence the message, you must be redirecting stderr at the time the message is generated . Because the kill command sends a signal and doesn't wait for the target process to respond, redirecting stderr of the kill command does you no good. The bash builtin wait was made specifically for this purpose. Here is very simple example that kills the most recent background command. ( Learn more about $! here. ) kill $!wait $! 2>/dev/null Because both kill and wait accept multiple pids, you can also do batch kills. Here is an example that kills all background processes (of the current process/script of course). kill $(jobs -rp)wait $(jobs -rp) 2>/dev/null I was led here from bash: silently kill background function process . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/81521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11436/"
]
} |
81,552 | There doesn't seem to be a dictionary.AddRange() method. Does anyone know a better way to copy the items to another dictionary without using a foreach loop. I'm using the System.Collections.Generic.Dictionary. This is for .NET 2.0. | There's the Dictionary constructor that takes another Dictionary . You'll have to cast it IDictionary , but there is an Add() overload that takes KeyValuePair<TKey, TValue> . You're still using foreach, though. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13028/"
]
} |
81,597 | How can I find and delete unused references in my projects? I know you can easily remove the using statements in vs 2008, but this doesn't remove the actual reference in your projects. The referenced dll will still be copied in your bin/setup package. | *Note: see http://www.jetbrains.net/devnet/message/5244658 for another version of this answer. Reading through the posts, it looks like there is some confusion as to the original question. Let me take a stab at it. The original post is really asking the question: "How do I identify and remove references from one Visual Studio project to other projects/assemblies that are not in use?" The poster wants the assemblies to no longer appear as part of the build output. In this case, ReSharper can help you identify them, but you have to remove them yourself. To do this, open up the References inth Solution Browser, right mouse click on each referenced assembly, and pick "Find Dependent Code". See: http://www.jetbrains.com/resharper/features/navigation_search.html#Find_ReferencedDependent_Code You will either get: A list of the dependencies on that Reference in a browser window, or A dialog telling you "Code dependent on module XXXXXXX was not found.". If you get the the second result, you can then right mouse click the Reference, select Remove, and remove it from your project. While you have to to this "manually", i.e. one reference at a time, it will get the job done. If anyone has automated this in some manner I am interested in hearing how it was done. You can pretty much ignore the ones in the .Net Framework as they don't normally get copied to your build output (typically - although not necessarily true for Silverlight apps). Some posts seem to be answering the question: "How do I remove using clauses (C#) from a source code file that are not needed to resolve any references within that file". In this case, ReSharper does help in a couple ways: Identifies unused using clauses for you during on the fly error detection. They appear as Code Inspection Warnings - the code will appear greyed out (be default) in the file and ReSharper will provide a Hint to remove it: http://www.jetbrains.com/resharper/features/code_analysis.html#On-the-fly_Error_Detection Allows you to automatically remove them as part of the Code Cleanup Process: http://www.jetbrains.com/resharper/features/code_formatting.html#Optimizing_Namespace_Import_Directives Finally, realize that ReSharper does static code analysis on your solution. So, if you have a dynamic reference to the assembly - say through reflection or an assembly that is dynamically loaded at runtime and accessed through an interface - it won't pick it up. There is no substitute for understanding your code base and the project dependencies as you work on your project. I do find the ReSharper features very useful. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/81597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
]
} |
81,627 | I am using Qt Dialogs in one of my application.I need to hide/delete the help button. But i am not able to locate where exactly I get the handle to his help button. Not sure if its a particular flag on the Qt window. | By default the Qt::WindowContextHelpButtonHint flag is added to dialogs.You can control this with the WindowFlags parameter to the dialog constructor. For instance you can specify only the TitleHint and SystemMenu flags by doing: QDialog *d = new QDialog(0, Qt::WindowSystemMenuHint | Qt::WindowTitleHint);d->exec(); If you add the Qt::WindowContextHelpButtonHint flag you will get the help button back. In PyQt you can do: from PyQt4 import QtGui, QtCoreapp = QtGui.QApplication([])d = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)d.exec_() More details on window flags can be found on the WindowType enum in the Qt documentation. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/81627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11212/"
]
} |
81,656 | For many questions the answer seems to be found in "the standard". However, where do we find that? Preferably online. Googling can sometimes feel futile, again especially for the C standards, since they are drowned in the flood of discussions on programming forums. To get this started, since these are the ones I am searching for right now, where are there good online resources for: C89 C99 C11 C++98 C++03 C++11 C++14 C++17 | PDF versions of the standard As of 1st September 2014 March 2022, the best locations by price for the official C and C++ standards documents in PDF seem to be: C++20 β ISO/IEC 14882:2020: 212 CAD (about $165 US) from csagroup.org C++17 β ISO/IEC 14882:2017: $90 NZD (about $65 US) from Standards New Zealand C++14 β ISO/IEC 14882:2014: $90 NZD (about $65 US) from Standards New Zealand C++11 β ISO/IEC 14882-2011: $60 from ansi.org or $60 from Techstreet C++03 β INCITS/ISO/IEC 14882:2003: $30 from ansi.org C++98 β ISO/IEC 14882:1998: $95 NZD (about $65 US) from Standards New Zealand C17/C18 β INCITS/ISO/IEC 9899:2018: $116 from INCITS/ANSI / N2176 / c17_updated_proposed_fdis.pdf draft from November 2017 (Link broken, see Wayback Machine N2176 ) C11 β ISO/IEC 9899:2011: $60 from ansi.org / WG14 draft version N1570 C99 β INCITS/ISO/IEC 9899-1999(R2005): $60 from ansi.org / WG14 draft version N1256 C90 β ISO/IEC 9899:1990: $90 NZD (about $65 USD) from Standards New Zealand Non-PDF electronic versions of the standard Warning: most copies of standard drafts are published in PDF format, and errors may have been introduced if the text/HTML was transcribed or automatically generated from the PDF. C89 β Draft version in ANSI text format: ( https://web.archive.org/web/20161223125339/http://flash-gordon.me.uk/ansi.c.txt ) C89 β Draft version as HTML document: ( http://port70.net/~nsz/c/c89/c89-draft.html ) C90 TC1; ISO/IEC 9899 TCOR1, single-page HTML document: ( http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc1.htm ) C90 TC2; ISO/IEC 9899 TCOR2, single-page HTML document: ( http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc2.htm ) C99 β Draft version (N1256) as HTML document: ( http://port70.net/~nsz/c/c99/n1256.html ) C11 β Draft version (N1570) as HTML document: ( http://port70.net/~nsz/c/c11/n1570.html ) C++11 β Working draft (N3337) as plain text document: ( http://port70.net/~nsz/c/c%2B%2B/c%2B%2B11_n3337.txt ) (The site hosting the plain text version of the C++11 working draft also has some C++14 drafts in this format. But none of them are copies of the final working draft, N4140.) Print versions of the standard Print copies of the standards are available from national standards bodies and ISO but are very expensive. If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of Herb Schildt 's book The Annotated ANSI Standard at Amazon , which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors). The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute): C++03 Standard on Amazon C99 Standard on Amazon Standards committee draft versions (free) The working drafts for future standards are often available from the committee websites: C++ committee website C committee website If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet: For C: ANSI X3.159-198 (C89):I cannot find a PDF of C89, but it is almost the same as C90. The only major differences are in the boilerplate and section numbering, although there are some slight textual differences ISO/IEC 9899:1990 (C90):(Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. There is at least one textual difference in section 6.5.7 (previously 3.5.7), where "a list" became "a brace-enclosed list" . Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as "ANSI/ISO: 9899/99" although this isn't the right name of the later made standard of it, the right name is "ISO/IEC 9899:1990") TC1 for C90: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n423.pdf There isn't a PDF link for TC2 on the WG14 website , sadly. ISO/IEC 9899:1999 (C99 incorporating all three Technical Corrigenda): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf An earlier version of C99 incorporating only TC1 and TC2: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf Working draft for the original (i.e. pre-corrigenda) C99: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n843.htm (HTML) and http://www.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.pdf (PDF).Note that there were two later working drafts: N869 and N878, but they seem to have been removed from the WG14 website, so this is the latest one available. List of changes between C89/C90 and C99: http://port70.net/~nsz/c/c89/c9x_changes.html TC1 for C99 (only the TC, not the standard incorporating it): http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899tc1/n32071.PDF TC2 for C99 (only the TC, not the standard incorporating it): http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899-1999_cor_2-2004.pdf ISO/IEC 9899:2011 (C11): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf For information on the differences between N1570 and the final, published version of C11, see Latest changes in C11 and https://groups.google.com/g/comp.std.c/c/v5hsWOu5vSw ISO/IEC 9899:2011/Cor 1:2012 (C11's only technical corrigendum): This can be viewed at https://www.iso.org/obp/ui/#iso:std:iso-iec:9899:ed-3:v1:cor:1:v1:en but cannot be downloaded. It is the actual corrigendum, not a draft. ISO/IEC 9899:2018 (C17/C18): https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf (N2176) C2x work-in-progress - latest working draft as of 7th August 2022 (N3047): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n3047.pdf For C++: ISO/IEC 14882:1998 (C++98): http://www.lirmm.fr/~ducour/Doc-objets/ISO+IEC+14882-1998.pdf ISO/IEC 14882:2003 (C++03): https://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf ISO/IEC 14882:2011 (C++11): http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf ISO/IEC 14882:2014 (C++14): https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true ISO/IEC 14882:2017 (C++17): http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf ISO/IEC 14882:2020 (C++20): https://isocpp.org/files/papers/N4860.pdf ISO/IEC 14882:2023 (C++23 work-in-progress. Working draft dated March 17 2022): https://open-std.org/JTC1/SC22/WG21/docs/papers/2022/n4910.pdf Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them. Even though the draft versions might be very close to the final ratified versions of the standards, some of this post's editors would strongly advise you to get a copy of the actual documents β especially if you're planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash. It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for "INCITS/ISO/IEC" instead of "ISO/IEC" when looking for a standard is the key. By doing so, one of this post's editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for "INCITS/ISO/IEC 9899:2011" instead of "ISO/IEC 9899:2011" on webstore.ansi.org you will find the reasonably priced PDF version. The site https://wg21.link/ provides short-URL links to the C++ current working draft and draft standards, and committee papers: https://wg21.link/std11 - C++11 https://wg21.link/std14 - C++14 https://wg21.link/std17 - C++17 https://wg21.link/std20 - C++20 https://wg21.link/std - current working draft (as of May 2022 still points to the 2021 version) The current draft of the standard is maintained as LaTeX sources on Github . These sources can be converted to HTML using cxxdraft-htmlgen . The following sites maintain HTML pages so generated: Tim Song - Current working draft - C++11 - C++14 - C++17 - C++20 Eelis - Current working draft Tim Song also maintains generated HTML and PDF versions of the Networking TS and Ranges TS. POSIX extensions to the C standard The POSIX standard (IEEE 1003.1) requires a compliant operating system to include a C compiler. This compiler must in turn be compliant with the C standard, and must also support various extensions defined in the "System Interfaces" section of POSIX (such as the off_t data type, the <aio.h> header, the clock_gettime() function and the _POSIX_C_SOURCE macro.) So if you've tried to look up a particular function, been informed "This function is part of POSIX, not the C standard", and wondered why an operating system standard was mandating compiler features and language extensions... now you know! POSIX.1-2001: The System Interfaces section can be downloaded as a separate document from https://mirror.math.princeton.edu/pub/oldlinux/download/c951.pdf . Section 1.7 states that the relevant version of the C standard is C99. The "Shell and Utilities" section ( https://mirror.math.princeton.edu/pub/oldlinux/download/c952.pdf ) mandates not only that a C99-compliant compiler should exist, but that it should be invokable from the command line under the name "c99". One way in which this can be implemented is to place a shell script called "c99" in /usr/bin, which calls gcc with the -std=c99 option added to the list of command-line parameters, and blocks any competing standards from being specified. POSIX.1-2001 had two technical corrigenda, one dated 2002 and one dated 2004. I don't think they're incorporated into the documents as linked above. There's an online HTML version incorporating the corrigenda at https://pubs.opengroup.org/onlinepubs/009695399/ - but I should add that I've had some trouble with the search box and so using Google to search the site is probably your best bet. There is a paywalled link to download the first corrigendum at https://standards.ieee.org/standard/1003_1-2001-Cor1-2002.html . There is also a paywalled link for the second at https://standards.ieee.org/standard/1003_1-2001-Cor2-2004.html There is a draft version of POSIX.1-2008 at http://www.open-std.org/jtc1/sc22/open/n4217.pdf . POSIX.1-2008 also had two technical corrigenda, the latter of the two being dated 2016. There is an online HTML version of the standard incorporating the corrigenda at https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/ - though, again, I have had situations where the site's own search box wasn't good for finding information. There is an online HTML version of POSIX.1-2017 at https://pubs.opengroup.org/onlinepubs/9699919799/ - though, again, I recommend using Google instead of that site's searchbox. According to the Open Group website "IEEE 1003.1-2017 ... is a revision to the 1003.1-2008 standard to rollup the standard including its two technical corrigenda (as-is)". Linux manpages describe it as "technically identical" to POSIX.1-2008 with Technical Corrigenda 1 and 2 applied. This is therefore not a major revision and does not change the value of the _POSIX_C_SOURCE macro. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/81656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15514/"
]
} |
81,674 | I am looking for an easy way to check if an object in C# is serializable. As we know you make an object serializable by either implementing the ISerializable interface or by placing the [Serializable] at the top of the class. What I am looking for is a quick way to check this without having to reflect the class to get it's attributes. The interface would be quick using an is statement. Using @Flard's suggestion this is the code that I have come up with, scream is there is a better way. private static bool IsSerializable(T obj){ return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute))));} Or even better just get the type of the object and then use the IsSerializable property on the type: typeof(T).IsSerializable Remember though this this seems to only just the class that we are dealing with if the class contains other classes you probably want to check them all or try and serialize and wait for errors as @pb pointed out. | You have a lovely property on the Type class called IsSerializable . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/81674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
]
} |
81,730 | In .NET, after this code, what mechanism stops the Thread object from being garbage collected? new Thread(Foo).Start();GC.Collect(); Yes, it's safe to assume something has a reference to the thread, I was just wandering what exactly. For some reason Reflector doesn't show me System.Threading , so I can't dig it myself (I know MS released the source code for the .NET framework, I just don't have it handy). | The runtime keeps a reference to the thread as long as it is running. The GC wont collect it as long as anyone still keeps that reference. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
]
} |
81,732 | I've got a virtual machine running on a server that I can't stop or reboot - I can't log onto it anymore and I can't stop it using the VMware server console. There are other VM's running so rebooting the host is out of the question. Is there any other way of forcing one machine to stop? | If you are using Windows, the virtual machine should have it's own process that is visible in task manager. Use sysinternals Process Explorer to find the right one and then kill it from there. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4271/"
]
} |
81,784 | How do you usually go about separating your codebase and associated unit tests ? I know people who create a separate project for unit tests, which I personally find confusing and difficult to maintain. On the other hand, if you mix up code and its tests in a single project, you end up with binaries related to your unit test framework (be it NUnit, MbUnit or whatever else) and your own binaries side by side. This is fine for debugging, but once I build a release version , I really do not want my code to reference the unit testing framework any more. One solution I found is to enclose all your unit tests within #if DEBUG -- #endif directives: when no code references an unit testing assembly, the compiler is clever enough to omit the reference in the compiled code. Are there any other (possibly more comfortable) options to achieve a similar goal? | I definitely advocate separating your tests out to a separate project. It's the only way to go in my opinion. Yes, as Gary says, it also forces you to test behavior through public methods rather than playing about with the innards of your classes | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
]
} |
81,786 | I'd like to add a method AddDefaultNamespace() to the String class in Java so that I can type "myString".AddDefaultNamespace() instead of DEFAULTNAMESPACE + "myString" , to obtain something like "MyDefaultNameSpace.myString" . I don't want to add another derived class either ( PrefixedString for example). Maybe the approach is not good for you but I personally hate using + . But, anyway, is it possible to add new methods to the String class in Java? Thanks and regards. | String is a final class which means it cannot be extended to work on your own implementation. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/81786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15546/"
]
} |
81,788 | I couldn't find a decent ThreadPool implementation for Ruby, so I wrote mine (based partly on code from here: http://web.archive.org/web/20081204101031/http://snippets.dzone.com:80/posts/show/3276 , but changed to wait/signal and other implementation for ThreadPool shutdown. However after some time of running (having 100 threads and handling about 1300 tasks), it dies with deadlock on line 25 - it waits for a new job there. Any ideas, why it might happen? require 'thread'begin require 'fastthread'rescue LoadError $stderr.puts "Using the ruby-core thread implementation"end class ThreadPool class Worker def initialize(callback) @mutex = Mutex.new @cv = ConditionVariable.new @callback = callback @mutex.synchronize {@running = true} @thread = Thread.new do while @mutex.synchronize {@running} block = get_block if block block.call reset_block # Signal the ThreadPool that this worker is ready for another job @callback.signal else # Wait for a new job @mutex.synchronize {@cv.wait(@mutex)} # <=== Is this line 25? end end end end def name @thread.inspect end def get_block @mutex.synchronize {@block} end def set_block(block) @mutex.synchronize do raise RuntimeError, "Thread already busy." if @block @block = block # Signal the thread in this class, that there's a job to be done @cv.signal end end def reset_block @mutex.synchronize {@block = nil} end def busy? @mutex.synchronize {[email protected]?} end def stop @mutex.synchronize {@running = false} # Signal the thread not to wait for a new job @cv.signal @thread.join end end attr_accessor :max_size def initialize(max_size = 10) @max_size = max_size @workers = [] @mutex = Mutex.new @cv = ConditionVariable.new end def size @mutex.synchronize {@workers.size} end def busy? @mutex.synchronize {@workers.any? {|w| w.busy?}} end def shutdown @mutex.synchronize {@workers.each {|w| w.stop}} end alias :join :shutdown def process(block=nil,&blk) block = blk if block_given? while true @mutex.synchronize do worker = get_worker if worker return worker.set_block(block) else # Wait for a free worker @cv.wait(@mutex) end end end end # Used by workers to report ready status def signal @cv.signal end private def get_worker free_worker || create_worker end def free_worker @workers.each {|w| return w unless w.busy?}; nil end def create_worker return nil if @workers.size >= @max_size worker = Worker.new(self) @workers << worker worker endend | Ok, so the main problem with the implementation is: how to make sure no signal is lost and avoid dead locks ? In my experience, this is REALLY hard to achieve with condition variables and mutex, but easy with semaphores. It so happens that ruby implement an object called Queue (or SizedQueue) that should solve the problem. Here is my suggested implementation: require 'thread'begin require 'fasttread'rescue LoadError $stderr.puts "Using the ruby-core thread implementation"endclass ThreadPool class Worker def initialize(thread_queue) @mutex = Mutex.new @cv = ConditionVariable.new @queue = thread_queue @running = true @thread = Thread.new do @mutex.synchronize do while @running @cv.wait(@mutex) block = get_block if block @mutex.unlock block.call @mutex.lock reset_block end @queue << self end end end end def name @thread.inspect end def get_block @block end def set_block(block) @mutex.synchronize do raise RuntimeError, "Thread already busy." if @block @block = block # Signal the thread in this class, that there's a job to be done @cv.signal end end def reset_block @block = nil end def busy? @mutex.synchronize { [email protected]? } end def stop @mutex.synchronize do @running = false @cv.signal end @thread.join end end attr_accessor :max_size def initialize(max_size = 10) @max_size = max_size @queue = Queue.new @workers = [] end def size @workers.size end def busy? @queue.size < @workers.size end def shutdown @workers.each { |w| w.stop } @workers = [] end alias :join :shutdown def process(block=nil,&blk) block = blk if block_given? worker = get_worker worker.set_block(block) end private def get_worker if [email protected]? or @workers.size == @max_size return @queue.pop else worker = Worker.new(@queue) @workers << worker worker end endend And here is a simple test code: tp = ThreadPool.new 500(1..1000).each { |i| tp.process { (2..10).inject(1) { |memo,val| sleep(0.1); memo*val }; print "Computation #{i} done. Nb of tasks: #{tp.size}\n" } }tp.shutdown | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12695/"
]
} |
81,830 | Grails vs Rails. Which has better support? And which one is a better choice to develop medium size apps with? Most importantly which one has more plug-ins? | One other thing worth mentioning: the design philosophy of both framework is somewhat different when it comes to the model. Grails is more "domain-oriented" while Rails is more "database-oriented". In Rails, you essentially start by defining your tables (with field names and their specifics). Then ActiveRecord will map them to Ruby classes or models. In Grails, it's the reverse: you start by defining your models (Groovy classes) and when you hit run, GORM (Grails ActiveRecord equivalent) will create the related database and tables (or update them). Which may also be why you don't have the concept of 'migrations' in Grails (although I think it will come in some future release). I don't know if one is better than the other. I guess it depends on your context. This being said, I'm still myself wondering which one to choose. As Tom was saying, if you're dependent on Java you can still go for JRuby - so Java reuse shouldn't be your sole criterion. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15476/"
]
} |
81,870 | For example: int a = 12;cout << typeof(a) << endl; Expected output: int | C++11 update to a very old question: Print variable type in C++. The accepted (and good) answer is to use typeid(a).name() , where a is a variable name. Now in C++11 we have decltype(x) , which can turn an expression into a type. And decltype() comes with its own set of very interesting rules. For example decltype(a) and decltype((a)) will generally be different types (and for good and understandable reasons once those reasons are exposed). Will our trusty typeid(a).name() help us explore this brave new world? No. But the tool that will is not that complicated. And it is that tool which I am using as an answer to this question. I will compare and contrast this new tool to typeid(a).name() . And this new tool is actually built on top of typeid(a).name() . The fundamental issue: typeid(a).name() throws away cv-qualifiers, references, and lvalue/rvalue-ness. For example: const int ci = 0;std::cout << typeid(ci).name() << '\n'; For me outputs: i and I'm guessing on MSVC outputs: int I.e. the const is gone. This is not a QOI (Quality Of Implementation) issue. The standard mandates this behavior. What I'm recommending below is: template <typename T> std::string type_name(); which would be used like this: const int ci = 0;std::cout << type_name<decltype(ci)>() << '\n'; and for me outputs: int const <disclaimer> I have not tested this on MSVC. </disclaimer> But I welcome feedback from those who do. The C++11 Solution I am using __cxa_demangle for non-MSVC platforms as recommend by ipapadop in his answer to demangle types. But on MSVC I'm trusting typeid to demangle names (untested). And this core is wrapped around some simple testing that detects, restores and reports cv-qualifiers and references to the input type. #include <type_traits>#include <typeinfo>#ifndef _MSC_VER# include <cxxabi.h>#endif#include <memory>#include <string>#include <cstdlib>template <class T>std::stringtype_name(){ typedef typename std::remove_reference<T>::type TR; std::unique_ptr<char, void(*)(void*)> own (#ifndef _MSC_VER abi::__cxa_demangle(typeid(TR).name(), nullptr, nullptr, nullptr),#else nullptr,#endif std::free ); std::string r = own != nullptr ? own.get() : typeid(TR).name(); if (std::is_const<TR>::value) r += " const"; if (std::is_volatile<TR>::value) r += " volatile"; if (std::is_lvalue_reference<T>::value) r += "&"; else if (std::is_rvalue_reference<T>::value) r += "&&"; return r;} The Results With this solution I can do this: int& foo_lref();int&& foo_rref();int foo_value();intmain(){ int i = 0; const int ci = 0; std::cout << "decltype(i) is " << type_name<decltype(i)>() << '\n'; std::cout << "decltype((i)) is " << type_name<decltype((i))>() << '\n'; std::cout << "decltype(ci) is " << type_name<decltype(ci)>() << '\n'; std::cout << "decltype((ci)) is " << type_name<decltype((ci))>() << '\n'; std::cout << "decltype(static_cast<int&>(i)) is " << type_name<decltype(static_cast<int&>(i))>() << '\n'; std::cout << "decltype(static_cast<int&&>(i)) is " << type_name<decltype(static_cast<int&&>(i))>() << '\n'; std::cout << "decltype(static_cast<int>(i)) is " << type_name<decltype(static_cast<int>(i))>() << '\n'; std::cout << "decltype(foo_lref()) is " << type_name<decltype(foo_lref())>() << '\n'; std::cout << "decltype(foo_rref()) is " << type_name<decltype(foo_rref())>() << '\n'; std::cout << "decltype(foo_value()) is " << type_name<decltype(foo_value())>() << '\n';} and the output is: decltype(i) is intdecltype((i)) is int&decltype(ci) is int constdecltype((ci)) is int const&decltype(static_cast<int&>(i)) is int&decltype(static_cast<int&&>(i)) is int&&decltype(static_cast<int>(i)) is intdecltype(foo_lref()) is int&decltype(foo_rref()) is int&&decltype(foo_value()) is int Note (for example) the difference between decltype(i) and decltype((i)) . The former is the type of the declaration of i . The latter is the "type" of the expression i . (expressions never have reference type, but as a convention decltype represents lvalue expressions with lvalue references). Thus this tool is an excellent vehicle just to learn about decltype , in addition to exploring and debugging your own code. In contrast, if I were to build this just on typeid(a).name() , without adding back lost cv-qualifiers or references, the output would be: decltype(i) is intdecltype((i)) is intdecltype(ci) is intdecltype((ci)) is intdecltype(static_cast<int&>(i)) is intdecltype(static_cast<int&&>(i)) is intdecltype(static_cast<int>(i)) is intdecltype(foo_lref()) is intdecltype(foo_rref()) is intdecltype(foo_value()) is int I.e. Every reference and cv-qualifier is stripped off. C++14 Update Just when you think you've got a solution to a problem nailed, someone always comes out of nowhere and shows you a much better way. :-) This answer from Jamboree shows how to get the type name in C++14 at compile time. It is a brilliant solution for a couple reasons: It's at compile time! You get the compiler itself to do the job instead of a library (even a std::lib). This means more accurate results for the latest language features (like lambdas). Jamboree's answer doesn't quite lay everything out for VS, and I'm tweaking his code a little bit. But since this answer gets a lot of views, take some time to go over there and upvote his answer, without which, this update would never have happened. #include <cstddef>#include <stdexcept>#include <cstring>#include <ostream>#ifndef _MSC_VER# if __cplusplus < 201103# define CONSTEXPR11_TN# define CONSTEXPR14_TN# define NOEXCEPT_TN# elif __cplusplus < 201402# define CONSTEXPR11_TN constexpr# define CONSTEXPR14_TN# define NOEXCEPT_TN noexcept# else# define CONSTEXPR11_TN constexpr# define CONSTEXPR14_TN constexpr# define NOEXCEPT_TN noexcept# endif#else // _MSC_VER# if _MSC_VER < 1900# define CONSTEXPR11_TN# define CONSTEXPR14_TN# define NOEXCEPT_TN# elif _MSC_VER < 2000# define CONSTEXPR11_TN constexpr# define CONSTEXPR14_TN# define NOEXCEPT_TN noexcept# else# define CONSTEXPR11_TN constexpr# define CONSTEXPR14_TN constexpr# define NOEXCEPT_TN noexcept# endif#endif // _MSC_VERclass static_string{ const char* const p_; const std::size_t sz_;public: typedef const char* const_iterator; template <std::size_t N> CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN : p_(a) , sz_(N-1) {} CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN : p_(p) , sz_(N) {} CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;} CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;} CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;} CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN {return p_ + sz_;} CONSTEXPR11_TN char operator[](std::size_t n) const { return n < sz_ ? p_[n] : throw std::out_of_range("static_string"); }};inlinestd::ostream&operator<<(std::ostream& os, static_string const& s){ return os.write(s.data(), s.size());}template <class T>CONSTEXPR14_TNstatic_stringtype_name(){#ifdef __clang__ static_string p = __PRETTY_FUNCTION__; return static_string(p.data() + 31, p.size() - 31 - 1);#elif defined(__GNUC__) static_string p = __PRETTY_FUNCTION__;# if __cplusplus < 201402 return static_string(p.data() + 36, p.size() - 36 - 1);# else return static_string(p.data() + 46, p.size() - 46 - 1);# endif#elif defined(_MSC_VER) static_string p = __FUNCSIG__; return static_string(p.data() + 38, p.size() - 38 - 7);#endif} This code will auto-backoff on the constexpr if you're still stuck in ancient C++11. And if you're painting on the cave wall with C++98/03, the noexcept is sacrificed as well. C++17 Update In the comments below Lyberta points out that the new std::string_view can replace static_string : template <class T>constexprstd::string_viewtype_name(){ using namespace std;#ifdef __clang__ string_view p = __PRETTY_FUNCTION__; return string_view(p.data() + 34, p.size() - 34 - 1);#elif defined(__GNUC__) string_view p = __PRETTY_FUNCTION__;# if __cplusplus < 201402 return string_view(p.data() + 36, p.size() - 36 - 1);# else return string_view(p.data() + 49, p.find(';', 49) - 49);# endif#elif defined(_MSC_VER) string_view p = __FUNCSIG__; return string_view(p.data() + 84, p.size() - 84 - 7);#endif} I've updated the constants for VS thanks to the very nice detective work by Jive Dadson in the comments below. Update: Be sure to check out this rewrite or this rewrite below which eliminate the unreadable magic numbers in my latest formulation. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/81870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6508/"
]
} |
81,896 | I have a script that works fine on my test server (using IIS6). The script processes an ajax request and sends a response with the following line: header( 'application/javascript' ); But on my live server, this line crashes the page and causes a 500 error. Do I need to allow PHP to send different MIME types in IIS7? If so, how do I do this? I can't find any way on the interface. | The header is incorrect, try this instead: header('Content-Type: application/javascript'); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/81896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15567/"
]
} |
81,902 | I need a Java way to find a running Win process from which I know to name of the executable. I want to look whether it is running right now and I need a way to kill the process if I found it. | private static final String TASKLIST = "tasklist";private static final String KILL = "taskkill /F /IM ";public static boolean isProcessRunning(String serviceName) throws Exception { Process p = Runtime.getRuntime().exec(TASKLIST); BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); if (line.contains(serviceName)) { return true; } } return false;}public static void killProcess(String serviceName) throws Exception { Runtime.getRuntime().exec(KILL + serviceName); } EXAMPLE: public static void main(String args[]) throws Exception { String processName = "WINWORD.EXE"; //System.out.print(isProcessRunning(processName)); if (isProcessRunning(processName)) { killProcess(processName); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11705/"
]
} |
81,905 | I have a table in my database the records start and stop times for a specific task. Here is a sample of the data: Start Stop9/15/2008 5:59:46 PM 9/15/2008 6:26:28 PM9/15/2008 6:30:45 PM 9/15/2008 6:40:49 PM9/16/2008 8:30:45 PM 9/15/2008 9:20:29 PM9/16/2008 12:30:45 PM 12/31/9999 12:00:00 AM I would like to write a script that totals up the elapsed minutes for these time frames, and wherever there is a 12/31/9999 date, I want it to use the current date and time, as this is still in progress. How would I do this using Transact-SQL? | SELECT SUM( CASE WHEN Stop = '31 dec 9999' THEN DateDiff(mi, Start, Stop) ELSE DateDiff(mi, Start, GetDate()) END ) AS TotalMinutes FROM task However, a better solution would be to make the Stop field nullable, and make it null when the task is still running. That way, you could do this: SELECT SUM( DateDiff( mi, Start, IsNull(Stop, GetDate() ) ) AS TotalMinutes FROM task | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
]
} |
81,934 | I need a way to easily export and then import data in a MySQL table from a remote server to my home server. I don't have direct access to the server, and no utilities such as phpMyAdmin are installed. I do, however, have the ability to put PHP scripts on the server. How do I get at the data? I ask this question purely to record my way to do it | You could use SQL for this: $file = 'backups/mytable.sql';$result = mysql_query("SELECT * INTO OUTFILE '$file' FROM `##table##`"); Then just point a browser or FTP client at the directory/file (backups/mytable.sql). This is also a nice way to do incremental backups, given the filename a timestamp for example. To get it back in to your DataBase from that file you can use: $file = 'backups/mytable.sql';$result = mysql_query("LOAD DATA INFILE '$file' INTO TABLE `##table##`"); The other option is to use PHP to invoke a system command on the server and run 'mysqldump': $file = 'backups/mytable.sql';system("mysqldump --opt -h ##databaseserver## -u ##username## -p ##password## ##database | gzip > ".$file); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
]
} |
81,991 | Every time a user posts something containing < or > in a page in my web application, I get this exception thrown. I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this. Trapping the exception and showing An error has occurred please go back and re-type your entire form again, but this time please do not use < doesn't seem professional enough to me. Disabling post validation ( validateRequest="false" ) will definitely avoid this error, but it will leave the page vulnerable to a number of attacks. Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded.So the .Text property of my text-box will be something & lt; html & gt; Is there a way I can do this from a handler? | I think you are attacking it from the wrong angle by trying to encode all posted data. Note that a " < " could also come from other outside sources, like a database field, a configuration, a file, a feed and so on. Furthermore, " < " is not inherently dangerous. It's only dangerous in a specific context: when writing strings that haven't been encoded to HTML output (because of XSS). In other contexts different sub-strings are dangerous, for example, if you write an user-provided URL into a link, the sub-string " javascript: " may be dangerous. The single quote character on the other hand is dangerous when interpolating strings in SQL queries, but perfectly safe if it is a part of a name submitted from a form or read from a database field. The bottom line is: you can't filter random input for dangerous characters, because any character may be dangerous under the right circumstances. You should encode at the point where some specific characters may become dangerous because they cross into a different sub-language where they have special meaning. When you write a string to HTML, you should encode characters that have special meaning in HTML, using Server.HtmlEncode. If you pass a string to a dynamic SQL statement, you should encode different characters (or better, let the framework do it for you by using prepared statements or the like).. When you are sure you HTML-encode everywhere you pass strings to HTML, then set ValidateRequest="false" in the <%@ Page ... %> directive in your .aspx file(s). In .NET 4 you may need to do a little more. Sometimes it's necessary to also add <httpRuntime requestValidationMode="2.0" /> to web.config ( reference ). | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/81991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
]
} |
82,058 | Given the following JSON Date representation: "\/Date(1221644506800-0700)\/" How do you deserialize this into it's JavaScript Date-type form? I've tried using MS AJAX JavaScrioptSerializer as shown below: Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/") However, all I get back is the literal string date. | Provided you know the string is definitely a date I prefer to do this : new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10)) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9275/"
]
} |
82,064 | I have a version number of the following form: version.release.modification where version, release and modification are either a set of digits or the '*' wildcard character. Additionally, any of these numbers (and any preceding .) may be missing. So the following are valid and parse as: 1.23.456 = version 1, release 23, modification 4561.23 = version 1, release 23, any modification1.23.* = version 1, release 23, any modification1.* = version 1, any release, any modification1 = version 1, any release, any modification* = any version, any release, any modification But these are not valid: *.12*123.112*12.*.34 Can anyone provide me a not-too-complex regex to validate and retrieve the release, version and modification numbers? | I'd express the format as: "1-3 dot-separated components, each numeric except that the last one may be *" As a regexp, that's: ^(\d+\.)?(\d+\.)?(\*|\d+)$ [Edit to add: this solution is a concise way to validate, but it has been pointed out that extracting the values requires extra work. It's a matter of taste whether to deal with this by complicating the regexp, or by processing the matched groups. In my solution, the groups capture the "." characters. This can be dealt with using non-capturing groups as in ajborley's answer. Also, the rightmost group will capture the last component, even if there are fewer than three components, and so for example a two-component input results in the first and last groups capturing and the middle one undefined. I think this can be dealt with by non-greedy groups where supported. Perl code to deal with both issues after the regexp could be something like this: @version = ();@groups = ($1, $2, $3);foreach (@groups) { next if !defined; s/\.//; push @version, $_;}($major, $minor, $mod) = (@version, "*", "*"); Which isn't really any shorter than splitting on "." ] | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/82064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7271/"
]
} |
82,109 | I am using Java 1.4 with Log4J. Some of my code involves serializing and deserializing value objects (POJOs). Each of my POJOs declares a logger with private final Logger log = Logger.getLogger(getClass()); The serializer complains of org.apache.log4j.Logger not being Serializable. Should I use private final transient Logger log = Logger.getLogger(getClass()); instead? | How about using a static logger? Or do you need a different logger reference for each instance of the class? Static fields are not serialized by default; you can explicitly declare fields to serialize with a private, static, final array of ObjectStreamField named serialPersistentFields . See Oracle documentation Added content: As you use getLogger(getClass()) , you will use the same logger in each instance. If you want to use separate logger for each instance you have to differentiate on the name of the logger in the getLogger() -method. e.g. getLogger(getClass().getName() + hashCode()). You should then use the transient attribute to make sure that the logger is not serialized. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
]
} |
82,128 | Our build server is taking too long to build one of our C++ projects. It uses Visual Studio 2008 , running devenv.com MyApp.sln /Build -- see devenv command-line switches (although that's for a newer version of VS). Is there a way to get devenv.com to log the time taken to build each project in the solution, so that I know where to focus my efforts? Improved hardware is not an option in this case. I've tried setting the output verbosity (under menu Tools β Options β Projects and Solutions β Build and Run β MSBuild project build output verbosity ). This doesn't seem to have any effect in the IDE. When running MSBuild from the command line (and, for Visual Studio 2008, it needs to be MSBuild v3.5), it displays the total time elapsed at the end, but not in the IDE. I really wanted a time-taken report for each project in the solution, so that I could figure out where the build process was taking its time. | Menu Tools β Options β Projects and Solutions β VC++ Project Settings β Build Timing should work. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/82128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
]
} |
82,256 | I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to. The trouble is, this contrived example doesn't work: sudo ls -hal /root/ > /root/test.out I just receive the response: -bash: /root/test.out: Permission denied How can I get this to work? | Your command does not work because the redirection is performed by your shell which does not have the permission to write to /root/test.out . The redirection of the output is not performed by sudo. There are multiple solutions: Run a shell with sudo and give the command to it by using the -c option: sudo sh -c 'ls -hal /root/ > /root/test.out' Create a script with your commands and run that script with sudo: #!/bin/shls -hal /root/ > /root/test.out Run sudo ls.sh . See Steve Bennett's answer if you don't want to create a temporary file. Launch a shell with sudo -s then run your commands: [nobody@so]$ sudo -s[root@so]# ls -hal /root/ > /root/test.out[root@so]# ^D[nobody@so]$ Use sudo tee (if you have to escape a lot when using the -c option): sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null The redirect to /dev/null is needed to stop tee from outputting to the screen. To append instead of overwriting the output file ( >> ), use tee -a or tee --append (the last one is specific to GNU coreutils ). Thanks go to Jd , Adam J. Forster and Johnathan for the second, third and fourth solutions. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/82256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6910/"
]
} |
82,259 | Ever wanted to have an HTML drag and drop sortable table in which you could sort both rows and columns? I know it's something I'd die for. There's a lot of sortable lists going around but finding a sortable table seems to be impossible to find. I know that you can get pretty close with the tools that script.aculo.us provides but I ran into some cross-browser issues with them. | I've used jQuery UI's sortable plugin with good results. Markup similar to this: <table id="myTable"><thead><tr><th>ID</th><th>Name</th><th>Details</th></tr></thead><tbody class="sort"><tr id="1"><td>1</td><td>Name1</td><td>Details1</td></tr><tr id="2"><td>2</td><td>Name1</td><td>Details2</td></tr><tr id="3"><td>3</td><td>Name1</td><td>Details3</td></tr><tr id="4"><td>4</td><td>Name1</td><td>Details4</td></tr></tbody></table> and then in the javascript $('.sort').sortable({ cursor: 'move', axis: 'y', update: function(e, ui) { href = '/myReorderFunctionURL/'; $(this).sortable("refresh"); sorted = $(this).sortable("serialize", 'id'); $.ajax({ type: 'POST', url: href, data: sorted, success: function(msg) { //do something with the sorted data } }); }}); This POSTs a serialized version of the items' IDs to the URL given. This function (PHP in my case) then updates the items' orders in the database. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7382/"
]
} |
82,319 | In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there:(channels) * (bits) * (samples/s) * (seconds) = (filesize) Is there a simpler way - a free library, or something in the .net framework perhaps? How would I do this if the .wav file is compressed (with the mpeg codec for example)? | You may consider using the mciSendString(...) function (error checking is omitted for clarity): using System;using System.Text;using System.Runtime.InteropServices;namespace Sound{ public static class SoundInfo { [DllImport("winmm.dll")] private static extern uint mciSendString( string command, StringBuilder returnValue, int returnLength, IntPtr winHandle); public static int GetSoundLength(string fileName) { StringBuilder lengthBuf = new StringBuilder(32); mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero); mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero); mciSendString("close wave", null, 0, IntPtr.Zero); int length = 0; int.TryParse(lengthBuf.ToString(), out length); return length; } }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078/"
]
} |
82,391 | It is advisable to use tables in HTML pages (now that we have CSS)? What are the applications of tables? What features/abilities does tables have that are not in CSS? Related Questions Tables instead of DIVs DIV vs TABLE DIVs vs. TABLEs a rebuttal please | No - not at all. But use tables for tabular data. Just don't use them for general layouting. But if you display tabular data, like results or maybe even a form, go ahead and use tables! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/82391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
82,409 | If I have a table in my database called 'Users', there will be a class generated by LINQtoSQL called 'User' with an already declared empty constructor. What is the best practice if I want to override this constructor and add my own logic to it? | The default constructor which is generated by the O/R-Designer, calls a partial function called OnCreated - so the best practice is not to override the default constructor, but instead implement the partial function OnCreated in MyDataClasses.cs to initialize items: partial void OnCreated(){ Name = "";} If you are implementing other constructors, always take care to call the default constructor so the classes will be initialized properly - for example entitysets (relations) are constructed in the default constructor. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15717/"
]
} |
82,429 | My understanding of Hibernate is that as objects are loaded from the DB they are added to the Session. At various points, depending on your configuration, the session is flushed. At this point, modified objects are written to the database. How does Hibernate decide which objects are 'dirty' and need to be written? Do the proxies generated by Hibernate intercept assignments to fields, and add the object to a dirty list in the Session? Or does Hibernate look at each object in the Session and compare it with the objects original state? Or something completely different? | Hibernate does/can use bytecode generation (CGLIB) so that it knows a field is dirty as soon as you call the setter (or even assign to the field afaict). This immediately marks that field/object as dirty, but doesn't reduce the number of objects that need to be dirty-checked during flush. All it does is impact the implementation of org.hibernate.engine.EntityEntry.requiresDirtyCheck() . It still does a field-by-field comparison to check for dirtiness. I say the above based on a recent trawl through the source code (3.2.6GA), with whatever credibility that adds. Points of interest are: SessionImpl.flush() triggers an onFlush() event. SessionImpl.list() calls autoFlushIfRequired() which triggers an onAutoFlush() event. (on the tables-of-interest). That is, queries can invoke a flush. Interestingly, no flush occurs if there is no transaction. Both those events eventually end up in AbstractFlushingEventListener.flushEverythingToExecutions() , which ends up (amongst other interesting locations) at flushEntities() . That loops over every entity in the session ( source.getPersistenceContext().getEntityEntries() ) calling DefaultFlushEntityEventListener.onFlushEntity() . You eventually end up at dirtyCheck() . That method does make some optimizations wrt to CGLIB dirty flags, but we've still ended up looping over every entity. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11002/"
]
} |
82,437 | Why is the following C# code not allowed: public abstract class BaseClass{ public abstract int Bar { get;}}public class ConcreteClass : BaseClass{ public override int Bar { get { return 0; } set {} }} CS0546 'ConcreteClass.Bar.set': cannot override because 'BaseClass.Bar' does not have an overridable set accessor | I think the main reason is simply that the syntax is too explicit for this to work any other way. This code: public override int MyProperty { get { ... } set { ... } } is quite explicit that both the get and the set are overrides. There is no set in the base class, so the compiler complains. Just like you can't override a method that's not defined in the base class, you can't override a setter either. You might say that the compiler should guess your intention and only apply the override to the method that can be overridden (i.e. the getter in this case), but this goes against one of the C# design principles - that the compiler must not guess your intentions, because it may guess wrong without you knowing. I think the following syntax might do nicely, but as Eric Lippert keeps saying, implementing even a minor feature like this is still a major amount of effort... public int MyProperty{ override get { ... } // not valid C# set { ... }} or, for autoimplemented properties, public int MyProperty { override get; set; } // not valid C# | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
]
} |
82,442 | Inspired by the MVC storefront the latest project I'm working on is using extension methods on IQueryable to filter results. I have this interface; IPrimaryKey{ int ID { get; }} and I have this extension method public static IPrimaryKey GetByID(this IQueryable<IPrimaryKey> source, int id){ return source(obj => obj.ID == id);} Let's say I have a class, SimpleObj which implements IPrimaryKey. When I have an IQueryable of SimpleObj the GetByID method doesn't exist, unless I explicitally cast as an IQueryable of IPrimaryKey, which is less than ideal. Am I missing something here? | It works, when done right. cfeduke's solution works. However, you don't have to make the IPrimaryKey interface generic, in fact, you don't have to change your original definition at all: public static IPrimaryKey GetByID<T>(this IQueryable<T> source, int id) where T : IPrimaryKey{ return source(obj => obj.ID == id);} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15691/"
]
} |
82,483 | Possible Duplicate: .NET - Whatβs the best way to implement a βcatch all exceptions handlerβ I have a .NET console app app that is crashing and displaying a message to the user. All of my code is in a try{<code>} catch(Exception e){<stuff>} block, but still errors are occasionally displayed. In a Win32 app, you can capture all possible exceptions/crashes by installing various exception handlers: /* C++ exc handlers */_set_se_translatorSetUnhandledExceptionFilter_set_purecall_handlerset_terminateset_unexpected_set_invalid_parameter_handler What is the equivalent in the .NET world so I can handle/log/quiet all possible error cases? | Contrary to what some others have posted, there's nothing wrong catching all exceptions. The important thing is to handle them all appropriately. If you have a stack overflow or out of memory condition, the app should shut down for them. Also, keep in mind that OOM conditions can prevent your exception handler from running correctly. For example, if your exception handler displays a dialog with the exception message, if you're out of memory, there may not be enough left for the dialog display. Best to log it and shut down immediately. As others mentioned, there are the UnhandledException and ThreadException events that you can handle to collection exceptions that might otherwise get missed. Then simply throw an exception handler around your main loop (assuming a winforms app). Also, you should be aware that OutOfMemoryExceptions aren't always thrown for out of memory conditions. An OOM condition can trigger all sorts of exceptions, in your code, or in the framework, that don't necessarily have anything to do with the fact that the real underlying condition is out of memory. I've frequently seen InvalidOperationException or ArgumentException when the underlying cause is actually out of memory. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7442/"
]
} |
82,509 | Let's say I want a web page that contains a Flash applet and I'd like to drag and drop some objects from or to the rest of the web page, is this at all possible? Bonus if you know a website somewhere that does that! | This one intrigued me. I know jessegavin posted some code while I went to figure this out, but this one is tested. I have a super-simple working example that lets you drag to and from flash. It's pretty messy as I threw it together during my lunch break. Here's the demo And the source The base class is taken directly from the External Interface LiveDocs . I added MyButton so the button could have some text. The majority of the javascript comes from the same LiveDocs example. I compiled this using mxmlc. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15695/"
]
} |
82,530 | I'm on laptop (Ubuntu) with a network that use HTTP proxy (only http connections allowed). When I use svn up for url like 'http://.....' everything is cool (google chrome repository works perfect), but right now I need to svn up from server with 'svn://....' and I see connection refused. I've set proxy configuration in /etc/subversion/servers but it doesn't help. Anyone have opinion/solution? | In /etc/subversion/servers you are setting http-proxy-host , which has nothing to do with svn:// which connects to a different server usually running on port 3690 started by svnserve command. If you have access to the server, you can setup svn+ssh:// as explained here. Update : You could also try using connect-tunnel , which uses your HTTPS proxy server to tunnel connections: connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690 Then you would use svn checkout svn://localhost:10234/path/to/trunk | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/82530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15752/"
]
} |
82,550 | I have a template class that I serialize (call it C), for which I want to specify a version for boost serialization. As BOOST_CLASS_VERSION does not work for template classes. I tried this: namespace boost {namespace serialization { template< typename T, typename U > struct version< C<T,U> > { typedef mpl::int_<1> type; typedef mpl::integral_c_tag tag; BOOST_STATIC_CONSTANT(unsigned int, value = version::type::value); };}} but it does not compile. Under VC8, a subsequent call to BOOST_CLASS_VERSION gives this error: error C2913: explicit specialization; 'boost::serialization::version' is not a specialization of a class template What is the correct way to do it? | #include <boost/serialization/version.hpp> :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14443/"
]
} |
82,632 | This answer says that Linq is targeted at a slightly different group of developers than NHibernate, Castle, etc. Being rather new to C#, nevermind all the DB stuff surrounding it: Are there other major, for lack of a better term, SQL wrappers than NHibernate, Castle, Linq? What are the differences between them? What kind of developers or development are they aimed at? -Adam | When you say Castle I assume you mean Castle Active Record? The difference is NHibernate is an OR/M and is aimed at developers who want to focus on the domain rather than the database. With linq to sql, your database is pre-existing and you're relationships and some of programming will be driven by how your database is defined. Now between NHibernate and Castle ActiveRecord -- they are similar in that you're driving your application design from the domain but with NHibernate you provide mapping xml files (or mapping classes with fluent NHibernate) where in Active Record you are using the convention over configuration (using attributes to define any columns and settings that don't fit naturally). Castle Active record is still using NHibernate in the background. One OR/M is not necessarily the 'one true way' to go. It depends on your environment, the application your developing and your team. You may also want to check out SubSonic . It's great for active record but it is not for project where you want to focus mainly on your Domain. Depending on the project, I usually use either NHibernate (with Castle Active Record) or Subsonic | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
]
} |
82,644 | Is it possible to use Microsoft Entity Framework with Oracle database? | DevArt's OraDirect provider now supports entity framework. See http://devart.com/news/2008/directs475.html | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
]
} |
82,645 | By default tomcat will create a session cookie for the current domain. If you are on www.example.com, your cookie will be created for www.example.com (will only work on www.example.com). Whereas for example.com it will be created for .example.com (desired behaviour, will work on any subdomain of example.com as well as example.com itself). I've seen a few Tomcat valves which seem to intercept the creation of session cookies and create a replacement cookie with the correct .example.com domain, however none of them seem to work flawlessly and they all appear to leave the existing cookie and just create a new one. This means that two JSESSIONID cookies are being sent with each request. I was wondering if anybody has a definitive solution to this problem. | This is apparently supported via a configuration setting in 6.0.27 and onwards: Configuration is done by editing META-INF/context.xml <Context sessionCookiePath="/something" sessionCookieDomain=".domain.tld" /> https://issues.apache.org/bugzilla/show_bug.cgi?id=48379 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15687/"
]
} |
82,653 | Is there any list of blog engines, written in Django? | EDIT: Original link went dead so here's an updated link with extracts of the list sorted with the most recently updated source at the top. Eleven Django blog engines you should know by Monty Lounge Industries Biblion Django-article Flother Basic-Blog Hello-Newman Banjo djangotechblog Django-YABA Shifting Bits (this is now just a biblion blog) Mighty Lemon Coltrane | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70293/"
]
} |
82,661 | I want to clear the list of projects on the start page...how do I do this? I know I can track it down in the registry, but is there an approved route to go? | There is an MSDN article here which suggests that you just move the projects to a new directory. However, as you mentioned, the list of projects is kept in the registry under this key: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\<version>\ProjectMRUList and the list of recent files is kept in this key: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\<version>\FILEMRUList Note For Visual Studio 2015: The location has changed. You can check out this answer for details. Some people have automated clearing this registry key with their own tools: Visual Studio Most Recent Files Utility Add-in for cleaning Visual Studio 2008 MRU Projects list | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/82661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15778/"
]
} |
82,726 | If I open files I created in Windows, the lines all end with ^M . How do I delete these characters all at once? | dos2unix is a commandline utility that will do this, or :%s/^M//g will if you use Ctrl - v Ctrl - m to input the ^M, or you can :set ff=unix and Vim will do it for you. There is documentation on the fileformat setting, and the Vim wiki has a comprehensive page on line ending conversions . Alternately, if you move files back and forth a lot, you might not want to convert them, but rather to do :set ff=dos , so Vim will know it's a DOS file and use DOS conventions for line endings. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/82726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15482/"
]
} |
82,831 | How do I check whether a file exists or not, without using the try statement? | If the reason you're checking is so you can do something like if file_exists: open_it() , it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it. If you're not planning to open the file immediately, you can use os.path.isfile Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path. import os.pathos.path.isfile(fname) if you need to be sure it's a file. Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7): from pathlib import Pathmy_file = Path("/path/to/file")if my_file.is_file(): # file exists To check a directory, do: if my_file.is_dir(): # directory exists To check whether a Path object exists independently of whether is it a file or directory, use exists() : if my_file.exists(): # path exists You can also use resolve(strict=True) in a try block: try: my_abs_path = my_file.resolve(strict=True)except FileNotFoundError: # doesn't existelse: # exists | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/82831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15616/"
]
} |
82,838 | Below are two ways of reading in the commandline parameters. The first is the way that I'm accustom to seeing using the parameter in the main. The second I stumbled on when reviewing code. I noticed that the second assigns the first item in the array to the path and application but the first skips this. Is it just preference or is the second way the better way now? Sub Main(ByVal args() As String) For i As Integer = 0 To args.Length - 1 Console.WriteLine("Arg: " & i & " is " & args(i)) Next Console.ReadKey()End Sub Sub Main() Dim args() As String = System.Environment.GetCommandLineArgs() For i As Integer = 0 To args.Length - 1 Console.WriteLine("Arg: " & i & " is " & args(i)) Next Console.ReadKey()End Sub I think the same can be done in C#, so it's not necessarily a vb.net question. | Second way is better because it can be used outside the main(), so when you refactor it's one less thing to think about. Also I don't like the "magic" that puts the args in the method parameter for the first way. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/82838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2357/"
]
} |
82,847 | If I am in a function in the code behind, and I want to implement displaying a "Loading..." in the status bar the following makes sense, but as we know from WinForms is a NoNo: StatusBarMessageText.Text = "Loading Configuration Settings..."; LoadSettingsGridData();StatusBarMessageText.Text = "Done"; What we all now from WinForms Chapter 1 class 101, is the form won't display changes to the user until after the Entire Function completes... meaning the "Loading" message will never be displayed to the user. The following code is needed. Form1.SuspendLayout(); StatusBarMessageText.Text = "Loading Configuration Settings..."; Form1.ResumeLayout();LoadSettingsGridData();Form1.SuspendLayout(); StatusBarMessageText.Text = "Done";Form1.ResumeLayout(); What is the best practice for dealing with this fundamental issue in WPF? | Best and simplest: using(var d = Dispatcher.DisableProcessing()){ /* your work... Use dispacher.begininvoke... */} Or IDisposable d;try{ d = Dispatcher.DisableProcessing(); /* your work... Use dispacher.begininvoke... */} finally { d.Dispose();} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744/"
]
} |
82,875 | What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the ATTACH command on the SQLiteΒ 3 command line tool? | There are a few steps to see the tables in an SQLite database: List the tables in your database: .tables List how the table looks: .schema tablename Print the entire table: SELECT * FROM tablename; List all of the available SQLite prompt commands: .help | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/82875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
]
} |
82,878 | Visual studio is pretty good but doesn't create stored procedures automatically. Iron Speed designer does supposedly. But is it any good? | I have used Ironspeed extensively for the past two years for most of our ASP.NET forms over data projects. It works. Does several things well: stored procs, fast layout of table browse and CRUD screens, fast layout of single record CRUD screens. It manages the round-trip (or half-round trip) process decently, detecting changes in your back end db schema and updating its data access layer, then making the changed columns available for you to alter your UI (in record or table control panels). ISD (as they call it) does an excellent job in making security management for your app pretty painless, even down to the control level (if you use ISD's subclassed versions of asp.net controls). Final plus, not a small one, is the CSS-based theme control (easy to change to a variety of themes, easy to customize a particular theme, and not even too bad to build your own theme variant by forking an existing one you like). Depending upon whether you let ISD create your stored procs in the code base or the database, changing DB's at run time can be a piece of cake. Fairly active forum with a core group of helpful contributors. You can probably avoid the paid tech support through the forum. Okay, the down sides. Creates fairly large code conglomerations, being a three tiered architecture. As Galwegian says, like any framework, you've got the velvet handcuffs (get your mind out of the gutter if you are thinking about anything other than code limitations and conventions!). The velvet handcuffs are the page and control model, the data layer, lack of a business object/class capability per se, the postback model, and the temptation to make your user GUI look like THEIR user GUI that comes out of the box because it is so darned easy and convenient. ISD builds a basic page by combining an HTML template (in to which you place ISD specific code generation tags and any other tags, etc., you which using the ISD GUI or by hand). The page model relies upon a code behind page created from a piece of code template. The base classes are almost completely overridable, so that you can override all of the default functions, regenerate the application and not lose your overrides. The database controls live in the page container, but have their own class definitions (i.e., their code-behind) in specific /app_code files. Again, each control type has its own base class with pretty completely overridable methods. A single record control (showing a single db record) is pretty simple. A table, showing several records, has a table class and a table row class. The ISD website (www.ironspeed.com/support) has good documentation of the ISD model as a whole. So, where are the problems in this model?1. Easy and tempting to live with their out of the box GUI. Point ISD at your database, pick the tables you want to have it turn in to pages, tell it the kinds of pages, give it a thematic style and five minutes later you're viewing the application. Cool. But, it is very easy to forget that their user GUI is probably not what your user wants to see. So, be prepared to think for yourself and tinker with the GUI thus created. Not hard to do, and you can use VS 2005 to help you. Business objects. You could put together your own business objects, but it would be difficult and you would get no help from ISD. ISD does a LOT of building of simple validation and checking (appropriate look up values, ranges, lengths, etc.) ISD lets you build custom queries, but these are read-only. It is smart enough (and you can override the write from a page in any case) to let you take a one to many view and write it back to the database (you'd probably override the default base method, but it isn't that hard to do). However, when you get in to serious dependency checking, ISD is still really about tables and not business objects. So, you're going to write some code. If you are smart, you'll write it once store it in app_code somewhere and use it by calling it from an overridden method in your table or record controls. If you are like most of us, you'll first spaghetti it in to one of the code-behind classes above, and then forget you did so, or have a copy in each of the 10 pages that manipulates customer data. In my world, that has usually meant 5 identical functions and 5 that are all different (even though they are all supposed to be the same). ISD makes it tempting to order marinara, because the model lends itself to spaghetti code. Of course, you can completely prevent this, but you gotta learn the ISD model to determine the best way to do it on your project. Page state and postbacks. Although ISD is quite open about this problem and tells users not to just take the defaults of returning the whole asp.net page state in the postback stream (cache on the server instead), the default is to return the whole page. Can make for some BIG pages. Which makes users think S L O W. As I said, you can manipulate this. But, what newbie is going to get this when it is SO tempting to just point, click, and boom - instant application. Your manager is now off your back because her product inventory table is "on the web" with a cool search and edit GUI (of 400kb state pages if you've gone a bit nuts and have just taken the default behaviors of ISD). Great in-house, but the customers in the real world.... Again, knowledge is the key. You can fix this, but you need to know you SHOULD. Database read/write postbacks. No big problem here, but you also need to know that the model is to fetch only the data used at the moment. If your table shows 1000 records in 50 record increments, when you go from records 1 to 50 to 51 through 100, you will postback and hit the database again. This keeps data current, but increases server traffic. Overall: Try the demo version. Point it at something simple that you really want to turn in to an asp.net application. Build maybe three tables. Then dissect it using the above as a guide. See what YOU think and post back to this question. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
82,881 | Lets say I have a Dictionary object: Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>(); Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A foreach is easy: foreach (SomeObject object in myDictionary.Values){ // Do stuff to object} But how can I perform this in reverse? | A dictionary or any other form of hashtable has no ordering. So what you are trying to do is pointless :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2273/"
]
} |
82,933 | Does anyone have any practical suggestions about how to manage feature creep in GUIs? I'm getting strong pressure from both internal and external sources to add, modify, tweak, etc. I always cringe when someone approaches me with the words "wouldn't it be nice if...?". I can't just turn around and yell "NO" at them, because often they are my superiors or customers. Instead, I'm looking for suggestions to help explain why it's a bad idea to be constantly adding new features, and in doing so, manage their expectations of the final product. | Have feature requests handled in a formal process, normally through the project manager and whoever analyzed the requirements originally. Its always better to palm those sorts of decisions off to someone that isn't the developer, assuming that whoever is going to do that job is actually capable of it. If you're freelance then obviously charge for changes to the requirements, and if you're an internal development team, then you could consider inter-department billing to make sure people think about what they want to spend money on. Finally, expect requirements to change and feature creep to happen. If you code without considering what changes might be requested, or your process and/or deadlines are so inflexible that you can't adjust to this, then you'll find that the project will become a nightmare. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
]
} |
82,949 | I'm trying to preform setup and teardown for a set of integration tests, using jUnit 4.4 to execute the tests. The teardown needs to be run reliably. I'm having other problems with TestNG, so I'm looking to port back to jUnit. What hooks are available for execution before any tests are run and after all tests have completed? Note: we're using maven 2 for our build. I've tried using maven's pre- & post-integration-test phases, but, if a test fails, maven stops and doesn't run post-integration-test , which is no help. | Yes, it is possible to reliably run set up and tear down methods before and after any tests in a test suite. Let me demonstrate in code: package com.test;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.runner.RunWith;import org.junit.runners.Suite;import org.junit.runners.Suite.SuiteClasses;@RunWith(Suite.class)@SuiteClasses({Test1.class, Test2.class})public class TestSuite { @BeforeClass public static void setUp() { System.out.println("setting up"); } @AfterClass public static void tearDown() { System.out.println("tearing down"); }} So your Test1 class would look something like: package com.test;import org.junit.Test;public class Test1 { @Test public void test1() { System.out.println("test1"); }} ...and you can imagine that Test2 looks similar. If you ran TestSuite , you would get: setting uptest1test2tearing down So you can see that the set up/tear down only run before and after all tests, respectively. The catch: this only works if you're running the test suite, and not running Test1 and Test2 as individual JUnit tests. You mentioned you're using maven, and the maven surefire plugin likes to run tests individually, and not part of a suite. In this case, I would recommend creating a superclass that each test class extends. The superclass then contains the annotated @BeforeClass and @AfterClass methods. Although not quite as clean as the above method, I think it will work for you. As for the problem with failed tests, you can set maven.test.error.ignore so that the build continues on failed tests. This is not recommended as a continuing practice, but it should get you functioning until all of your tests pass. For more detail, see the maven surefire documentation . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/82949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
]
} |
82,971 | Is it possible to configure Visual Studio 2008 to automatically remove whitespace characters at the end of each line when saving a file? There doesn't seem to be a built-in option, so are there any extensions available to do this? | CodeMaid is a very popular Visual Studio extension and does this automatically along with other useful cleanups. Download: https://github.com/codecadwallader/codemaid/releases/tag/v0.4.3 Modern Download: https://marketplace.visualstudio.com/items?itemName=SteveCadwallader.CodeMaid Documentation: http://www.codemaid.net/documentation/#cleaning I set it to clean up a file on save, which I believe is the default. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/82971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3853/"
]
} |
82,993 | We need to programatically burn files to CD in a C\C++ Windows XP/Vista application we are developing using Borlands Turbo C++. What is the simplest and best way to do this? We would prefer a native windows API (that doesnt rely on MFC) so as not to rely on any third party software/drivers if one is available. | We used the following: Store files in the directory returned by GetBurnPath, then write using Burn. GetCDRecordableInfo is used to check when the CD is ready. #include <stdio.h>#include <imapi.h>#include <windows.h>struct MEDIAINFO { BYTE nSessions; BYTE nLastTrack; ULONG nStartAddress; ULONG nNextWritable; ULONG nFreeBlocks;};//==============================================================================// Description: CD burning on Windows XP//==============================================================================#define CSIDL_CDBURN_AREA 0x003bSHSTDAPI_(BOOL) SHGetSpecialFolderPathA(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate);SHSTDAPI_(BOOL) SHGetSpecialFolderPathW(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate);#ifdef UNICODE#define SHGetSpecialFolderPath SHGetSpecialFolderPathW#else#define SHGetSpecialFolderPath SHGetSpecialFolderPathA#endif//==============================================================================// Interface IDiscMasterconst IID IID_IDiscMaster = {0x520CCA62,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}};const CLSID CLSID_MSDiscMasterObj = {0x520CCA63,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}};typedef interface ICDBurn ICDBurn;// Interface ICDBurnconst IID IID_ICDBurn = {0x3d73a659,0xe5d0,0x4d42,{0xaf,0xc0,0x51,0x21,0xba,0x42,0x5c,0x8d}};const CLSID CLSID_CDBurn = {0xfbeb8a05,0xbeee,0x4442,{0x80,0x4e,0x40,0x9d,0x6c,0x45,0x15,0xe9}};MIDL_INTERFACE("3d73a659-e5d0-4d42-afc0-5121ba425c8d")ICDBurn : public IUnknown{public: virtual HRESULT STDMETHODCALLTYPE GetRecorderDriveLetter( /* [size_is][out] */ LPWSTR pszDrive, /* [in] */ UINT cch) = 0; virtual HRESULT STDMETHODCALLTYPE Burn( /* [in] */ HWND hwnd) = 0; virtual HRESULT STDMETHODCALLTYPE HasRecordableDrive( /* [out] */ BOOL *pfHasRecorder) = 0;};//==============================================================================// Description: Get burn pathname// Parameters: pathname - must be at least MAX_PATH in size// Returns: Non-zero for an error// Notes: CoInitialize(0) must be called once in application//==============================================================================int GetBurnPath(char *path){ ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { BOOL flag; if (pICDBurn->HasRecordableDrive(&flag) == S_OK) { if (SHGetSpecialFolderPath(0, path, CSIDL_CDBURN_AREA, 0)) { strcat(path, "\\"); } else { ret = 1; } } else { ret = 2; } pICDBurn->Release(); } else { ret = 3; } return ret;}//==============================================================================// Description: Get CD pathname// Parameters: pathname - must be at least 5 bytes in size// Returns: Non-zero for an error// Notes: CoInitialize(0) must be called once in application//==============================================================================int GetCDPath(char *path){ ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { BOOL flag; WCHAR drive[5]; if (pICDBurn->GetRecorderDriveLetter(drive, 4) == S_OK) { sprintf(path, "%S", drive); } else { ret = 1; } pICDBurn->Release(); } else { ret = 3; } return ret;}//==============================================================================// Description: Burn CD// Parameters: None// Returns: Non-zero for an error// Notes: CoInitialize(0) must be called once in application//==============================================================================int Burn(void){ ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { if (pICDBurn->Burn(NULL) != S_OK) { ret = 1; } pICDBurn->Release(); } else { ret = 2; } return ret;}//==============================================================================bool GetCDRecordableInfo(long *FreeSpaceSize){ bool Result = false; IDiscMaster *idm = NULL; IDiscRecorder *idr = NULL; IEnumDiscRecorders *pEnumDiscRecorders = NULL; ULONG cnt; long type; long mtype; long mflags; MEDIAINFO mi; try { CoCreateInstance(CLSID_MSDiscMasterObj, 0, CLSCTX_ALL, IID_IDiscMaster, (void**)&idm); idm->Open(); idm->EnumDiscRecorders(&pEnumDiscRecorders); pEnumDiscRecorders->Next(1, &idr, &cnt); pEnumDiscRecorders->Release(); idr->OpenExclusive(); idr->GetRecorderType(&type); idr->QueryMediaType(&mtype, &mflags); idr->QueryMediaInfo(&mi.nSessions, &mi.nLastTrack, &mi.nStartAddress, &mi.nNextWritable, &mi.nFreeBlocks); idr->Release(); idm->Close(); idm->Release(); Result = true; } catch (...) { Result = false; } if (Result == true) { Result = false; if (mtype == 0) { // No Media inserted Result = false; } else { if ((mflags & 0x04) == 0x04) { // Writable Media Result = true; } else { Result = false; } if (Result == true) { *FreeSpaceSize = (mi.nFreeBlocks * 2048); } else { *FreeSpaceSize = 0; } } } return Result;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/82993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14260/"
]
} |
83,068 | I've got a load-balanced (not using Session state) ASP.Net 2.0 app on IIS5 running back to a single Oracle 10g server, using version 10.1.0.301 of the ODAC/ODP.Net drivers. After a long period of inactivity (a few hours), the application, seemingly randomly, will throw an Oracle exception: Exception: ORA-03113: end-of-file on communication channel atOracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx*pOpoSqlValCtx, Object src, String procedure) atOracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery,Boolean fillRequest, CommandBehavior behavior) atOracle.DataAccess.Client.OracleCommand.System.Data.IDbCommand.ExecuteReader() ...Oracle portion of the stack ends here... We are creating new connections on every request, have the open & close wrapped in a try/catch/finally to ensure proper connection closure, and the whole thing is wrapped in a using (OracleConnection yadayada) {...} block. This problem does not appear linked to the restart of the ASP.Net application after being spun down for inactivity. We have yet to reproduce the problem ourselves. Thoughts, prayers, help? More: Checked with IT, the firewall isn't set to kill connections between those servers. | ORA-03113: end-of-file on communication channel Is the database letting you know that the network connection is no more. This could be because: A network issue - faulty connection, or firewall issue The server process on the database that is servicing you died unexpectedly. For 1) ( firewall ) search tahiti.oracle.com for SQLNET.EXPIRE_TIME . This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live. For 1) ( network ) speak to your network admin (connection could be unreliable) For 2) Check the alert.log for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file. Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35/"
]
} |
83,073 | It seems to be the general opinion that tables should not be used for layout in HTML. Why? I have never (or rarely to be honest) seen good arguments for this. The usual answers are: It's good to separate content from layout But this is a fallacious argument; Cliche Thinking . I guess it's true that using the table element for layout has little to do with tabular data. So what? Does my boss care? Do my users care? Perhaps me or my fellow developers who have to maintain a web page care... Is a table less maintainable? I think using a table is easier than using divs and CSS. By the way... why is using a div or a span good separation of content from layout and a table not? Getting a good layout with only divs often requires a lot of nested divs. Readability of the code I think it's the other way around. Most people understand HTML, few understand CSS. It's better for SEO not to use tables Why? Can anybody show some evidence that it is? Or a statement from Google that tables are discouraged from an SEO perspective? Tables are slower. An extra tbody element has to be inserted. This is peanuts for modern web browsers. Show me some benchmarks where the use of a table significantly slows down a page. A layout overhaul is easier without tables, see css Zen Garden . Most web sites that need an upgrade need new content (HTML) as well. Scenarios where a new version of a web site only needs a new CSS file are not very likely. Zen Garden is a nice web site, but a bit theoretical. Not to mention its misuse of CSS. I am really interested in good arguments to use divs + CSS instead of tables. | I'm going to go through your arguments one after another and try to show the errors in them. It's good to separate content from layout But this is a fallacious argument; ClichΓ© Thinking. It's not fallacious at all because HTML was designed intentionally. Misuse of an element might not be completely out of question (after all, new idioms have developed in other languages, as well) but possible negative implications have to be counterbalanced. Additionally, even if there were no arguments against misusing the <table> element today, there might be tomorrow because of the way browser vendors apply special treatment to the element. After all, they know that β <table> elements are for tabular data onlyβ and might use this fact to improve the rendering engine, in the process subtly changing how <table> s behave, and thus breaking cases where it was previously misused. So what? Does my boss care? Do my users care? Depends. Is your boss pointy-haired? Then he might not care. If she's competent, then she will care, because the users will . Perhaps me or my fellow developers who have to maintain a web page care... Is a table less maintainable? I think using a table is easier than using divs and css. The majority of professional web developers seem to oppose you [ citation needed ] . That tables are in fact less maintainable should be obvious. Using tables for layout means that changing the corporate layout will in fact mean changing every single page. This can be very expensive. On the other hand, judicious use of semantically meaningful HTML combined with CSS might confine such changes to the CSS and the pictures used. By the way... why is using a div or a span good separation of content from layout and a table not? Getting a good layout with only divs often requires a lot of nested divs. Deeply nested <div> s are an anti-pattern just as table layouts. Good web designers don't need many of them. On the other hand, even such deep-nested divs don't have many of the problems of table layouts. In fact, they can even contribute to a semantic structure by logically dividing the content in parts. Readability of the code I think it's the other way around. Most people understand html, little understand css. It's simpler. βMost peopleβ don't matter. Professionals matter. For professionals, table layouts create many more problems than HTML + CSS. This is like saying I shouldn't use GVim or Emacs because Notepad is simpler for most people. Or that I shouldn't use LaTeX because MS Word is simpler for most people. It's better for SEO not to use tables I don't know if this is true and wouldn't use this as an argument but it would be logical. Search engines search for relevant data. While tabular data could of course be relevant, it's rarely what users search for. Users search for terms used in the page title or similarly prominent positions. It would therefore be logical to exclude tabular content from filtering and thus cutting the processing time (and costs!) by a large factor. Tables are slower. An extra tbody element has to be inserted. This is peanuts for modern web browsers. The extra element has got nothing to do with tables being slower. On the other hand, the layout algorithm for tables is much harder, the browser often has to wait for the whole table to load before it can begin to layout the content. Additionally, caching of the layout won't work (CSS can easily be cached). All this has been mentioned before. Show me some benchmarks where the use of a table significantly slows down a page. Unfortunately, I don't have any benchmark data. I would be interested in it myself because it's right that this argument lacks a certain scientific rigour. Most web sites that need an upgrade need new content (html) as well. Scenarios where a new version of a web site only needs a new css file are not very likely. Not at all. I've worked on several cases where changing the design was simplified by a separation of content and design. It's often still necessary to change some HTML code but the changes will always be much more confined. Additionally, design changes must on occasion be made dynamically. Consider template engines such as the one used by the WordPress blogging system. Table layouts would literally kill this system. I've worked on a similar case for a commercial software. Being able to change the design without changing the HTML code was one of the business requirements. Another thing. Table layout makes automated parsing of websites (screen scraping) much harder. This might sound trivial because, after all, who does it? I was surprised myself. Screen scraping can help a lot if the service in question doesn't offer a WebService alternative to access its data. I'm working in bioinformatics where this is a sad reality. Modern web techniques and WebServices have not reached most developers and often, screen scraping is the only way to automate the process of getting data. No wonder that many biologists still perform such tasks manually. For thousands of data sets. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/83073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3565/"
]
} |
83,086 | I'm using Visual Studio Team System 2008 at work to do web development. I've gotten quite used to it but can't really afford to purchase even VS 2008 Standard at this time. I have never used any of the Express editions before but I was thinking about downloading VS C# Express and VS Web Developer Express. Am I wasting my time or can I do some serious development with these tools? | You can do serious development on the express editions. They have taken out a few things most notably the plug in system. If you are use to using a bunch of plug ins you may find that not being able to use them is a deterrent. Here is a link to a comparison of the express edition and the other editions. http://msdn.microsoft.com/en-us/library/zcbsd3cz(VS.80).aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2173/"
]
} |
83,132 | I thought I'd found the solution a while ago (see my blog ): If you ever get the JavaScript (or should that be JScript) error "Can't execute code from a freed script" - try moving any meta tags in the head so that they're before your script tags. ...but based on one of the most recent blog comments, the fix I suggested may not work for everyone. I thought this would be a good one to open up to the StackOverflow community.... What causes the error "Can't execute code from a freed script" and what are the solutions/workarounds? | You get this error when you call a function that was created in a window or frame that no longer exists. If you don't know in advance if the window still exists, you can do a try/catch to detect it: try{ f();}catch(e){ if (e.number == -2146823277) // f is no longer available ...} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12124/"
]
} |
83,147 | I remember hearing Joel Spolsky mention in podcast 014 that he'd barely ever used a foreign key (if I remember correctly). However, to me they seem pretty vital to avoid duplication and subsequent data integrity problems throughout your database. Do people have some solid reasons as to why (to avoid a discussion in lines with Stack Overflow principles)? Edit: "I've yet to have a reason to create a foreign key, so this might be my first reason to actually set up one." | Reasons to use Foreign Keys: you won't get Orphaned Rows you can get nice "on delete cascade" behavior, automatically cleaning up tables knowing about the relationships between tables in the database helps the Optimizer plan your queries for most efficient execution, since it is able to get better estimates on join cardinality. FKs give a pretty big hint on what statistics are most important to collect on the database, which in turn leads to better performance they enable all kinds of auto-generated support -- ORMs can generate themselves, visualization tools will be able to create nice schema layouts for you, etc. someone new to the project will get into the flow of things faster since otherwise implicit relationships are explicitly documented Reasons not to use Foreign Keys: you are making the DB work extra on every CRUD operation because it has to check FK consistency. This can be a big cost if you have a lot of churn by enforcing relationships, FKs specify an order in which you have to add/delete things, which can lead to refusal by the DB to do what you want. (Granted, in such cases, what you are trying to do is create an Orphaned Row, and that's not usually a good thing). This is especially painful when you are doing large batch updates, and you load up one table before another, with the second table creating consistent state (but should you be doing that sort of thing if there is a possibility that the second load fails and your database is now inconsistent?). sometimes you know beforehand your data is going to be dirty, you accept that, and you want the DB to accept it you are just being lazy :-) I think (I am not certain!) that most established databases provide a way to specify a foreign key that is not enforced, and is simply a bit of metadata. Since non-enforcement wipes out every reason not to use FKs, you should probably go that route if any of the reasons in the second section apply. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/83147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
]
} |
83,152 | Is there an open source library that will help me with reading/parsing PDF documents in .NET/C#? | Since this question was last answered in 2008, iTextSharp has improved their api dramatically. If you download the latest version of their api from http://sourceforge.net/projects/itextsharp/ , you can use the following snippet of code to extract all text from a pdf into a string. using iTextSharp.text.pdf;using iTextSharp.text.pdf.parser;namespace PdfParser{ public static class PdfTextExtractor { public static string pdfText(string path) { PdfReader reader = new PdfReader(path); string text = string.Empty; for(int page = 1; page <= reader.NumberOfPages; page++) { text += PdfTextExtractor.GetTextFromPage(reader,page); } reader.Close(); return text; } }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/83152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6777/"
]
} |
83,232 | I'm looking for a key/value pair object that I can include in a web service. I tried using .NET's System.Collections.Generic.KeyValuePair<> class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this. Is there any other generic class that can be used for this situation? I'd use .NET's System.Web.UI.Pair class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety. | Just define a struct/class. [Serializable]public struct KeyValuePair<K,V>{ public K Key {get;set;} public V Value {get;set;}} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/83232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
} |
83,279 | I'm developing a 3-column website using a layout like this: <div id='left' style='left: 0; width: 150px; '> ... </div> <div id='middle' style='left: 150px; right: 200px' > ... </div> <div id='right' style='right: 0; width: 200px; '> ... </div> But, considering the default CSS 'position' property of <DIV>'s is 'static', my <DIV>'s were shown one below the other, as expected. So I set the CSS property 'position' to 'relative', and changed the 'top' property of the 'middle' and 'right' <DIV>'s to -(minus) the height of the preceding <DIV> . It worked fine, but this approach brought me two problems: 1) Even though Internet Explorer 7 shows three columns properly, it still keeps the vertical scrollbar as if the <DIV>'s were positioned one below the other, and there is a lot of white space after the content is over. I would'n like to have that. 2) The height of these elements is variable, so I don't really know which value to set for each <DIV> 's 'top' property; and I wouldn't like to hardcode it. So my question is, what would be the best (simple + elegant) way to implement this layout? I would like to avoid absolute positioning , and I also to keep my design tableless. | If you haven't already checked out A List Apart you should, as it contains some excellent tutorials and guidelines for website design. This article in particular should help you out. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/83279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15931/"
]
} |
83,319 | I'm trying to figure out why the control does not honor ZIndex. Example 1 - which works fine <Canvas> <Rectangle Canvas.ZIndex="1" Height="400" Width="600" Fill="Yellow"/> <Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/> </Canvas> Example 2 - which does not work <Canvas> <WebBrowser Canvas.ZIndex="1" Height="400" Width="600" Source="http://www.stackoverflow.com"/> <Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/> </Canvas> Thanks,-- Ed | Unfortunately this is because the WebBrowser control is a wrapper around the Internet Explorer COM control. This means that it gets its own HWND and does not allow WPF to draw anything over it. It has the same restrictions as hosting any other Win32 or WinForms control in WPF. MSDN has more information about WPF/Win32 interop. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15921/"
]
} |
83,320 | What is the difference between TrueType fonts and Type-1 fonts? | The Postscript Type-1 specification was created by Adobe back in 1985 or so. Type-1 fonts are vector based. You can find the specification in " Adobe Type 1. Font Format. ". TrueType fonts were defined by Apple a couple of years earlier so True Type and PostScript were competitors in the 1990s. Microsoft picked up True Type for the native Windows font format in the beginning 1990s (for using PostScript, additional tools like Adobe Type manager were necessary). Today, Microsoft is fading out support for PostScript fonts. Try using one as an UI font in Vista. Good luck ;-) As a successor of TrueType, Microsoft (I think together with Adobe) created the Open Type (anytime around 2000) format and Adobe converted their whole font library into the new format (you can still get them as Type-1 fonts). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15719/"
]
} |
83,329 | I have a ~23000 line SQL dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want. Does anyone know a Unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file? | sed -n '16224,16482p;16483q' filename > newfile From the sed manual : p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option. n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed exits without processing any more commands. q - Exit sed without processing any more commands or input. Note that the current pattern space is printed if auto-print is not disabled with the -n option. and Addresses in a sed script can be in any of the following forms: number Specifying a line number will match only that line in the input. An address range can be specified by specifying two addresses separated by a comma (,). An address range matches lines starting from where the first address matches, and continues until the second address matches (inclusively). | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/83329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15676/"
]
} |
83,405 | I am looking for a good JavaScript library for parsing XML data. It should be much easier to use than the built-in XML DOM parsers bundled with the browsers. I got spoiled a bit working with JSON and am looking forward to something on similar lines for XML. | Disclaimer: I am the author if the open-source Jsonix library which may be suitable for the task. A couple of years ago I was also looking for a good XML<->JSON parsing/serialization library for JavaScript. I needed to process XML documents conforming to rather complex XML Schemas. In Java, I routinely use JAXB for the task so I was looking for something similar: Is there a JavaScript API for XML binding - analog to JAXB for Java? I failed to find such a tool back then. So I wrote Jsonix which I consider to be a JAXB analog for JavaScript. You may find Jsonix suitable, if you're interested in the following features: XML<->JSON conversion is based on a declaraive mapping between XML and JSON structures This mapping can be generated from an XML Schema or written manually Bidirectional - supports parsing as well as serialization (or unmarshalling/marshalling in other terms). Support elements , attributes and also considers namespaces defined in the XML document. Strictly typed. Strictly structured. Support almost all of the XML Schema built-in types (including special types like QName ). Works in browsers as well as Node.js , also compatible to RequireJS / AMD (also to amdefine in Node.js) Has extensive documentation . However, Jsonix may be an overkill , if your XML is rather simple, does not have an XML Schema or if you're not interested in strict typing or structures. Check your requirements. Example Try it in JSFiddle . You can take a purchase order schema and generate a mapping for it using the following command: java -jar node_modules/jsonix/lib/jsonix-schema-compiler-full.jar -d mappings -p PO purchaseorder.xsd You'll get a PO.js file which describes mappings between XML and JavaScript structures. Here's a snippet from this mapping file to give you an impression: var PO = { name: 'PO', typeInfos: [{ localName: 'PurchaseOrderType', propertyInfos: [{ name: 'shipTo', typeInfo: 'PO.USAddress' }, { name: 'billTo', typeInfo: 'PO.USAddress' }, { name: 'comment' }, { name: 'orderDate', typeInfo: 'Calendar', type: 'attribute' }, ...] }, { localName: 'USAddress', propertyInfos: [ ... ] }, ...], elementInfos: [{ elementName: 'purchaseOrder', typeInfo: 'PO.PurchaseOrderType' }, ... ]}; Having this mapping file you can parse the XML : // First we construct a Jsonix context - a factory for unmarshaller (parser)// and marshaller (serializer)var context = new Jsonix.Context([PO]);// Then we create a unmarshallervar unmarshaller = context.createUnmarshaller();// Unmarshal an object from the XML retrieved from the URLunmarshaller.unmarshalURL('po.xml', // This callback function will be provided // with the result of the unmarshalling function (unmarshalled) { // Alice Smith console.log(unmarshalled.value.shipTo.name); // Baby Monitor console.log(unmarshalled.value.items.item[1].productName); }); Or serialize your JavaScript object as XML: // Create a marshallervar marshaller = context.createMarshaller();// Marshal a JavaScript Object as XML (DOM Document)var doc = marshaller.marshalDocument({ name: { localPart: "purchaseOrder" }, value: { orderDate: { year: 1999, month: 10, day: 20 }, shipTo: { country: "US", name: "Alice Smith", street: "123 Maple Street", city: "Mill Valley", state: "CA", zip: 90952 }, billTo: { /* ... */ }, comment: 'Hurry, my lawn is going wild!', items: { /* ... */ } }}); You can try it in JSFiddle to see how it works in practice. Additional disclaimer: this answer is high-voted because of the following discussion on meta. So please be aware of the "meta-effect". High votes here do not necessarily mean that Jsonix is good, applicable or recommended by the community. Do not be mislead by the high votes. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/83405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4337/"
]
} |
83,410 | I have a large CSV file and I want to execute a stored procedure for each line. What is the best way to execute a stored procedure from PowerShell? | This answer was pulled from http://www.databasejournal.com/features/mssql/article.php/3683181 This same example can be used for any adhoc queries. Let us execute the stored procedure βsp_helpdbβ as shown below. $SqlConnection = New-Object System.Data.SqlClient.SqlConnection$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"$SqlCmd = New-Object System.Data.SqlClient.SqlCommand$SqlCmd.CommandText = "sp_helpdb"$SqlCmd.Connection = $SqlConnection$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter$SqlAdapter.SelectCommand = $SqlCmd$DataSet = New-Object System.Data.DataSet$SqlAdapter.Fill($DataSet)$SqlConnection.Close()$DataSet.Tables[0] | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/83410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12767/"
]
} |
83,419 | I'm quoting part of an answer which I received for another question of mine : In the PHP/MySQL world I would say stored procedures are no-go I would like to know: Is that so? Why? Why not? [edit]I mean this as a general question without a specific need in mind[/edit] | I develop and maintain a large PHP/MySQL application. Here is my experience with stored procedures. Over time our application has grown very complex. And with all the logic on the php side, some operations would query the database with over 100 short queries. MySQL is so quick that the performance was still acceptable, but not great. We made the decision in our latest version of the software to move some of the logic to stored procedures for complex operations. We did achieve a significant performance gain due to the fact that we did not have to send data back and forth between PHP and MySQL. I do agree with the other posters here that PL/SQL is not a modern language and is difficult to debug. Bottom Line: Stored Procedures are a great tool for certain situations. But I would not recommend using them unless you have a good reason. For simple applications, stored procedures are not worth the hassle. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/83419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
]
} |
83,439 | What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way? | The best thing to do is to use the algorithm remove_if and isspace: remove_if(str.begin(), str.end(), isspace); Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container: str.erase(remove_if(str.begin(), str.end(), isspace), str.end()); We should also note that remove_if will make at most one copy of the data. Here is a sample implementation: template<typename T, typename P>T remove_if(T beg, T end, P pred){ T dest = beg; for (T itr = beg;itr != end; ++itr) if (!pred(*itr)) *(dest++) = *itr; return dest;} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/83439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15947/"
]
} |
83,531 | I'm trying to write a stored procedure to select employees who have birthdays that are upcoming. SELECT * FROM Employees WHERE Birthday > @Today AND Birthday < @Today + @NumDays This will not work because the birth year is part of Birthday, so if my birthday was '09-18-1983' that will not fall between '09-18-2008' and '09-25-2008'. Is there a way to ignore the year portion of date fields and just compare month/days? This will be run every monday morning to alert managers of birthdays upcoming, so it possibly will span new years. Here is the working solution that I ended up creating, thanks Kogus. SELECT * FROM Employees WHERE Cast(DATEDIFF(dd, birthdt, getDate()) / 365.25 as int) - Cast(DATEDIFF(dd, birthdt, futureDate) / 365.25 as int) <> 0 | Note: I've edited this to fix what I believe was a significant bug. The currently posted version works for me. This should work after you modify the field and table names to correspond to your database. SELECT BRTHDATE AS BIRTHDAY ,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25) AS AGE_NOW ,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()+7) / 365.25) AS AGE_ONE_WEEK_FROM_NOWFROM "Database name".dbo.EMPLOYEES EMPWHERE 1 = (FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()+7) / 365.25)) - (FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25)) Basically, it gets the # of days from their birthday to now, and divides that by 365 (to avoid rounding issues that come up when you convert directly to years). Then it gets the # of days from their birthday to a week from now, and divides that by 365 to get their age a week from now. If their birthday is within a week, then the difference between those two values will be 1. So it returns all of those records. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/83531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2460/"
]
} |
83,547 | I have a decimal number (let's call it goal ) and an array of other decimal numbers (let's call the array elements ) and I need to find all the combinations of numbers from elements which sum to goal. I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective. Your method signature might look something like: public decimal[][] Solve(decimal goal, decimal[] elements) | Interesting answers. Thank you for the pointers to Wikipedia - whilst interesting - they don't actually solve the problem as stated as I was looking for exact matches - more of an accounting/book balancing problem than a traditional bin-packing / knapsack problem. I have been following the development of stack overflow with interest and wondered how useful it would be. This problem came up at work and I wondered whether stack overflow could provide a ready-made answer (or a better answer) quicker than I could write it myself. Thanks also for the comments suggesting this be tagged homework - I guess that is reasonably accurate in light of the above. For those who are interested, here is my solution which uses recursion (naturally) I also changed my mind about the method signature and went for List> rather than decimal[][] as the return type: public class Solver { private List<List<decimal>> mResults; public List<List<decimal>> Solve(decimal goal, decimal[] elements) { mResults = new List<List<decimal>>(); RecursiveSolve(goal, 0.0m, new List<decimal>(), new List<decimal>(elements), 0); return mResults; } private void RecursiveSolve(decimal goal, decimal currentSum, List<decimal> included, List<decimal> notIncluded, int startIndex) { for (int index = startIndex; index < notIncluded.Count; index++) { decimal nextValue = notIncluded[index]; if (currentSum + nextValue == goal) { List<decimal> newResult = new List<decimal>(included); newResult.Add(nextValue); mResults.Add(newResult); } else if (currentSum + nextValue < goal) { List<decimal> nextIncluded = new List<decimal>(included); nextIncluded.Add(nextValue); List<decimal> nextNotIncluded = new List<decimal>(notIncluded); nextNotIncluded.Remove(nextValue); RecursiveSolve(goal, currentSum + nextValue, nextIncluded, nextNotIncluded, startIndex++); } } }} If you want an app to test this works, try this console app code: class Program { static void Main(string[] args) { string input; decimal goal; decimal element; do { Console.WriteLine("Please enter the goal:"); input = Console.ReadLine(); } while (!decimal.TryParse(input, out goal)); Console.WriteLine("Please enter the elements (separated by spaces)"); input = Console.ReadLine(); string[] elementsText = input.Split(' '); List<decimal> elementsList = new List<decimal>(); foreach (string elementText in elementsText) { if (decimal.TryParse(elementText, out element)) { elementsList.Add(element); } } Solver solver = new Solver(); List<List<decimal>> results = solver.Solve(goal, elementsList.ToArray()); foreach(List<decimal> result in results) { foreach (decimal value in result) { Console.Write("{0}\t", value); } Console.WriteLine(); } Console.ReadLine(); }} I hope this helps someone else get their answer more quickly (whether for homework or otherwise). Cheers... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16005/"
]
} |
83,674 | I want to find records on a combination of created_on >= some date AND name IN some list of names. For ">=" I'd have to use sql condition. For "IN" I'd have to use a hash of conditions where the key is :name and the value is the array of names. Is there a way to combine the two? | You can use named scopes in rails 2.1 and above Class Test < ActiveRecord::Base named_scope :created_after_2005, :conditions => "created_on > 2005-01-01" named_scope :named_fred, :conditions => { :name => "fred"}end then you can do Test.created_after_2005.named_fred Or you can give named_scope a lambda allowing you to pass in arguments Class Test < ActiveRecord::Base named_scope :created_after, lambda { |date| {:conditions => ["created_on > ?", date]} } named_scope :named, lambda { |name| {:conditions => {:name => name}} }end then you can do Test.created_after(Time.now-1.year).named("fred") | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/83674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1167846/"
]
} |
83,741 | I need a simple way to monitor multiple text log files distributed over a number of HP-UX servers. They are a mix of text and XML log files from several distributed legacy systems. Currently we just ssh to the servers and use tail -f and grep , but that doesn't scale when you have many logs to keep track of. Since the logs are in different formats and just files in folders (automatically rotated when they reach a certain size) I need to both collect them remotely and parse each one differently. My initial thought was to make a simple daemon process that I can run on each server using a custom file reader for each file type to parse it into a common format that can be exported over the network via a socket. Another viewer program running locally will connect to these sockets and show the parsed logs in some simple tabbed GUI or aggregated to a console. What log format should I try to convert to if I am to implement it this way? Is there some other easier way? Should I attempt to translate the log files to the log4j format to use with Chainsaw or are there better log viewers that can connect to remote sockets? Could I use BareTail as suggested in another log question ? This is not a massivly distributed system and changing the current logging implementations for all applications to use UDP broadcast or put messages on a JMS queue is not an option. | Probably the lightest-weight solution for real-time log watching is to use Dancer's shell in concurrent mode with tail -f: dsh -Mac -- tail -f /var/log/apache/*.log The -a is for all machine names that you've defined in ~/.dsh/machines.list The -c is for concurrent running of tail The -M prepends the hostname to every line of output. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4992/"
]
} |
83,756 | I need to enable/disable completely network interfaces from a script in Windows XP. I'm looking for a python solution, but any general way (eg WMI, some command-line Γ la netsh, some windows call) is welcome and will be adjusted. Thanks. | Using the netsh interface Usage set interface [name = ] IfName [ [admin = ] ENABLED|DISABLED [connect = ] CONNECTED|DISCONNECTED [newname = ] NewName ] Try including everything inside the outer brackets:netsh interface set interface name="thename" admin=disabled connect=DISCONNECTED newname="thename" See also this MS KB page: http://support.microsoft.com/kb/262265/ You could follow either of their suggestions.For disabling the adapter, you will need to determine a way to reference the hardware device. If there will not be multiple adapters with the same name on the computer, you could possibly go off of the Description for the interface (or PCI ID works well). After that, using devcon (disable|enable). Devcon is an add-on console interface for the Device Manager. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6899/"
]
} |
83,777 | There are similar question, but not regarding C# libraries I can use in my source code. Thank you all for your help. I've already saw lucene, but I need something more easy to search for similar strings and without the overhead of the indexing part. The answer I marked has got two very easy algorithms, and one uses LINQ too, so it's perfect. | Levenshtein distance implementation: Using LINQ (not really, see comments) Not using LINQ I have a .NET 1.1 project in which I use the latter. It's simplistic, but works perfectly for what I need. From what I remember it needed a bit of tweaking, but nothing that wasn't obvious. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/83777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4206/"
]
} |
83,787 | I would like to extract the date a jpg file was created. Java has the lastModified method for the File object, but appears to provide no support for extracting the created date from the file. I believe the information is stored within the file as the date I see when I hover the mouse pointer over the file in Win XP is different than what I can get by using JNI with "dir /TC" on the file in DOS. | The information is stored within the image in a format called EXIF or link text . There several libraries out there capable of reading this format, like this one | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16029/"
]
} |
83,807 | All I know about the constraint is it's name ( SYS_C003415 ), but I want to see it's definition. | Looks like I should be querying ALL_CONSTRAINTS . select OWNER, CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION from ALL_CONSTRAINTS where CONSTRAINT_NAME = 'SYS_C003415'; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4203/"
]
} |
83,808 | Where is the option in Visual Studio to make the Home key go to the start of the line? Right now you have to do Home , Home or Home , Ctrl + Left Arrow i'd prefer that home goes to the start of the line. i saw it before, but now i cannot find it. | In Tools/Customize/Keyboard, Reassign the "Home" key from Edit.LineStart" to "Edit.LineFirstColumn" Edit by OP: You must change Scope to Text Editor before this will work. Visual Studio 2010 Visual Studio 2010 removed the "scope" option. Instead you want the "Use new shortcut in" option: | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/83808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
]
} |
83,856 | I have a string coming from a table like "can no pay{1},as your payment{2}due on {3}". I want to replace {1} with some value , {2} with some value and {3} with some value . Is it Possible to replace all 3 in one replace function ? or is there any way I can directly write query and get replaced value ? I want to replace these strings in Oracle stored procedure the original string is coming from one of my table I am just doing select on that table and then I want to replace {1},{2},{3} values from that string to the other value that I have from another table | Although it is not one call, you can nest the replace() calls: SET mycol = replace( replace(mycol, '{1}', 'myoneval'), '{2}', mytwoval) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14299/"
]
} |
83,918 | We have several jobs that run concurrently that have to use the same config info for log4j. They are all dumping the logs into one file using the same appender. Is there a way to have each job dynamically name its log file so they stay seperate? Thanks Tom | Can you pass a Java system property for each job? If so, you can parameterize like this: java -Dmy_var=somevalue my.job.Classname And then in your log4j.properties: log4j.appender.A.File=${my_var}/A.log You could populate the Java system property with a value from the host's environment (for example) that would uniquely identify the instance of the job. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5659/"
]
} |
83,962 | Test the following code: #include <stdio.h>#include <stdlib.h>main(){ const char *yytext="0"; const float f=(float)atof(yytext); size_t t = *((size_t*)&f); printf("t should be 0 but is %d\n", t);} Compile it with: gcc -O3 test.c The GOOD output should be: "t should be 0 but is 0" But with my gcc 4.1.3, I have: "t should be 0 but is -1209357172" | Use the compiler flag -fno-strict-aliasing. With strict aliasing enabled, as it is by default for at least -O3, in the line: size_t t = *((size_t*)&f); the compiler assumes that the size_t* does NOT point to the same memory area as the float*. As far as I know, this is standards-compliant behaviour (adherence with strict aliasing rules in the ANSI standard start around gcc-4, as Thomas Kammeyer pointed out). If I recall correctly, you can use an intermediate cast to char* to get around this. (compiler assumes char* can alias anything) In other words, try this (can't test it myself right now but I think it will work): size_t t = *((size_t*)(char*)&f); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/83962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
]
} |
83,967 | Sometimes my Oracle database on Windows gets hosed. How do I do a manual uninstall of Oracle? | The six-step process to remove all things Oracle from a Windows machine: A. Delete the Oracle services : In the registry, go to \HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services and delete everything that starts with "Oracle" B. Remove other Oracle stuff from the registry : Go to \HKEY_LOCAL_MACHINE\SOFTWARE\ and delete the key ORACLE C. Reboot D. Delete all the Oracle software from the directories where you installed it E. Delete the Oracle software inventory : Delete the directory C:\Program Files\Oracle . You must do this no matter where you installed your Oracle software - the Oracle installer automatically writes information here. F. Delete all shortcuts from your Start menu. G. Remove the Oracle directories from PATH Environment Variable. To simplify cleanup in the future, I'd strongly recommend you install your Oracle products in one or more virtual machines. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/83967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013/"
]
} |
83,983 | example: a_list = [1, 2, 3]a_list.len() # doesn't worklen(a_list) # works Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object. Plus I keep trying the wrong solution since it appears as the logical one to me | Guido's explanation is here : First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI: (a) For some operations, prefix notation just reads better than postfix β prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of doing the same thing using a raw OO notation. (b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isnβt a file has a write() method. Saying the same thing in another way, I see βlenβ as a built-in operation. Iβd hate to lose that. /β¦/ | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/83983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16070/"
]
} |
83,990 | It's common to want browsers to cache resources - JavaScript, CSS, images, etc. until there is a new version available, and then ensure that the browser fetches and caches the new version instead. One solution is to embed a version number in the resource's filename, but will placing the resources to be managed in this way in a directory with a revision number in it do the same thing? Is the whole URL to the file used as a key in the browser's cache, or is it just the filename itself and some meta-data? If my code changes from fetching /r20/example.js to /r21/example.js , can I be sure that revision 20 of example.js was cached, but now revision 21 has been fetched instead and it is now cached? | Yes, any change in any part of the URL (excluding HTTP and HTTPS protocols changes) is interpreted as a different resource by the browser (and any intermediary proxies), and will thus result in a separate entity in the browser-cache. Update: The claim in this ThinkVitamin article that Opera and Safari/Webkit browsers don't cache URLs with ?query=strings is false . Adding a version number parameter to a URL is a perfectly acceptable way to do cache-busting. What may have confused the author of the ThinkVitamin article is the fact that hitting Enter in the address/location bar in Safari and Opera results in different behavior for URLs with query string in them. However, ( and this is the important part! ) Opera and Safari behave just like IE and Firefox when it comes to caching embedded/linked images and stylesheets and scripts in web pages - regardless of whether they have "?" characters in their URLs. (This can be verified with a simple test on a normal Apache server.) (I would have commented on the currently accepted answer if I had the reputation to do it. :-) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/83990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12559/"
]
} |
84,007 | Do you guys know how I can use the Curl command line to POST SOAP to test a web service? I have a file (soap.xml) which has all the soap message attached to it I just don't seem to be able to properly post it. Thanks! | Posting a string: curl -d "String to post" "http://www.example.com/target" Posting the contents of a file: curl -d @soap.xml "http://www.example.com/target" | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/84007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13469/"
]
} |
84,009 | I like ReSharper, but it is a total memory hog. It can quickly swell up and consume a half-gig of RAM without too much effort and bog down the IDE. Does anybody know of any way to configure it to be not as slow? | Turn off the on-the-fly compilation (which, unfortunately, is one of its best features) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/84009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13890/"
]
} |
84,034 | I have 1 red polygon say and 50 randomly placed blue polygons - they are situated in geographical 2D space . What is the quickest/speediest algorithim to find the the shortest distance between a red polygon and its nearest blue polygon? Bear in mind that it is not a simple case of taking the points that make up the vertices of the polygon as values to test for distance as they may not necessarily be the closest points. So in the end - the answer should give back the closest blue polygon to the singular red one. This is harder than it sounds! | I doubt there is better solution than calculating the distance between the red one and every blue one and sorting these by length. Regarding sorting, usually QuickSort is hard to beat in performance (an optimized one, that cuts off recursion if size goes below 7 items and switches to something like InsertionSort, maybe ShellSort). Thus I guess the question is how to quickly calculate the distance between two polygons, after all you need to make this computation 50 times. The following approach will work for 3D as well, but is probably not the fastest one: Minimum Polygon Distance in 2D Space The question is, are you willing to trade accuracy for speed? E.g. you can pack all polygons into bounding boxes, where the sides of the boxes are parallel to the coordinate system axes. 3D games use this approach pretty often. Therefor you need to find the maximum and minimum values for every coordinate (x, y, z) to construct the virtual bounding box. Calculating the distances of these bounding boxes is then a pretty trivial task. Here's an example image of more advanced bounding boxes, that are not parallel to the coordinate system axes: Oriented Bounding Boxes - OBB However, this makes the distance calculation less trivial. It is used for collision detection, as you don't need to know the distance for that, you only need to know if one edge of one bounding box lies within another bounding box. The following image shows an axes aligned bounding box: Axes Aligned Bounding Box - AABB OOBs are more accurate, AABBs are faster. Maybe you'd like to read this article: Advanced Collision Detection Techniques This is always assuming, that you are willing to trade precision for speed. If precision is more important than speed, you may need a more advanced technique. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/84034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
]
} |
84,096 | ssh will look for its keys by default in the ~/.ssh folder. I want to force it to always look in another location. The workaround I'm using is to add the keys from the non-standard location to the agent: ssh-agentssh-add /path/to/where/keys/really/are/id_rsa (on Linux and MingW32 shell on Windows) | If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry: IdentityFile ~/.foo/identity man ssh_config to find other config options. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/84096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6329/"
]
} |
84,102 | I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks. | Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language. non-idiomatic python using a loop with append: mylist = [1, 2, 3, 4]newlist = []for i in mylist: newlist.append(i * 2) idiomatic python using a list comprehension: mylist = [1, 2, 3, 4]newlist = [(i * 2) for i in mylist] | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/84102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
]
} |
84,125 | I've been writing PHP for about six years now and have got to a point where I feel I should be doing more to write better code. I know that Object Oriented code is the way to go but I can't get my head around the concept. Can anyone explain in terms that any idiot can understand, OO and how it works in PHP or point me to an idiots guide tutorial? | Think of a thingy. Any thingy, a thingy you want to do stuff to. Say, a breakfast. (All code is pseudocode, any resemblance to any language living, dead, or being clinically abused in the banking industry is entirely coincidental and nothing to do with your post being tagged PHP) So you define a template for how you'd represent a breakfast. This is a class: class Breakfast {} Breakfasts contain attributes. In normal non-object-oriented stuff, you might use an array for this: $breakfast = array('toast_slices' => 2,'eggs' => 2,'egg_type' => 'fried','beans' => 'Hell yeah','bacon_rashers' => 3 ); And you'd have various functions for fiddling with it: function does_user_want_beans($breakfast){ if (isset($breakfast['beans']) && $breakfast['beans'] != 'Hell no'){ return true; } return false;} And you've got a mess, and not just because of the beans. You've got a data structure that programmers can screw with at will, an ever-expanding collection of functions to do with the breakfast entirely divorced from the definition of the data. So instead, you might do this: class Breakfast { var $toast_slices = 2; var $eggs = 2; var $egg_type = 'fried'; var $beans = 'Hell yeah'; var $bacon_rashers = 3; function wants_beans(){ if (isset($this->beans) && $this->beans != 'Hell no'){ return true; } return true; } function moar_magic_pig($amount = 1){ $this->bacon += $amount; } function cook(){ breakfast_cook($this); }} And then manipulating the program's idea of Breakfast becomes a lot cleaner: $users = fetch_list_of_users();foreach ($users as $user){ // So this creates an instance of the Breakfast template we defined above $breakfast = new Breakfast(); if ($user->likesBacon){ $breakfast->moar_magic_pig(4); } // If you find a PECL module that does this, Email me. $breakfast->cook();} I think this looks cleaner, and a far neater way of representing blobs of data we want to treat as a consistent object. There are better explanations of what OO actually is, and why it's academically better, but this is my practical reason, and it contains bacon. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/84125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6916/"
]
} |
84,209 | Introduction I've always been searching for a way to make Visual Studio draw a line after a certain amount of characters. Below is a guide to enable these so called guidelines for various versions of Visual Studio. Visual Studio 2013 or later Install Paul Harrington's Editor Guidelines extension . Visual Studio 2010 and 2012 Install Paul Harrington's Editor Guidelines extension for VS 2010 or VS 2012 . Open the registry at: VS 2010: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor VS 2012: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor and add a new string called Guides with the value RGB(100,100,100), 80 . Thefirst part specifies the color, while the other one ( 80 ) is the column the line will be displayed. Or install the Guidelines UI extension (which is also a part of the Productivity Power Tools ), which will add entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. The current disadvantage of this method is that you can't specify the column directly. Visual Studio 2008 and Other Versions If you are using Visual Studio 2008 open the registry at HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor and add a new string called Guides with the value RGB(100,100,100), 80 . The first part specifies the color, while the other one ( 80 ) is the column the line will be displayed. The vertical line will appear, when you restart Visual Studio. This trick also works for various other version of Visual Studio, as long as you use the correct path: 2003: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\Text Editor2005: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor2008 Express: HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor This also works in SQL Server 2005 and probably other versions. | This is originally from Sara's blog . It also works with almost any version of Visual Studio, you just need to change the "8.0" in the registry key to the appropriate version number for your version of Visual Studio. The guide line shows up in the Output window too. (Visual Studio 2010 corrects this, and the line only shows up in the code editor window.) You can also have the guide in multiple columns by listing more than one number after the color specifier: RGB(230,230,230), 4, 80 Puts a white line at column 4 and column 80. This should be the value of a string value Guides in "Text Editor" key (see bellow). Be sure to pick a line color that will be visisble on your background. This color won't show up on the default background color in VS. This is the value for a light grey: RGB(221, 221, 221). Here are the registry keys that I know of: Visual Studio 2010 : HKCU\Software\Microsoft\VisualStudio\10.0\Text Editor Visual Studio 2008 : HKCU\Software\Microsoft\VisualStudio\9.0\Text Editor Visual Studio 2005 : HKCU\Software\Microsoft\VisualStudio\8.0\Text Editor Visual Studio 2003 : HKCU\Software\Microsoft\VisualStudio\7.1\Text Editor For those running Visual Studio 2010, you may want to install the following extensions rather than changing the registry yourself: http://visualstudiogallery.msdn.microsoft.com/en-us/0fbf2878-e678-4577-9fdb-9030389b338c http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91 These are also part of the Productivity Power Tools , which includes many other very useful extensions. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/84209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11387/"
]
} |
84,269 | I'm regularly running into similar situations :I have a bunch of COM .DLLs (no IDL files) which I need to use and invoke to be able to access some foreign (non-open, non-documented) data format. Microsoft's Visual Studio platform has very nice capabilities to import such COM DLLs and use them in my project (Visual C++'s #import directive, or picking and adding them using Visual Basic .NET's dialogs) - and that's the vendors recommended way to use them. I would be interested into finding a way to use those DLLs on non-microsoft development platforms. Namely, using these COM classes in C++ project compiled with MinGW or Cygwin, or even Wine's GCC port to linux (compiles C++ targeting Win32 into binary running natively on Linux). I have got some limited success using this driver, but this isn't successful in 100% of situations (I can't use COM objects returned by some methods). Has someone had success in similar situations ? | Answering myself but I managed to find the perfect library for OLE/COM calling in non-Microsoft compilers : disphelper . (it's available from sourceforge.net under a permissive BSD license). It works both in C and C++ (and thus any other language with C bindings as well). It uses a printf/scanf-like format string syntax . (You pass whatever you want as long as you specify it in the format string, unlike XYDispDriver which requires the arguments to exactly match whatever is specified in the type library). I modified it a little bit to get it also compile under Linux with WineGCC (to produce native Linux elf out of Win32 code), and to handle "by ref" calls automatically (stock disthelper requires the programmer to setup his/her own VARIANT). My patched version and patches are available as a fork on github: https://github.com/DrYak/disphelper And here are my patches : patch for single source patch for split source | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/84269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16168/"
]
} |
84,278 | How do I use RelativeSource with WPF bindings and what are the different use-cases? | If you want to bind to another property on the object: {Binding Path=PathToProperty, RelativeSource={RelativeSource Self}} If you want to get a property on an ancestor: {Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}} If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate) {Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}} or, shorter (this only works for OneWay bindings): {TemplateBinding Path=PathToProperty} | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/84278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
]
} |
84,282 | Do you need to use some kind of provider? Can you setup your own SMS server? Does any open source solutions exist? I am an SMS newbie so any insight on how this is accomplished would be great. I am partial to Java but any language is fine. | This is easy. Yes, you need a "sms gateway" provider. There are a lot out there. These companies provide APIs for you to send/receive SMS. e.g. the German company Mobilant provides an easy API. If you want to receive a SMS just program a simple PHP / JSP / s.th.else dynamic web page and let Mobilant call it. e.g. Mobilant receives a SMS for you Mobilant calls your web page http://yourpage.com/receive.php?message= ... You do what you need to do You really don't want to setup your own SMS Server or Center ;-) This is really expensive, takes months to setup and costs some nice ferraris. Use a provider and pay per SMS. It's the cheapest and fastest way. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/84282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5569/"
]
} |
84,330 | Here is the updated question: the current query is doing something like: $sql1 = "TRUNCATE TABLE fubar";$sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu"; The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet. Is my only option to do the CREATE TABLE , run the TRUNCATE TABLE , and then fill the table? (3 separate queries) original question was: I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql: CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries. This code will be executed using PHP. | shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion. Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it doesn't exist isn't quite right. You will indeed need multiple statements. Either conditionally create then populate: CREATE TEMPORARY TABLE IF NOT EXISTS fubar ( id int, name varchar(80) ) TRUNCATE TABLE fubar INSERT INTO fubar SELECT * FROM barfu or just drop and recreate DROP TABLE IF EXISTS fubar CREATE TEMPORARY TABLE fubar SELECT id, name FROM barfu With pure SQL those are your two real classes of solutions. I like the second better. (With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/84330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16186/"
]
} |
84,340 | I wonder why would a C++, C#, Java developer want to learn a dynamic language? Assuming the company won't switch its main development language from C++/C#/Java to a dynamic one what use is there for a dynamic language? What helper tasks can be done by the dynamic languages faster or better after only a few days of learning than with the static language that you have been using for several years? Update After seeing the first few responses it is clear that there are two issues.My main interest would be something that is justifiable to the employer as an expense.That is, I am looking for justifications for the employer to finance the learning of a dynamic language. Aside from the obvious that the employee will have broader view, theemployers are usually looking for some "real" benefit. | A lot of times some quick task comes up that isn't part of the main software you are developing. Sometimes the task is one off ie compare this file to the database and let me know the differences. It is a lot easier to do text parsing in Perl/Ruby/Python than it is in Java or C# (partially because it is a lot easier to use regular expressions). It will probably take a lot less time to parse the text file using Perl/Ruby/Python (or maybe even vbscript cringe and then load it into the database than it would to create a Java/C# program to do it or to do it by hand. Also, due to the ease at which most of the dynamic languages parse text, they are great for code generation. Sure your final project must be in C#/Java/Transact SQL but instead of cutting and pasting 100 times, finding errors, and cutting and pasting another 100 times it is often (but not always) easier just to use a code generator. A recent example at work is we needed to get data from one accounting system into our accounting system. The system has an import format, but the old system had a completely different format (fixed width although some things had to be matched). The task is not to create a program to migrate the data over and over again. It is to shove the data into our system and then maintain it there going forward. So even though we are a C# and SQL Server shop, I used Python to convert the data into the format that could be imported by our application. Ultimately it doesn't matter that I used python, it matters that the data is in the system. My boss was pretty impressed. Where I often see the dynamic languages used for is testing. It is much easier to create a Python/Perl/Ruby program to link to a web service and throw some data against it than it is to create the equivalent Java program. You can also use python to hit against command line programs, generate a ton of garbage (but still valid) test data, etc.. quite easily. The other thing that dynamic languages are big on is code generation. Creating the C#/C++/Java code. Some examples follow: The first code generation task I often see is people using dynamic languages to maintain constants in the system. Instead of hand coding a bunch of enums, a dynamic language can be used to fairly easily parse a text file and create the Java/C# code with the enums. SQL is a whole other ball game but often you get better performance by cut and pasting 100 times instead of trying to do a function (due to caching of execution plans or putting complicated logic in a function causing you to go row by row instead of in a set). In fact it is quite useful to use the table definition to create certain stored procedures automatically. It is always better to get buy in for a code generator. But even if you don't, is it more fun to spend time cutting/pasting or is it more fun to create a Perl/Python/Ruby script once and then have that generate the code? If it takes you hours to hand code something but less time to create a code generator, then even if you use it once you have saved time and hence money. If it takes you longer to create a code generator than it takes to hand code once but you know you will have to update the code more than once, it may still make sense. If it takes you 2 hours to hand code, 4 hours to do the generator but you know you'll have to hand code equivalent work another 5 or 6 times than it is obviously better to create the generator. Also some things are easier with dynamic languages than Java/C#/C/C++. In particular regular expressions come to mind. If you start using regular expressions in Perl and realize their value, you may suddenly start making use of the Java regular expression library if you haven't before. If you have then there may be something else. I will leave you with one last example of a task that would have been great for a dynamic language. My work mate had to take a directory full of files and burn them to various cd's for various customers. There were a few customers but a lot of files and you had to look in them to see what they were. He did this task by hand....A Java/C# program would have saved time, but for one time and with all the development overhead it isn't worth it. However slapping something together in Perl/Python/Ruby probably would have been worth it. He spent several hours doing it. It would have taken less than one to create the Python script to inspect each file, match which customer it goes to, and then move the file to the appropriate place.....Again, not part of the standard job. But the task came up as a one off. Is it better to do it yourself, spend the larger amount of time to make Java/C# do the task, or spend a much smaller amount of time doing it in Python/Perl/Ruby. If you are using C or C++ the point is even more dramatic due to the extra concerns of programming in C or C++ (pointers, no array bounds checking, etc.). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/84340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11827/"
]
} |
84,341 | I have a core file generated on a remote system that I don't have direct access to. I also have local copies of the library files from the remote system, and the executable file for the crashing program. I'd like to analyse this core dump in gdb. For example: gdb path/to/executable path/to/corefile My libraries are in the current directory. In the past I've seen debuggers implement this by supplying the option "-p ." or "-p /=."; so my question is: How can I specify that libraries be loaded first from paths relative to my current directory when analysing a corefile in gdb? | Start gdb without specifying the executable or core file, then type the following commands: set solib-absolute-prefix ./usrfile path/to/executablecore-file path/to/corefile You will need to make sure to mirror your library path exactly from the target system. The above is meant for debugging targets that don't match your host, that is why it's important to replicate your root filesystem structure containing your libraries. If you are remote debugging a server that is the same architecture and Linux/glibc version as your host, then you can do as fd suggested: set solib-search-path <path> If you are trying to override some of the libraries, but not all then you can copy the target library directory structure into a temporary place and use the solib-absolute-prefix solution described above. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/84341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13956/"
]
} |
84,378 | When using divs when is it best to use a class vs id ? Is it best to use class , on say font variant or elements within the html? Then use id for the structure/containers? This is something I've always been a little uncertain on, any help would be great. | Use id to identify elements that there will only be a single instance of on a page. For instance, if you have a single navigation bar that you are placing in a specific location, use id="navigation" . Use class to group elements that all behave a certain way. For instance, if you want your company name to appear in bold in body text, you might use <span class='company'> . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/84378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16195/"
]
} |
84,404 | Visual Studio 2003 and 2005 (and perhaps 2008 for all I know) require the command line user to run in the 'Visual Studio Command Prompt'. When starting this command prompt it sets various environment variables that the C++ compiler, cl, uses when compiling. This is not always desirable. If, for example, I want to run 'cl' from within Ant, I'd like to avoid having to run Ant from within the 'Visual Studio Command Prompt'. Running vcvars32.bat isn't an option as the environment set by vcvars32.bat would be lost by the time cl was run (if running from within Ant). Is there an easy way to run cl without having to run from within the Visual Studio command prompt? | The compilers can be used from command line (or makefiles) just like any other compilers. The main things you need to take care of are the INCLUDE and LIB environment variables, and PATH. If you're running from cmd.exe, you can just run this .bat to set the environment: C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat If you're trying to use the compilers from a makefile, Cygwin, MinGW, or something like that you need to set the environment variables manually. Assuming the compiler is installed in the default location, this should work for the Visual Studio 2008 compiler and the latest Windows SDK: Add to PATH: C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin C:\Program Files\Microsoft Visual Studio 9.0\VC\Bin C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE Add to INCLUDE: C:\Program Files\Microsoft SDKs\Windows\v6.1\Include C:\Program Files\Microsoft Visual Studio 9.0\VC\include C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\include Add to LIB: C:\Program Files\Microsoft SDKs\Windows\v6.1\Lib C:\Program Files\Microsoft Visual Studio 9.0\VC\lib These are the bare minimum, but should be enough for basic things. Study the vcvarsall.bat script to see what more you may want to set. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/84404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6839/"
]
} |
84,421 | Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent? Something like the opposite of String#to_i : "0A".to_i(16) #=>10 Like perhaps: "0A".hex #=>10 I know how to roll my own, but it's probably more efficient to use a built in Ruby function. | You can give to_s a base other than 10: 10.to_s(16) #=> "a" Note that in ruby 2.4 FixNum and BigNum were unified in the Integer class. If you are using an older ruby check the documentation of FixNum# to_s and BigNum# to_s | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/84421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6106/"
]
} |
84,422 | in XSLT processing, is there a performance difference between apply-template and call-template? In my stylesheets there are many instances where I can use either, which is the best choice? | As with all performance questions, the answer will depend on your particular configuration (in particular the XSLT processor you're using) and the kind of processing that you're doing. <xsl:apply-templates> takes a sequence of nodes and goes through them one by one. For each, it locates the template with the highest priority that matches the node, and invokes it. So <xsl:apply-templates> is like a <xsl:for-each> with an <xsl:choose> inside, but more modular. In contrast, <xsl:call-template> invokes a template by name. There's no change to the context node (no <xsl:for-each> ) and no choice about which template to use. So with exactly the same circumstances, you might imagine that <xsl:call-template> will be faster because it's doing less work. But if you're in a situation where either <xsl:apply-templates> or <xsl:call-template> could be used, you're probably going to be doing the <xsl:for-each> and <xsl:choose> yourself, in XSLT, rather than the processor doing it for you, behind the scenes. So in the end my guess it that it will probably balance out. But as I say it depends a lot on the kind of optimisation your processor has put into place and exactly what processing you're doing. Measure it and see. My rules of thumb about when to use matching templates and when to use named templates are: use <xsl:apply-templates> and matching templates if you're processing individual nodes to create a result; use modes if a particular node needs to be processed in several different ways (such as in the table of contents vs the body of a document) use <xsl:call-template> and a named template if you're processing something other than an individual node, such as strings or numbers or sets of nodes (in XSLT 2.0) use <xsl:function> if you're returning an atomic value or an existing node | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/84422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
84,427 | Specifically, is the following legal C++? class A{};void foo(A*);void bar(const A&);int main(void){ foo(&A()); // 1 bar(A()); // 2} It appears to work correctly, but that doesn't mean it's necessarily legal. Is it? Edit - changed A& to const A& | 1: Taking the address of a temporary is not allowed. Visual C++ allows it as a language extension (language extensions are on by default). 2: This is perfectly legal. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/84427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9530/"
]
} |
84,449 | The XML Schema Part 2 specifies that an instance of a datatype that is defined as boolean can have the following legal literals {true, false, 1, 0}.The following XML, for example, when deserialized, sets the boolean property "Emulate" to true . <root> <emulate>1</emulate></root> However, when I serialize the object back to the XML, I get true instead of the numerical value. My question is, is there a way that I can control the boolean representation in the XML? | You can also do this by using some XmlSerializer attribute black magic: [XmlIgnore]public bool MyValue { get; set; }/// <summary>Get a value purely for serialization purposes</summary>[XmlElement("MyValue")]public string MyValueSerialize{ get { return this.MyValue ? "1" : "0"; } set { this.MyValue = XmlConvert.ToBoolean(value); }} You can also use other attributes to hide this member from intellisense if you're offended by it! It's not a perfect solution, but it can be quicker than implementing IXmlSerializable. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/84449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8205/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.