source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
119,706 | Possible Duplicate: How do I get the HMODULE for the currently executing code? I'm trying to find a resource in my own module. If this module is an executable, that's trivial - GetModuleHandle(NULL) returns the handle of the "main" module. My module, however, is a DLL that is loaded by another executable. So GetModuleHandle(NULL) will return the module handle to that executable, which is obviously not what I want. Is there any way to determine the module handle of the module that contains the currently running code? Using the DLL's name in a call to GetModuleHandle() seems like a hack to me (and is not easily maintainable in case the code in question is transplanted into a different DLL). | Store the module handle away when it is given to you in DllMain and then use it later when you actually need it. A lot of frameworks (e.g., MFC) do this automatically. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/119706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2074/"
]
} |
119,723 | Developing websites are time-consuming. To improve productivity, I would code a prototype to show to our clients. I don't worry about making the prototype comform to the standard. Most of the time, our clients would approve the prototype and give an unreasonable deadline. I usually end up using the prototype in production (hey, the prototype works. No need to make my job harder.) I could refactor the code to output valid HTML. But is it worth the effort to output valid HTML? | It is only worth the effort if it gives you a practical benefit. Sticking to standards might make it easier to build a website that works across most browsers. Then again, if you're happy with how a website displays on the browsers you care about (maybe one, maybe all), then going through hoops to make it pass validation is a waste of time. Also, the difference in SEO between an all-valid html website and a mostly-valid html website is negligible. So always look for the practical benefit, there are some in some situations, but don't do it just for the sake of it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/119723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
]
} |
119,730 | I have a VARCHAR column in a SQL Server 2000 database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer. When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order. 1210ABB1 What is the best way to achieve this? | One possible solution is to pad the numeric values with a character in front so that all are of the same string length. Here is an example using that approach: select MyColumnfrom MyTableorder by case IsNumeric(MyColumn) when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn else MyColumn end The 100 should be replaced with the actual length of that column. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/119730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
]
} |
119,788 | Before moving on to use SVN, I used to manage my project by simply keeping a /develop/ directory and editing and testing files there, then moving them to the /main/ directory. When I decided to move to SVN, I needed to be sure that the directories were indeed in sync. So, what is a good way to write a shell script [ bash ] to recursively compare files with the same name in two different directories? Note: The directory names used above are for sample only. I do not recommend storing your code in the top level :). | The diff command has a -r option to recursively compare directories: diff -r /develop /main | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/119788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20386/"
]
} |
119,802 | I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this: server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT))service = Service()server.register_instance(service)server.serve_forever() I then have a ServiceRemote class that looks like this: def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port))def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs: @useDbdef select(self, db, fields, **kwargs): pass The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result. When I call this method, I get the error " call () got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need. Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments. | You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, example below: Server from SimpleXMLRPCServer import SimpleXMLRPCServerclass Server(object): def __init__(self, hostport): self.server = SimpleXMLRPCServer(hostport) def register_function(self, function, name=None): def _function(args, kwargs): return function(*args, **kwargs) _function.__name__ = function.__name__ self.server.register_function(_function, name) def serve_forever(self): self.server.serve_forever()#example usageserver = Server(('localhost', 8000))def test(arg1, arg2): print 'arg1: %s arg2: %s' % (arg1, arg2) return 0server.register_function(test)server.serve_forever() Client import xmlrpclibclass ServerProxy(object): def __init__(self, url): self._xmlrpc_server_proxy = xmlrpclib.ServerProxy(url) def __getattr__(self, name): call_proxy = getattr(self._xmlrpc_server_proxy, name) def _call(*args, **kwargs): return call_proxy(args, kwargs) return _call#example usageserver = ServerProxy('http://localhost:8000')server.test(1, 2)server.test(arg2=2, arg1=1)server.test(1, arg2=2)server.test(*[1,2])server.test(**{'arg1':1, 'arg2':2}) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/119802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
]
} |
119,969 | Would anyone recommend a particular JavaScript charting library - specifically one that doesn't use flash at all? | There is a growing number of Open Source and commercial solutions for pure JavaScript charting that do not require Flash. In this response I will only present Open Source options. There are 2 main classes of JavaScript solutions for graphics that do not require Flash: Canvas-based, rendered in IE using ExplorerCanvas that in turns relies on VML SVG on standard-based browsers, rendered as VML in IE There are pros and cons of both approaches but for a charting library I would recommend the later because it is well integrated with DOM, allowing to manipulate charts elements with the DOM, and most importantly setting DOM events. By contrast Canvas charting libraries must reinvent the DOM wheel to manage events. So unless you intend to build static graphs with no event handling, SVG/VML solutions should be better. For SVG/VML solutions there are many options, including: Dojox Charting , good if you use the Dojo toolkit already Raphael -based solutions Raphael is a very active, well maintained, and mature, open-source graphic library with very good cross-browser support including IE 6 to 8, Firefox, Opera, Safari, Chrome, and Konqueror. Raphael does not depend on any JavaScript framework and therefore can be used with Prototype, jQuery, Dojo, Mootools, etc... There are a number of charting libraries based on Raphael, including (but not limited to): gRaphael , an extension of the Raphael graphic library Ico , with an intuitive API based on a single function call to create complex charts Disclosure: I am the developer of one of the Ico forks on github . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/119969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
]
} |
119,980 | Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser? I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load. Edit: From link provided in accepted answer: Include Silverlight.js (from Silverlight SDK) Silverlight.isInstalled("2.0"); | Include Silverlight.js (from Silverlight SDK) Silverlight.isInstalled("4.0") Resource: http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/119980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
]
} |
119,994 | We run full re-indexes every 7 days (i.e. creating the index from scratch) on our Lucene index and incremental indexes every 2 hours or so. Our index has around 700,000 documents and a full index takes around 17 hours (which isn't a problem). When we do incremental indexes, we only index content that has changed in the past two hours, so it takes much less time - around half an hour. However, we've noticed that a lot of this time (maybe 10 minutes) is spent running the IndexWriter.optimize() method. The LuceneFAQ mentions that: The IndexWriter class supports an optimize() method that compacts the index database and speeds up queries. You may want to use this method after performing a complete indexing of your document set or after incremental updates of the index. If your incremental update adds documents frequently, you want to perform the optimization only once in a while to avoid the extra overhead of the optimization. ...but this doesn't seem to give any definition for what "frequently" means. Optimizing is CPU intensive and VERY IO-intensive, so we'd rather not be doing it if we can get away with it. How much is the hit of running queries on an un-optimized index (I'm thinking especially in terms of query performance after a full re-index compared to after 20 incremental indexes where, say, 50,000 documents have changed)? Should we be optimising after every incremental index or is the performance hit not worth it? | Mat, since you seem to have a good idea how long your current process takes, I suggest that you remove the optimize() and measure the impact. Do many of the documents change in those 2 hour windows? If only a small fraction (50,000/700,000 is about 7%) are incrementally re-indexed, then I don't think you are getting much value out of an optimize() . Some ideas: Don't do an incremental optimize() at all. My experience says you are not seeing a huge query improvement anyway. Do the optimize() daily instead of 2-hourly. Do the optimize() during low-volume times (which is what the javadoc says). And make sure you take measurements. These kinds of changes can be a shot in the dark without them. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/119994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6282/"
]
} |
120,016 | I have the following XML structure: <?xml version="1.0" ?><course xml:lang="nl"> <body> <item id="787900813228567" view="12000" title="0x|Beschrijving" engtitle="0x|Description"><![CDATA[Dit college leert studenten hoe ze een onderzoek kunn$ <item id="5453116633894965" view="12000" title="0x|Onderwijsvorm" engtitle="0x|Method of instruction"><![CDATA[instructiecollege]]></item> <item id="7433550075448316" view="12000" title="0x|Toetsing" engtitle="0x|Examination"><![CDATA[Opdrachten/werkstuk]]></item> <item id="015071401858970545" view="12000" title="0x|Literatuur" engtitle="0x|Required reading"><![CDATA[Wayne C. Booth, Gregory G. Colomb, Joseph M. Wi$ <item id="5960589172957031" view="12000" title="0x|Uitbreiding" engtitle="0x|Expansion"><![CDATA[]]></item> <item id="3610066867901779" view="12000" title="0x|Aansluiting" engtitle="0x|Place in study program"><![CDATA[]]></item> <item id="19232369892482925" view="12000" title="0x|Toegangseisen" engtitle="0x|Course requirements"><![CDATA[]]></item> <item id="3332396346891524" view="12000" title="0x|Doelgroep" engtitle="0x|Target audience"><![CDATA[]]></item> <item id="6606851872934866" view="12000" title="0x|Aanmelden bij" engtitle="0x|Enrollment at"><![CDATA[]]></item> <item id="1478643580820973" view="12000" title="0x|Informatie bij" engtitle="0x|Information at"><![CDATA[Docent]]></item> <item id="9710608434763993" view="12000" title="0x|Rooster" engtitle="0x|Schedule"><![CDATA[1e semester, maandag 15.00-17.00, zaal 1175/030]]></item> </body></course> I want to get the data from one of the item tags. To get to this tag, I use the following xpath: $description = $xml->xpath("//item[@title='0x|Beschrijving']"); This does indeed return an array in the form of: Array( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 787900813228567 [view] => 12000 [title] => 0x|Beschrijving [engtitle] => 0x|Description ) )) But where is the actual information (that is stored between the item tags) located? I must be doing something wrong, but I can't figure out what that might be... Probably something really simple... Help would be appreciated. | When you load the XML file, you'll need to handle the CDATA.. This example works: <?php$xml = simplexml_load_file('file.xml', NULL, LIBXML_NOCDATA);$description = $xml->xpath("//item[@title='0x|Beschrijving']");var_dump($description);?> Here's the output: array(1) { [0]=> object(SimpleXMLElement)#2 (2) { ["@attributes"]=> array(4) { ["id"]=> string(15) "787900813228567" ["view"]=> string(5) "12000" ["title"]=> string(15) "0x|Beschrijving" ["engtitle"]=> string(14) "0x|Description" } [0]=> string(41) "Dit college leert studenten hoe ze een on" }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18922/"
]
} |
120,022 | What's the best tool that you use to monitor Web Service, SOAP, WCF, etc. traffic that's coming and going on the wire? I have seen some tools that made with Java but they seem to be a little crappy. What I want is a tool that sits in the middle as a proxy and does port redirection (which should have configurable listen/redirect ports). Are there any tools work on Windows to do this? | For Windows HTTP, you can't beat Fiddler . You can use it as a reverse proxy for port-forwarding on a web server. It doesn't necessarily need IE, either. It can use other clients . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/120022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39/"
]
} |
120,061 | I try to fetch a Wikipedia article with Python's urllib: f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes") s = f.read()f.close() However instead of the html page I get the following response: Error - Wikimedia Foundation: Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to ()Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT Wikipedia seems to block request which are not from a standard browser. Anybody know how to work around this? | You need to use the urllib2 that superseedes urllib in the python std library in order to change the user agent. Straight from the examples import urllib2opener = urllib2.build_opener()opener.addheaders = [('User-agent', 'Mozilla/5.0')]infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes')page = infile.read() | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/120061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20999/"
]
} |
120,071 | I have a string of arbitrary length, and starting at position p0, I need to find the first occurrence of one of three 3-letter patterns. Assume the string contain only letters. I need to find the count of triplets starting at position p0 and jumping forward in triplets until the first occurrence of either 'aaa' or 'bbb' or 'ccc'. Is this even possible using just a regex? | Moritz says this might be faster than a regex. Even if it's a little slower, it's easier to understand at 5 am. :) #0123456789.123456789.123456789. my $string = "alsdhfaaasccclaaaagalkfgblkgbklfs"; my $pos = 9; my $length = 3; my $regex = qr/^(aaa|bbb|ccc)/;while( $pos < length $string ) { print "Checking $pos\n"; if( substr( $string, $pos, $length ) =~ /$regex/ ) { print "Found $1 at $pos\n"; last; } $pos += $length; } | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
]
} |
120,083 | Is there a way to alter the precision of an existing decimal column in Microsoft SQL Server? | ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1) Just put decimal(precision, scale) , replacing the precision and scale with your desired values. I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/120083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12767/"
]
} |
120,116 | I have been tasked with implementing a PKI library in C# for a company project, and have been unable to find a good implementation of it. There appear to be multiple libraries, and many broken links pointing to MSDN libraries that have been removed. I've seen people using Crypt32.dll, people building their own libraries, people using P/Invoke to access system certificate stores, people extending the built-in libraries, examples that simply don't apply to C# (e.g. Java examples), and commercial libraries. My question is, which implementation/library is most recommended for simple encryption/decryption of data? As some background for what I plan to do with it, I simply need to encrypt messages using a private key (.pfx), and decrypt with public keys (.cer). Message signing and authentication isn't required at this level of the project, although it may be in future.I have seen reference to encryption lengths which make me uneasy. We need to be able to encrypt any length message (within reason, of course!). Is this something I need to worry about, and if so, is there a way to deal with it? I would prefer not to store public/private keys in the windows certificate manager if at all possible, but if it makes implementation significantly simpler, so be it. I realize PKI and encryption is a large and complex subject, but I'm hoping for a relatively simple library anyway... (one can hope, right?) Thanks! | Well, you did not mention that the built-in class doesn't cover your need, so how about System.Security.Cryptography.RSACryptoServiceProvider ? It has a large set qualified ways to asymmetrically encrypt/decrypt streams. There are several tutorial/guides to take you along the way: Public Key RSA Encryption in C# .NET - Code Project RSA Encryption in .NET -- Demystified! - By Peter A. Bromberg There are countless more to be found through Google . Update : About the length-restrictments, it's should not be any problems if you just implement the same buffer-algorithm on both sides, encryption and decryption. Update2 : Yes, my example was RSACryptoProvider , but you can use any class that derives from System.Security.Cryptography.AsymmetricAlgorithm , if you want a public/private key-solution. Or build your own... or maybe not :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21002/"
]
} |
120,131 | I'm considering the following: I have some data stream which I'd like to protect as secure as possible -- does it make any sense to apply let's say AES with some IV, then Blowfish with some IV and finally again AES with some IV? The encryption / decryption process will be hidden (even protected against debugging) so it wont be easy to guess which crypto method and what IVs were used (however, I'm aware of the fact the power of this crypto chain can't be depend on this fact since every protection against debugging is breakable after some time). I have computer power for this (that amount of data isn't that big) so the question only is if it's worth of implementation. For example, TripleDES worked very similarly, using three IVs and encrypt/decrypt/encrypt scheme so it probably isn't total nonsense. Another question is how much I decrease the security when I use the same IV for 1st and 3rd part or even the same IV for all three parts? I welcome any hints on this subject | I'm not sure about this specific combination, but it's generally a bad idea to mix things like this unless that specific combination has been extensively researched. It's possible the mathematical transformations would actually counteract one another and the end result would be easier to hack. A single pass of either AES or Blowfish should be more than sufficient. UPDATE: From my comment below… Using TripleDES as an example: think of how much time and effort from the world's best cryptographers went into creating that combination (note that DoubleDES had a vulnerability), and the best they could do is 112 bits of security despite 192 bits of key. UPDATE 2: I have to agree with Diomidis that AES is extremely unlikely to be the weak link in your system. Virtually every other aspect of your system is more likely to be compromised than AES. UPDATE 3: Depending on what you're doing with the stream, you may want to just use TLS (the successor to SSL). I recommend Practical Cryptography for more details—it does a pretty good job of addressing a lot of the concerns you'll need to address. Among other things, it discusses stream ciphers , which may or may not be more appropriate than AES (since AES is a block cipher and you specifically mentioned that you had a data stream to encrypt). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21009/"
]
} |
120,139 | What's the difference between failover and disaster recovery? | Failover: When one machine fails, another machine (usually in the same location) takes over and resumes service Disaster recovery: When Godzilla destroys your data center, you do have alternative locations to keep providing your service and protocols/means for the other location to know how to keep delivering the service Depending on the particular needs of each service, disaster recovery might just be a backup tape in a safe in a different location. In other words, it's just having a defined protocol to recover from disaster. Likewise, failover might just be having a spare backup machine which makes you go to the data center for it to take over the place of the failed one, that is, having a defined protocol about what to do in case of machine failure. Summing up, failover answers the question 'what do I do in case a single machine fails?', disaster recovery answers 'what do I do in case a disaster happens (fire, floods, war, ISP goes bankrupt, whatever)?' High Availability Deployment Architecture | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/120139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21011/"
]
} |
120,180 | I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it! I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated! To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc. | Based on @Alexandre Victoor's answer, I wrote a little class based on the Lucene Spellchecker in the contrib package (and using the LuceneDictionary included in it) that does exactly what I want. This allows re-indexing from a single source index with a single field, and provides suggestions for terms. Results are sorted by the number of matching documents with that term in the original index, so more popular terms appear first. Seems to work pretty well :) import java.io.IOException;import java.io.Reader;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.ISOLatin1AccentFilter;import org.apache.lucene.analysis.LowerCaseFilter;import org.apache.lucene.analysis.StopFilter;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter;import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side;import org.apache.lucene.analysis.standard.StandardFilter;import org.apache.lucene.analysis.standard.StandardTokenizer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.index.CorruptIndexException;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.Term;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.Sort;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TopDocs;import org.apache.lucene.search.spell.LuceneDictionary;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;/** * Search term auto-completer, works for single terms (so use on the last term * of the query). * <p> * Returns more popular terms first. * * @author Mat Mannion, [email protected] */public final class Autocompleter { private static final String GRAMMED_WORDS_FIELD = "words"; private static final String SOURCE_WORD_FIELD = "sourceWord"; private static final String COUNT_FIELD = "count"; private static final String[] ENGLISH_STOP_WORDS = { "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "i", "if", "in", "into", "is", "no", "not", "of", "on", "or", "s", "such", "t", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with" }; private final Directory autoCompleteDirectory; private IndexReader autoCompleteReader; private IndexSearcher autoCompleteSearcher; public Autocompleter(String autoCompleteDir) throws IOException { this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir, null); reOpenReader(); } public List<String> suggestTermsFor(String term) throws IOException { // get the top 5 terms for query Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term)); Sort sort = new Sort(COUNT_FIELD, true); TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort); List<String> suggestions = new ArrayList<String>(); for (ScoreDoc doc : docs.scoreDocs) { suggestions.add(autoCompleteReader.document(doc.doc).get( SOURCE_WORD_FIELD)); } return suggestions; } @SuppressWarnings("unchecked") public void reIndex(Directory sourceDirectory, String fieldToAutocomplete) throws CorruptIndexException, IOException { // build a dictionary (from the spell package) IndexReader sourceReader = IndexReader.open(sourceDirectory); LuceneDictionary dict = new LuceneDictionary(sourceReader, fieldToAutocomplete); // code from // org.apache.lucene.search.spell.SpellChecker.indexDictionary( // Dictionary) IndexReader.unlock(autoCompleteDirectory); // use a custom analyzer so we can do EdgeNGramFiltering IndexWriter writer = new IndexWriter(autoCompleteDirectory, new Analyzer() { public TokenStream tokenStream(String fieldName, Reader reader) { TokenStream result = new StandardTokenizer(reader); result = new StandardFilter(result); result = new LowerCaseFilter(result); result = new ISOLatin1AccentFilter(result); result = new StopFilter(result, ENGLISH_STOP_WORDS); result = new EdgeNGramTokenFilter( result, Side.FRONT,1, 20); return result; } }, true); writer.setMergeFactor(300); writer.setMaxBufferedDocs(150); // go through every word, storing the original word (incl. n-grams) // and the number of times it occurs Map<String, Integer> wordsMap = new HashMap<String, Integer>(); Iterator<String> iter = (Iterator<String>) dict.getWordsIterator(); while (iter.hasNext()) { String word = iter.next(); int len = word.length(); if (len < 3) { continue; // too short we bail but "too long" is fine... } if (wordsMap.containsKey(word)) { throw new IllegalStateException( "This should never happen in Lucene 2.3.2"); // wordsMap.put(word, wordsMap.get(word) + 1); } else { // use the number of documents this word appears in wordsMap.put(word, sourceReader.docFreq(new Term( fieldToAutocomplete, word))); } } for (String word : wordsMap.keySet()) { // ok index the word Document doc = new Document(); doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES, Field.Index.UN_TOKENIZED)); // orig term doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES, Field.Index.TOKENIZED)); // grammed doc.add(new Field(COUNT_FIELD, Integer.toString(wordsMap.get(word)), Field.Store.NO, Field.Index.UN_TOKENIZED)); // count writer.addDocument(doc); } sourceReader.close(); // close writer writer.optimize(); writer.close(); // re-open our reader reOpenReader(); } private void reOpenReader() throws CorruptIndexException, IOException { if (autoCompleteReader == null) { autoCompleteReader = IndexReader.open(autoCompleteDirectory); } else { autoCompleteReader.reopen(); } autoCompleteSearcher = new IndexSearcher(autoCompleteReader); } public static void main(String[] args) throws Exception { Autocompleter autocomplete = new Autocompleter("/index/autocomplete"); // run this to re-index from the current index, shouldn't need to do // this very often // autocomplete.reIndex(FSDirectory.getDirectory("/index/live", null), // "content"); String term = "steve"; System.out.println(autocomplete.suggestTermsFor(term)); // prints [steve, steven, stevens, stevenson, stevenage] }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/120180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6282/"
]
} |
120,228 | I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend? What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not. This is just a quick example of what I was thinking about: if ($alreadyDone == 0 && time() > $timeToRunMaintainance) { runTask(); $timeToRunMaintainance = time() + $interval;} Anything else I should take into consideration or is there a better method than this? | That's what cronjobs are made for. man crontab assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15214/"
]
} |
120,240 | I am trying to optimize some stored procedures on a SQL Server 2000 database and when I try to use SQL Profiler I get an error message "In order to run a trace against SQL Server you have to be a member of sysadmin fixed server role.". It seems that only members of the sysadmin role can run traces on the server (something that was fixed in SQL Server 2005) and there is no way in hell that I will be granted that server role (company policies) What I'm doing now is inserting the current time minus the time the procedure started at various stages of the code but I find this very tedious I was also thinking of replicating the database to a local installation of SQL Server but the stored procedure is using data from many different databases that i will spend a lot of time copying data locally So I was wondering if there is some other way of profiling SQL code? (Third party tools, different practices, something else ) | That's what cronjobs are made for. man crontab assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11471/"
]
} |
120,250 | Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')? | Nope. But you can use short integers in arrays: from array import arraya = array("h") # h = signed short, H = unsigned short As long as the value stays in that array it will be a short integer. documentation for the array module | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21029/"
]
} |
120,262 | Say for instance I was writing a function that was designed to accept multiple argument types: var overloaded = function (arg) { if (is_dom_element(arg)) { // Code for DOM Element argument... }}; What's the best way to implement is_dom_element so that it works in a cross-browser, fairly accurate way? | jQuery checks the nodeType property. So you would have: var overloaded = function (arg) { if (arg.nodeType) { // Code for DOM Element argument... }}; Although this would detect all DOM objects, not just elements. If you want elements alone, that would be: var overloaded = function (arg) { if (arg.nodeType && arg.nodeType == 1) { // Code for DOM Element argument... }}; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10942/"
]
} |
120,283 | I am wanting to find the distance between two different points. This I know can be accomplished with the great circle distance. http://www.meridianworlddata.com/Distance-calculation.asp Once done, with a point and distance I would like to find the point that distance north, and that distance east in order to create a box around the point. | Here is a Java implementation of Haversine formula. I use this in a project to calculate distance in miles between lat/longs. public static double distFrom(double lat1, double lng1, double lat2, double lng2) { double earthRadius = 3958.75; // miles (or 6371.0 kilometers) double dLat = Math.toRadians(lat2-lat1); double dLng = Math.toRadians(lng2-lng1); double sindLat = Math.sin(dLat / 2); double sindLng = Math.sin(dLng / 2); double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2) * Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); double dist = earthRadius * c; return dist; } | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/120283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8633/"
]
} |
120,295 | I'd like to find a good object oriented C++ (as opposed to C) wrapper for sqlite. What do people recommend? If you have several suggestions please put them in separate replies for voting purposes. Also, please indicate whether you have any experience of the wrapper you are suggesting and how you found it to use. | This is really inviting down-votes, but here goes... I use sqlite directly from C++, and don't see any value with an added C++ abstraction layer. It's quite good (and efficient) as is. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/120295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17493/"
]
} |
120,296 | This is obviously a stupid question.I am coding in Eclipse both on Mac and Linux, but I mixed up and used the Mac shortcut to window tabbing ( Ctrl - Cmd - F6 ), but I was using the Linux on uni and screen went black. I've done this before, but this time I can't get back to my desktop. Ctrl - Alt F1 - F6 gives me different terminals, F7 gives me a black screen and F8 a blinking underscore in the top left corner. Shouldn't my session have been somewhere in F1 - F6 and is it lost? | X is probably still running on F7 , your display driver (or something else) is just misbehaving. You might be able to trick it into coming back on by going to F7 and blindly opening a terminal and playing with xset ($ xset dpms force on ). Or you can ctrl - alt - backspace to kill X and GDM should restart it. Try seeing if you can repeat the problem and then file a bug report (or let the lab admin know if it isn't your computer). It probably has something to do with your distro's kernel configuration/patching. I've had this happen before on Ubuntu but not any other distros (I've used many), which is why I am assuming it might be distro-specific issue. Probably the unintended consequences of some kernel patching. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6371/"
]
} |
120,334 | I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution. The following does not work on my windows development machine (although I'd think that this should be at least a possible solution): $array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich');$oldLocal=setlocale(LC_COLLATE, "0");var_dump(setlocale(LC_COLLATE, 'German_Germany.65001'));usort($array, 'strcoll');var_dump(setlocale(LC_COLLATE, $oldLocal));var_dump($array); The output is: string(20) "German_Germany.65001"string(1) "C"array(6) { [0]=> string(6) "Birnen" [1]=> string(9) "Ungetiere" [2]=> string(6) "Äpfel" [3]=> string(5) "Apfel" [4]=> string(9) "Ungetüme" [5]=> string(11) "Österreich"} This is complete nonsense. Using 1252 as the codepage for setlocale() gives another output but still a plainly wrong one: string(19) "German_Germany.1252"string(1) "C"array(6) { [0]=> string(11) "Österreich" [1]=> string(6) "Äpfel" [2]=> string(5) "Apfel" [3]=> string(6) "Birnen" [4]=> string(9) "Ungetüme" [5]=> string(9) "Ungetiere"} Is there a way to sort an array with UTF-8 strings locale aware? Just noted that this seems to be PHP on Windows problem, as the same snippet with de_DE.utf8 used as locale works on a Linux machine. Nevertheless a solution for this Windows-specific problem would be nice... | $a = array( 'Кръстев', 'Делян1', 'делян1', 'Делян2', 'делян3', 'кръстев' );$col = new \Collator('bg_BG');$col->asort( $a );var_dump( $a ); Prints: array 2 => string 'делян1' (length=11) 1 => string 'Делян1' (length=11) 3 => string 'Делян2' (length=11) 4 => string 'делян3' (length=11) 5 => string 'кръстев' (length=14) 0 => string 'Кръстев' (length=14) The Collator class is defined in PECL intl extension . It is distributed with PHP 5.3 sources but might be disabled for some builds. E.g. in Debian it is in package php5-intl . Collator::compare is useful for usort . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11354/"
]
} |
120,380 | Is there anyway in Java to delete data (e.g., a variable value, object) and be sure it can't be recovered from memory? Does assigning null to a variable in Java delete the value from memory? Any ideas? Answers applicable to other languages are also acceptable. | Due to the wonders virtual memory, it is nearly impossible to delete something from memory in a completely irretrievable manner. Your best bet is to zero out the value fields; however: This does not mean that an old (unzeroed) copy of the object won't be left on an unused swap page, which could persist across reboots. Neither does it stop someone from attaching a debugger to your application and poking around before the object gets zeroed or crashing the VM and poking around in the heap dump. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15474/"
]
} |
120,420 | I would like to have information about the icons which are displayed alongside the site URLs on a web browser. Is this some browser specific feature? Where do we specify the icon source, ie, is it in some tag on the web page itself ? | These icons are called favicons Most web browsers support http://mysite.com/favicon.ico but the proper way to do it is to include an icon meta tag in the head profile. <head profile="http://www.w3.org/2005/10/profile"><link rel="icon" type="image/png" href="/somewhere/myicon.png" />[…]</head> Source from the W3C itself. Your best bet is to probably do both with the same icon image. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/120420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11614/"
]
} |
120,422 | How do I iterate over a set of records in RPG(LE) with embedded SQL? | Usually I'll create a cursor and fetch each record. //*********************************************************************** // Main - Main Processing Routine begsr Main; exsr BldSqlStmt; if OpenSqlCursor() = SQL_SUCCESS; dow FetchNextRow() = SQL_SUCCESS; exsr ProcessRow; enddo; if sqlStt = SQL_NO_MORE_ROWS; CloseSqlCursor(); endif; endif; CloseSqlCursor(); endsr; // Main I have added more detail to this answer in a post on my website . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
120,438 | What's the difference between "Layers" and "Tiers"? | Logical layers are merely a way oforganizing your code. Typical layersinclude Presentation, Business andData – the same as the traditional3-tier model. But when we’re talkingabout layers, we’re only talking aboutlogical organization of code. In noway is it implied that these layersmight run on different computers or indifferent processes on a singlecomputer or even in a single processon a single computer. All we are doingis discussing a way of organizing acode into a set of layers defined byspecific function. Physical tiers however, are only aboutwhere the code runs. Specifically,tiers are places where layers aredeployed and where layers run. Inother words, tiers are the physicaldeployment of layers. Source: Rockford Lhotka, Should all apps be n-tier? | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/120438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
]
} |
120,584 | In a pyGame application, I would like to render resolution-free GUI widgets described in SVG. How can I achieve this? (I like the OCEMP GUI toolkit but it seems to be bitmap dependent for its rendering) | This is a complete example which combines hints by other people here.It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0. #!/usr/bin/pythonimport arrayimport mathimport cairoimport pygameimport rsvgWIDTH = 512HEIGHT = 512data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)pygame.init()window = pygame.display.set_mode((WIDTH, HEIGHT))svg = rsvg.Handle(file="test.svg")ctx = cairo.Context(surface)svg.render_cairo(ctx)screen = pygame.display.get_surface()image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")screen.blit(image, (0, 0)) pygame.display.flip() clock = pygame.time.Clock()while True: clock.tick(15) for event in pygame.event.get(): if event.type == pygame.QUIT: raise SystemExit | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8450/"
]
} |
120,588 | I'm using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objects from the database according to user-provided strings. For example, when searching for people, if the user is looking for people who live in 'fran', I want to be able to give her people in San Francisco. SQL is not my strong suit, and I prefer Hibernate's Criteria building code to hard-coded strings as it is. Can anyone point me in the right direction about how to do this in code, and if impossible, how the hard-coded SQL should look like? Thanks, Yuval =8-) | For the simple case you describe, look at Restrictions.ilike(), which does a case-insensitive search. Criteria crit = session.createCriteria(Person.class);crit.add(Restrictions.ilike('town', '%fran%');List results = crit.list(); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/120588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2819/"
]
} |
120,618 | What logging solutions exist for j2me? I'm specifically interested in easily excluding logging for "release" version, to have a smaller package & memory footprint. | If you are using preprocessing and obfuscation with Proguard, then you can have a simple logging class. public class Log { public static void debug(final String message) { //#if !release.build System.out.println(message); //#endif }} Or do logging where ever you need to. Now, if release.build property is set to true, this code will be commented out, that will result in an empty method. Proguard will remove all usages of empty method - In effect release build will have all debug messages removed. Edit: Thinking about it on library level (I'm working on mapping J2ME library) I have, probably, found a better solution. public class Log { private static boolean showDebug; public static void debug(final String message) { if (showDebug) { System.out.println(message); } } public static void setShowDebug(final boolean show) { showDebug = show; }} This way end developer can enable log levels inside library that he/she is interested in. If nothing will be enabled, all logging code will be removed in end product obfuscation. Sweet :) /JaanusSiim | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6827/"
]
} |
120,621 | Is Eclipse at all theme-able? I would like to install a dark color scheme for it, since I much prefer white text on dark background than the other way around. | As posted to a few related questions already, I'm working on a plugin for easy, cross-editor color theme management: http://marketplace.eclipse.org/content/eclipse-color-theme It is still work in progress, but already supports many editors and a few dark color themes. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/120621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/985/"
]
} |
120,627 | I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error: MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj) This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it? I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library. | There is really good discussion of how hard this is here: http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/ Apparently, you need to patch the CRT Edit: actually, a MS employee gave the technique in the discussion. You need to move your malloc to a lib, and then link it before the CRT "he also mentions that if you link your malloc as a lib before the CRT (i.e. make sure to turn on ‘ignore default libs’ and explictly include the CRT), you’ll get what you want, and can redistribute this lib without problems." | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14443/"
]
} |
120,648 | I use Assert.Fail a lot when doing TDD. I'm usually working on one test at a time but when I get ideas for things I want to implement later I quickly write an empty test where the name of the test method indicates what I want to implement as sort of a todo-list. To make sure I don't forget I put an Assert.Fail() in the body. When trying out xUnit.Net I found they hadn't implemented Assert.Fail. Of course you can always Assert.IsTrue(false) but this doesn't communicate my intention as well. I got the impression Assert.Fail wasn't implemented on purpose. Is this considered bad practice? If so why? @Martin MeredithThat's not exactly what I do. I do write a test first and then implement code to make it work. Usually I think of several tests at once. Or I think about a test to write when I'm working on something else. That's when I write an empty failing test to remember. By the time I get to writing the test I neatly work test-first. @JimmehThat looks like a good idea. Ignored tests don't fail but they still show up in a separate list. Have to try that out. @Matt HowellsGreat Idea. NotImplementedException communicates intention better than assert.Fail() in this case @Mitch WheatThat's what I was looking for. It seems it was left out to prevent it being abused in another way I abuse it. | For this scenario, rather than calling Assert.Fail, I do the following (in C# / NUnit) [Test]public void MyClassDoesSomething(){ throw new NotImplementedException();} It is more explicit than an Assert.Fail. There seems to be general agreement that it is preferable to use more explicit assertions than Assert.Fail(). Most frameworks have to include it though because they don't offer a better alternative. For example, NUnit (and others) provide an ExpectedExceptionAttribute to test that some code throws a particular class of exception. However in order to test that a property on the exception is set to a particular value, one cannot use it. Instead you have to resort to Assert.Fail: [Test]public void ThrowsExceptionCorrectly(){ const string BAD_INPUT = "bad input"; try { new MyClass().DoSomething(BAD_INPUT); Assert.Fail("No exception was thrown"); } catch (MyCustomException ex) { Assert.AreEqual(BAD_INPUT, ex.InputString); }} The xUnit.Net method Assert.Throws makes this a lot neater without requiring an Assert.Fail method. By not including an Assert.Fail() method xUnit.Net encourages developers to find and use more explicit alternatives, and to support the creation of new assertions where necessary. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/120648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3320/"
]
} |
120,656 | How do I get a list of all files (and directories) in a given directory in Python? | This is a way to traverse every file and directory in a directory tree: import osfor dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # print path to all filenames. for filename in filenames: print(os.path.join(dirname, filename)) # Advanced usage: # editing the 'dirnames' list will stop os.walk() from recursing into there. if '.git' in dirnames: # don't go into any .git directories. dirnames.remove('.git') | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/120656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
]
} |
120,662 | I'm trying to run SQuirreL SQL. I've downloaded it and installed it, but when I try to run it I get this error message: Java Virtual Machine Launcher. Could not find the main class. Program will exit. I get the gist of this, but I have not idea how to fix it. Any help? more info: I'm on Windows XP pro. I have java 1.6 installed, and other apps are running OK. The install ran OK. I believe I've followed the installation instructions correctly. To run it, I'm invoking the squirrel-sql.bat file. Update This question: "Could not find the main class: XX. Program will exit." gives some background on this error from the point of view of a java developer. | Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type 'java' from the command line do you get back a list of instructions or do you get something like "java is not recognized as a .....")? You could try try running squirrel-sql.jar from the command line (from the squirrel sql directory), using: java -jar squirrel-sql.jar | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
]
} |
120,693 | I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens. If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that. Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html><head> <title>Regex</title> <script type="text/javascript" charset="utf-8"> var grep = new RegExp('gr['); try { var results = grep.exec('bob went to town'); } catch (e) { //Do nothing? } alert('If you can see this then the script kept going'); </script></head><body></body></html> | Try this the new RegExp is throwing the exception Regex <script type="text/javascript" charset="utf-8"> var grep; try { grep = new RegExp("gr["); } catch(e) { alert(e); } try { var results = grep.exec('bob went to town'); } catch (e) { //Do nothing? } alert('If you can see this then the script kept going'); </script> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
120,702 | Using Scala's command line REPL: def foo(x: Int): Unit = {}def foo(x: String): Unit = {println(foo(2))} gives error: type mismatch;found: Int(2)required: String It seems that you can't define overloaded recursive methods in the REPL. I thought this was a bug in the Scala REPL and filed it, but it was almost instantly closed with "wontfix: I don't see any way this could be supported given the semantics of the interpreter, because these two methods must to be compiled together." He recommended putting the methods in an enclosing object. Is there a JVM language implementation or Scala expert who could explain why? I can see it would be a problem if the methods called each other for instance, but in this case? Or if this is too large a question and you think I need more prerequisite knowledge, does someone have any good links to books or sites about language implementations, especially on the JVM? (I know about John Rose's blog, and the book Programming Language Pragmatics... but that's about it. :) | The issue is due to the fact that the interpreter most often has to replace existing elements with a given name, rather than overload them. For example, I will often be running through experimenting with something, often creating a method called test : def test(x: Int) = x + x A little later on, let's say that I'm running a different experiment and I create another method named test , unrelated to the first: def test(ls: List[Int]) = (0 /: ls) { _ + _ } This isn't an entirely unrealistic scenario. In fact, it's precisely how most people use the interpreter, often without even realizing it. If the interpreter arbitrarily decided to keep both versions of test in scope, that could lead to confusing semantic differences in using test. For example, we might make a call to test , accidentally passing an Int rather than List[Int] (not the most unlikely accident in the world): test(1 :: Nil) // => 1test(2) // => 4 (expecting 2) Over time, the root scope of the interpreter would get incredibly cluttered with various versions of methods, fields, etc. I tend to leave my interpreter open for days at a time, but if overloading like this were allowed, we would be forced to "flush" the interpreter every so often as things got to be too confusing. It's not a limitation of the JVM or the Scala compiler, it's a deliberate design decision. As mentioned in the bug, you can still overload if you're within something other than the root scope. Enclosing your test methods within a class seems like the best solution to me. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15627/"
]
} |
120,755 | Is the Entity Framework aware of identity columns? I am using SQL Server 2005 Express Edition and have several tables where the primary key is an identity column. when I use these tables to create an entity model and use the model in conjunction with an entity datasource bond to a formview in order to create a new entity I am asked to enter a value for the identity column. Is there a way to make the framework not ask for values for identity columns? | I know this post is quite old, but this may help the next person arriving hear via a Google search for "Entitiy Framework" and "Identity". It seems that Entity Frameworks does respect server-generated primary keys, as the case would be if the "Identity" property is set. However, the application side model still requires a primary key to be supplied in the CreateYourEntityHere method. The key specified here is discarded upon the SaveChanges() call to the context. The page here gives the detailed information regarding this. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/120755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
120,763 | I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command? Instead of this: string filePath = @"C:\somepath\file.txt"; I want to do this: string filePath = @helper.getFilePath(); //getFilePath returns a string This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something? | I don't think you have to worry about it if you already have the value. The @ operator is for when you're specifying the string (like in your first code snippet). What are you attempting to do with the path string that isn't working? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14777/"
]
} |
120,766 | I have several <li> elements with different id's on ASP.NET page: <li id="li1" class="class1"><li id="li2" class="class1"><li id="li3" class="class1"> and can change their class using JavaScript like this: li1.className="class2" But is there a way to change <li> element class using ASP.NET? It could be something like: WebControl control = (WebControl)FindControl("li1");control.CssClass="class2"; But FindControl() doesn't work as I expected. Any suggestions? Thanks in advance! | Add runat="server" in your HTML page then use the attribute property in your asp.Net page like this li1.Attributes["Class"] = "class1";li2.Attributes["Class"] = "class2"; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
]
} |
120,781 | I am a bit confused in what the application controller should do? Because I see the functionality will also exists in your MVP pattern to make the decisions which form should be shown when a button is clicked? Are there any good examples for Windows Forms that uses the application controller pattern? There is a difference in the MVC(ontroler) and the Application Controller. I know the MVC(ontroller), I am not sure what is the responsibilities for an Application Controller, and how does it fit into a WinForms application. Martin Fowler also calls this the Application Controller pattern, surely it is not the same thing as the MVC(ontroller)? | I recently wrote an article on creating and using an ApplicationController in a C# Winforms project, to decouple the workflow and presenters from the forms directly. It may help: Decoupling Workflow And Forms With An Application Controller edit: Archive.org has got a more readable copy of the article at this time. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12230/"
]
} |
120,797 | Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema. I am behind a proxy server. How can I set my JVM to use the proxy ? | From the Java documentation ( not the javadoc API): http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html Set the JVM flags http.proxyHost and http.proxyPort when starting your JVM on the command line.This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script: JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800java ${JAVA_FLAGS} ... When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor. Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: http://download.oracle.com/javase/6/docs/technotes/guides/ Update : If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak: Also don't forget the http.nonProxyHosts property! -Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.example.com|etc" | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/120797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
]
} |
120,804 | I am going through John Resig's excellent Advanced javascript tutorial and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice) >>> arguments [3, 1, 2, 3] >>> Array.slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 >>> Array.slice.call( arguments, 1 ) []>>> Array().slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 >>> Array().slice.call( arguments, 1 ) 1,2,3 0=1 1=2 2=3 Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list). | Not quite. Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2): >>> String.substring.call("foo", 1)"1">>> String().substring.call("foo", 1)"oo" Array.slice is neither properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []). The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. Try running the equivalent code in IE and you'll get an error that Array.slice is null . This is why Array.slice does not behave correctly (nor does String.substring). Proof (the following is something one should never expect based on the definition of slice()...just like substring() above): >>> Array.slice.call([1,2], [3,4])3,4 Now, if you properly call slice() on either an instantiated object or the Array prototype, you'll get what you expect: >>> Array.prototype.slice.call([4,5], 1)[5]>>> Array().slice.call([4,5], 1)[5] More proof... >>> Array.prototype.slice == Array().slicetrue>>> Array.slice == Array().slicefalse | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/120804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21075/"
]
} |
120,851 | We are creating an XBAP application that we need to have rounded corners in various locations in a single page and we would like to have a WPF Rounded Corner container to place a bunch of other elements within. Does anyone have some suggestions or sample code on how we can best accomplish this? Either with styles on a or with creating a custom control? | You don't need a custom control, just put your container in a border element: <Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8"> <Grid/></Border> You can replace the <Grid/> with any of the layout containers... | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/120851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21096/"
]
} |
120,876 | What are the C++ rules for calling the base class constructor from a derived class? For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing). | Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()". class SuperClass{ public: SuperClass(int foo) { // do something with foo }};class SubClass : public SuperClass{ public: SubClass(int foo, int bar) : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list. { // do something with bar }}; More info on the constructor's initialization list here and here . | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/120876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4465/"
]
} |
120,886 | Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by infinite = itertools.cycle([[1,2,3]]) What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc. In the example above it would return 1,2,3,1,2,3,... . The iterator is infinite, so itertools.chain(*infinite) will not work. Related Flattening a shallow list in python | Starting with Python 2.6, you can use itertools.chain.from_iterable : itertools.chain.from_iterable(iterables) You can also do this with a nested generator comprehension: def flatten(iterables): return (elem for iterable in iterables for elem in iterable) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/120886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12166/"
]
} |
120,900 | I'm working on databases that have moving tables auto-generated by some obscure tools. By the way, we have to track information changes in the table via some triggers. And, of course, it occurs that some changes in the table structure broke some triggers, by removing a column or changing its type, for example. So, the question is: Is there a way to query the Oracle metadata to check is some triggers are broken, in order to send a report to the support team? The user_triggers give all the triggers and tells if they are enable or not, but does not indicate if they are still valid. | SELECT *FROM ALL_OBJECTSWHERE OBJECT_NAME = trigger_nameAND OBJECT_TYPE = 'TRIGGER'AND STATUS <> 'VALID' | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9396/"
]
} |
120,917 | How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on D:\temp\dbFolder . How to do this? | When you create the new database you specify the location. For example: USE [master]GO CREATE DATABASE [AdventureWorks] ON PRIMARY ( NAME = N'AdventureWorks_Data', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB ) LOG ON ( NAME = N'AdventureWorks_Log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB ) GO | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/120917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
} |
120,926 | I see on Stack Overflow and PEP 8 that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with. | The answer was given right there in the PEP [ed: this passage has been edited out in 2013 ]. I quote: The most popular way of indenting Python is with spaces only. What other underlying reason do you need? To put it less bluntly: Consider also the scope of the PEP as stated in the very first paragraph: This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. The intention is to make all code that goes in the official python distribution consistently formatted (I hope we can agree that this is universally a Good Thing™). Since the decision between spaces and tabs for an individual programmer is a) really a matter of taste and b) easily dealt with by technical means (editors, conversion scripts, etc.), there is a clear way to end all discussion: choose one. Guido was the one to choose. He didn't even have to give a reason, but he still did by referring to empirical data. For all other purposes you can either take this PEP as a recommendation, or you can ignore it -- your choice, or your team's, or your team leaders. But if I may give you one advice: don't mix'em ;-) [ed: Mixing tabs and spaces is no longer an option.] | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/120926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4834/"
]
} |
120,937 | After reading the Test-and-Set Wikipedia entry , I am still left with the question "What would a Test-and-Set be used for?" I realize that you can use it to implement Mutex (as described in wikipedia), but what other uses does it have? | You use it any time you want to write data to memory after doing some work and make sure another thread hasn't overwritten the destination since you started. A lot of lock/mutex-free algorithms take this form. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
120,941 | I am building a small website for fun/learning using a fairly standard Web/Service/Data Access layered design. For the Data Access Layer, what is the best way to handle creating Connection objects to call my SQL stored procedures and why? Bearing in mind I am writing a lot of the code by hand (I know I could be using Hibernate etc to do a lot of this for me)... 1) Should I create one static instance of the Connection and run all my querys through it or will this cause concurrency problems? 2) Should I create a Connection instance per database call and accept the performance overhead? (I will look into connection pooling at a later date if this is the case) | You use it any time you want to write data to memory after doing some work and make sure another thread hasn't overwritten the destination since you started. A lot of lock/mutex-free algorithms take this form. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
120,951 | I'd like to know do I normalize a URL in python. For example, If I have a url string like : " http://www.example.com/foo goo/bar.html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL. | Have a look at this module: werkzeug.utils . (now in werkzeug.urls ) The function you are looking for is called "url_fix" and works like this: >>> from werkzeug.urls import url_fix>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29' It's implemented in Werkzeug as follows: import urllibimport urlparsedef url_fix(s, charset='utf-8'): """Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)') 'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29' :param charset: The target charset for the URL if the url was given as unicode string. """ if isinstance(s, unicode): s = s.encode(charset, 'ignore') scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor)) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/120951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
]
} |
120,957 | What features of C++ should be avoided in embedded systems? Please classify the answer by reason such as: memory usage code size speed portability EDIT: Lets' use an ARM7TDMI with 64k ram as a target to control the scope of the answers. | RTTI and Exception Handling: Increases code-size Decreases performance Can often be replaced by cheaper mechanisms or a better software-design. Templates: be careful with them if code-size is an issue. If your target CPU has no or only a very tiny ínstruction cache it may reduce the performance as well. (templates tend to bloat code if used without care). Otoh clever meta-programming can decrease the code-size as well. There is no clear cut answer on his. Virtual functions and inheritance: These are fine for me. I write almost all of my embedded code in C. That does not stop me from using function-pointer tables to mimic virtual functions. They never became a peformance problem. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
]
} |
120,997 | I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags? For example, when you create an asp:repeater you can add a nested tag for itemtemplate . | I wrote a blog post about this some time ago. In brief, if you had a control with the following markup: <Abc:CustomControlUno runat="server" ID="Control1"> <Children> <Abc:Control1Child IntegerProperty="1" /> </Children></Abc:CustomControlUno> You'd need the code in the control to be along the lines of: [ParseChildren(true)][PersistChildren(true)][ToolboxData("<{0}:CustomControlUno runat=server></{0}:CustomControlUno>")]public class CustomControlUno : WebControl, INamingContainer{ private Control1ChildrenCollection _children; [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Control1ChildrenCollection Children { get { if (_children == null) { _children = new Control1ChildrenCollection(); } return _children; } }}public class Control1ChildrenCollection : List<Control1Child>{}public class Control1Child{ public int IntegerProperty { get; set; }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/120997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11508/"
]
} |
121,018 | I know there are emulators, but is this good enough? If someone is serious about iPhone development, do they absolutely need an iPhone? | Just my personal opinion: if you're serious it means that you're committed to quality of your product. If you're committed to quality there is no way to deliver a product without actually launching it on the target platform :) As noted in other posts you'll have tough time testing the multi-touch screen and other aspects of the hardware on your emulator. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/121018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
121,025 | How do I get the modified date/time of a file in Python? | os.path.getmtime(filepath) or os.stat(filepath).st_mtime | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
]
} |
121,066 | I want to attach a click event to a button element and then later remove it, but I can't get unclick() or unbind() event(s) to work as expected. In the code below, the button is tan colour and the click event works. window.onload = init; function init() { $("#startButton").css('background-color', 'beige').click(process_click); $("#startButton").css('background-color', 'tan').unclick();} How can I remove events from my elements? | There's no such thing as unclick() . Where did you get that from? You can remove individual event handlers from an element by calling unbind: $("#startButton").unbind("click", process_click); If you want to remove all handlers, or you used an anonymous function as a handler, you can omit the second argument to unbind() : $("#startButton").unbind("click"); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
} |
121,105 | Changing a value prompt to a multi-select value prompt in Report studio, provide single select functionality. How can i get multi-select functionality? | Look at the parameter associated with the prompt. Now go look and see how you use that parameter to filter the queries in your report. If you have the filter set as:- [namespace].[table].[column] = ?MyParameter? ... then it doesn't matter that your prompt is a multi-select prompt, it will still run as a single selection prompt. Modify your filters so they are of the form:- [namespace].[table].[column] in ?MyParameter? This tells Cognos that your parameter can contain multiple values, and it will display the prompt accordingly. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
121,116 | I have a managed DLL (written in C++/CLI) that contains a class used by a C# executable. In the constructor of the class, I need to get access to the full path of the executable referencing the DLL. In the actual app I know I can use the Application object to do this, but how can I do it from a managed DLL? | Assembly.GetCallingAssembly() or Assembly.GetExecutingAssembly() or Assembly.GetEntryAssembly() Depending on your need. Then use Location or CodeBase property (I never remember which one). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
]
} |
121,162 | What does the explicit keyword mean in C++? | The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter. Here's an example class with a constructor that can be used for implicit conversions: class Foo{private: int m_foo;public: // single parameter constructor, can be used as an implicit conversion Foo (int foo) : m_foo (foo) {} int GetFoo () { return m_foo; }}; Here's a simple function that takes a Foo object: void DoBar (Foo foo){ int i = foo.GetFoo ();} and here's where the DoBar function is called: int main (){ DoBar (42);} The argument is not a Foo object, but an int . However, there exists a constructor for Foo that takes an int so this constructor can be used to convert the parameter to the correct type. The compiler is allowed to do this once for each parameter. Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar (42) . It is now necessary to call for conversion explicitly with DoBar (Foo (42)) The reason you might want to do this is to avoid accidental construction that can hide bugs. Contrived example: You have a MyString class with a constructor that constructs a string of the given size. You have a function print(const MyString&) (as well as an overload print (char *string) ), and you call print(3) (when you actually intended to call print("3") ). You expect it to print "3", but it prints an empty string of length 3 instead. | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/121162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1898/"
]
} |
121,199 | How is it possible in Eclipse JDT to convert a multiline selection to String. Like the following From: xxxxyyyyzzz To: "xxxx " +"yyyy " +"zzz" I tried the following template "${line_selection}${cursor}"+ but that way I only get the whole block surrounded not each line separately. How can I achieve a multiline processing like commenting the selected block? | Maybe this is not what you mean but... If I'm on a line in Eclipse and I enter double quotation marks, then inside that paste a multiline selection (like your xyz example) it will paste out like this: "xxxx\n" + "yyyy\n" + "zzz" Then you could just find/replace in a selection for "\n" to "" , if you didn't intend the newlines. I think the option to enable this is in Window/Preferences , under Java/Editor/Typing/ , check the box next to "Escape text when pasting into a string literal" . ( Eclipse 3.4 Ganymede ) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
121,203 | There was a post this morning asking about how many people disable JavaScript. Then I began to wonder what techniques might be used to determine if the user has it disabled. Does anyone know of some short/simple ways to detect if JavaScript is disabled? My intention is to give a warning that the site is not able to function properly without the browser having JS enabled. Eventually I would want to redirect them to content that is able to work in the absence of JS, but I need this detection as a placeholder to start. | I assume you're trying to decide whether or not to deliver JavaScript-enhanced content. The best implementations degrade cleanly, so that the site will still operate without JavaScript. I also assume that you mean server-side detection, rather than using the <noscript> element for an unexplained reason. There is no good way to perform server-side JavaScript detection. As an alternative it is possible to set a cookie using JavaScript , and then test for that cookie using server-side scripting upon subsequent page views. However this would be unsuitable for deciding what content to deliver, as it would not distinguish visitors without the cookie from new visitors or from visitors who did not accept the JavaScript set cookie. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/121203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
]
} |
121,218 | Is it possible to detect the HTTP request method (e.g. GET or POST) of a page from JavaScript? If so, how? | In a word - No | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
]
} |
121,237 | I would like to convert a string into a node. I have a method that is defined to take a node, but the value I have is a string (it is hard coded). How do I turn that string into a node? So, given an XQuery method: define function foo($bar as node()*) as node() { (: unimportant details :)} I have a string that I want to pass to the foo method. How do I convert the string to a node so that the method will accept the string. | MarkLogic solutions: The best way to convert a string into a node is to use: xdmp:unquote($string). Conversely if you want to convert a node into a string you would use: xdmp:quote($node). Language agnostic solutions: Node to string is: fn:string($node) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
]
} |
121,240 | What is the best (cleanest, most efficient) way to write saturating addition in C? The function or macro should add two unsigned inputs (need both 16- and 32-bit versions) and return all-bits-one (0xFFFF or 0xFFFFFFFF) if the sum overflows. Target is x86 and ARM using gcc (4.1.2) and Visual Studio (for simulation only, so a fallback implementation is OK there). | You probably want portable C code here, which your compiler will turn into proper ARM assembly. ARM has conditional moves, and these can be conditional on overflow. The algorithm then becomes: add and conditionally set the destination to unsigned(-1), if overflow was detected. uint16_t add16(uint16_t a, uint16_t b){ uint16_t c = a + b; if (c < a) /* Can only happen due to overflow */ c = -1; return c;} Note that this differs from the other algorithms in that it corrects overflow, instead of relying on another calculation to detect overflow. x86-64 clang 3.7 -O3 output for adds32 : significantly better than any other answer: add edi, esimov eax, -1cmovae eax, ediret ARMv7: gcc 4.8 -O3 -mcpu=cortex-a15 -fverbose-asm output for adds32 : adds r0, r0, r1 @ c, a, bit csmovcs r0, #-1 @ conditional-movebx lr 16bit: still doesn't use ARM's unsigned-saturating add instruction ( UADD16 ) add r1, r1, r0 @ tmp114, amovw r3, #65535 @ tmp116,uxth r1, r1 @ c, tmp114cmp r0, r1 @ a, cite ls @movls r0, r1 @,, cmovhi r0, r3 @,, tmp116bx lr @ | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8964/"
]
} |
121,243 | What are some hidden features of SQL Server ? For example, undocumented system stored procedures, tricks to do things which are very useful but not documented enough? Answers Thanks to everybody for all the great answers! Stored Procedures sp_msforeachtable: Runs a command with '?' replaced with each table name (v6.5 and up) sp_msforeachdb: Runs a command with '?' replaced with each database name (v7 and up) sp_who2: just like sp_who, but with a lot more info for troubleshooting blocks (v7 and up) sp_helptext: If you want the code of a stored procedure, view & UDF sp_tables: return a list of all tables and views of database in scope. sp_stored_procedures: return a list of all stored procedures xp_sscanf: Reads data from the string into the argument locations specified by each format argument. xp_fixeddrives: : Find the fixed drive with largest free space sp_help: If you want to know the table structure, indexes and constraints of a table. Also views and UDFs. Shortcut is Alt+F1 Snippets Returning rows in random order All database User Objects by Last Modified Date Return Date Only Find records which date falls somewhere inside the current week. Find records which date occurred last week. Returns the date for the beginning of the current week. Returns the date for the beginning of last week. See the text of a procedure that has been deployed to a server Drop all connections to the database Table Checksum Row Checksum Drop all the procedures in a database Re-map the login Ids correctly after restore Call Stored Procedures from an INSERT statement Find Procedures By Keyword Drop all the procedures in a database Query the transaction log for a database programmatically. Functions HashBytes() EncryptByKey PIVOT command Misc Connection String extras TableDiff.exe Triggers for Logon Events (New in Service Pack 2) Boosting performance with persisted-computed-columns (pcc). DEFAULT_SCHEMA setting in sys.database_principles Forced Parameterization Vardecimal Storage Format Figuring out the most popular queries in seconds Scalable Shared Databases Table/Stored Procedure Filter feature in SQL Management Studio Trace flags Number after a GO repeats the batch Security using schemas Encryption using built in encryption functions, views and base tables with triggers | In Management Studio, you can put a number after a GO end-of-batch marker to cause the batch to be repeated that number of times: PRINT 'X'GO 10 Will print 'X' 10 times. This can save you from tedious copy/pasting when doing repetitive stuff. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/121243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
]
} |
121,251 | My quick search reveals the reference implementation ( http://stax.codehaus.org ), the Woodstox implementation ( http://woodstox.codehaus.org ), and Sun's SJSXP implementation ( https://sjsxp.dev.java.net/ ). Please comment on the relative merits of these, and fill me in on any other implementations I should consider. | Woodstox wins every time for me. It's not just performance, either - sjsxp is twitchy and overly pedantic, woodstox just gets on with it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15988/"
]
} |
121,266 | I'm currently looking for ways to create automated tests for a JAX-RS (Java API for RESTful Web Services) based web service. I basically need a way to send it certain inputs and verify that I get the expected responses. I'd prefer to do this via JUnit, but I'm not sure how that can be achieved. What approach do you use to test your web-services? Update: As entzik pointed out, decoupling the web service from the business logic allows me to unit test the business logic. However, I also want to test for the correct HTTP status codes etc. | Jersey comes with a great RESTful client API that makes writing unit tests really easy. See the unit tests in the examples that ship with Jersey. We use this approach to test the REST support in Apache Camel , if you are interested the test cases are here | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2964/"
]
} |
121,274 | How would I go about binding the following object, Car, to a gridview? public class Car{ long Id {get; set;} Manufacturer Maker {get; set;}}public class Manufacturer{ long Id {get; set;} String Name {get; set;}} The primitive types get bound easy but I have found no way of displaying anything for Maker. I would like for it to display the Manufacturer.Name. Is it even possible? What would be a way to do it? Would I have to store ManufacturerId in Car as well and then setup an lookupEditRepository with list of Manufacturers? | Allright guys... This question was posted waaay back but I just found a fairly nice & simple way to do this by using reflection in the cell_formatting event to go retrieve the nested properties. Goes like this: private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { DataGridView grid = (DataGridView)sender; DataGridViewRow row = grid.Rows[e.RowIndex]; DataGridViewColumn col = grid.Columns[e.ColumnIndex]; if (row.DataBoundItem != null && col.DataPropertyName.Contains(".")) { string[] props = col.DataPropertyName.Split('.'); PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]); object val = propInfo.GetValue(row.DataBoundItem, null); for (int i = 1; i < props.Length; i++) { propInfo = val.GetType().GetProperty(props[i]); val = propInfo.GetValue(val, null); } e.Value = val; } } And that's it! You can now use the familiar syntax "ParentProp.ChildProp.GrandChildProp" in the DataPropertyName for your column. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
]
} |
121,282 | If I do something like: $ cat /bin/ls into my terminal, I understand why I see a bunch of binary data, representing the ls executable. But afterwards, when I get my prompt back, my own keystrokes look crazy. I type "a" and I get a weird diagonal line. I type "b" and I get a degree symbol. Why does this happen? | Because somewhere in your binary data were some control sequences that your terminal interpreted as requests to, for example, change the character set used to draw. You can restore everything to normal like so: reset | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
} |
121,324 | I'm looking for a framework to generate Java source files. Something like the following API: X clazz = Something.createClass("package name", "class name");clazz.addSuperInterface("interface name");clazz.addMethod("method name", returnType, argumentTypes, ...);File targetDir = ...;clazz.generate(targetDir); Then, a java source file should be found in a sub-directory of the target directory. Does anyone know such a framework? EDIT : I really need the source files. I also would like to fill out the code of the methods. I'm looking for a high-level abstraction, not direct bytecode manipulation/generation. I also need the "structure of the class" in a tree of objects. The problem domain is general: to generate a large amount of very different classes, without a "common structure". SOLUTIONS I have posted 2 answers based in your answers... with CodeModel and with Eclipse JDT . I have used CodeModel in my solution, :-) | Sun provides an API called CodeModel for generating Java source files using an API. It's not the easiest thing to get information on, but it's there and it works extremely well. The easiest way to get hold of it is as part of the JAXB 2 RI - the XJC schema-to-java generator uses CodeModel to generate its java source, and it's part of the XJC jars. You can use it just for the CodeModel. Grab it from http://codemodel.java.net/ | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/121324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16135/"
]
} |
121,326 | What does it mean when it gives a backtrace with the following output? #0 0x00000008009c991c in pthread_testcancel () from /lib/libpthread.so.2#1 0x00000008009b8120 in sigaction () from /lib/libpthread.so.2#2 0x00000008009c211a in pthread_mutexattr_init () from /lib/libpthread.so.2#3 0x0000000000000000 in ?? () The program has crashed with a standard signal 11, segmentation fault.My application is a multi-threaded FastCGI C++ program running on FreeBSD 6.3, using pthread as the threading library. It has been compiled with -g and all the symbol tables for my source are loaded, according to info sources. As is clear, none of my actual code appears in the trace but instead the error seems to originate from standard pthread libraries. In particular, what is ?? () ???? EDIT : eventually tracked the crash down to a standard invalid memory access in my main code. Doesn't explain why the stack trace was corrupted, but that's a question for another day :) | gdb wasn't able to extract the proper return address from pthread_mutexattr_init; it got an address of 0. The "??" is the result of looking up address 0 in the symbol table. It cannot find a symbolic name, so it prints a default "??" Unfortunately right offhand I don't know why it could not extract the correct return address. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10264/"
]
} |
121,382 | Is there a way to comment out markup in an .ASPX page so that it isn't delivered to the client? I have tried the standard comments <!-- --> but this just gets delivered as a comment and doesn't prevent the control from rendering. | <%-- Commented out HTML/CODE/Markup. Anything with this block will not be parsed/handled by ASP.NET. <asp:Calendar runat="server"></asp:Calendar> <%# Eval(“SomeProperty”) %> --%> Source | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/121382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
]
} |
121,385 | What makes a language strongly typed? I'm looking for the most important aspects of a strongly typed language. Yesterday I asked if PowerShell was strongly typed, but no one could agree on the definition of "strongly-typed", so I'm looking to clarify the definition. Feel free to link to wikipedia or other sources, but don't just cut and paste for your answer. | The term "strongly typed" has no agreed-upon definition. It makes a "great" argument in a flamewar, because whenever someone is proven wrong, they can just redefine it to mean whatever they want it to mean. Other than that, the term serves no real purpose. It is best to just not use the term, or, if you use it, rigorously define it first. If you see someone else use it, ask him to define the term. Everybody has their own definition. Some that I have seen are: strongly typed = statically typed strongly typed = explicitly typed strongly typed = nominally typed strongly typed = typed strongly typed = has no implicit typecasts, only explicit strongly typed = has no typecasts at all strongly typed = what I understand / weakly typed = what I don't understand strongly typed = C++ / weakly typed = everything else strongly typed = Java / weakly typed = everything else strongly typed = .NET / weakly typed = everything else strongly typed = my programming language / weakly typed = your programming language In Type Theory, there exists the notion of one type system being stronger than another. In particular, if there exists an expression e1 such that it is accepted by a type system T1 , but rejected by a type system T2 , then T2 is said to be stronger than T1 . There are two important things to note here: this a comparative, not an absolute: there is no strong or weak , only stronger and weaker there is no value implied by the term; stronger does not mean better | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289/"
]
} |
121,387 | Table: UserId, Value, Date. I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date. Is there a way to do this simply in SQL? (Preferably Oracle) Update: Apologies for any ambiguity: I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date. | This will retrieve all rows for which the my_date column value is equal to the maximum value of my_date for that userid. This may retrieve multiple rows for the userid where the maximum date is on multiple rows. select userid, my_date, ...from(select userid, my_date, ... max(my_date) over (partition by userid) max_my_datefrom users)where my_date = max_my_date "Analytic functions rock" Edit: With regard to the first comment ... "using analytic queries and a self-join defeats the purpose of analytic queries" There is no self-join in this code. There is instead a predicate placed on the result of the inline view that contains the analytic function -- a very different matter, and completely standard practice. "The default window in Oracle is from the first row in the partition to the current one" The windowing clause is only applicable in the presence of the order by clause. With no order by clause, no windowing clause is applied by default and none can be explicitly specified. The code works. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/121387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21154/"
]
} |
121,392 | I have a bunch (hundreds) of files that are supposed to have Unix line endings. I strongly suspect that some of them have Windows line endings, and I want to programmatically figure out which ones do. I know I can just run flip -u or something similar in a script to convert everything, but I want to be able to identify those files that need changing first. | You can use the file tool, which will tell you the type of line ending. Or, you could just use dos2unix -U which will convert everything to Unix line endings, regardless of what it started with. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18177/"
]
} |
121,396 | When you call the object.__repr__() method in Python you get something like this back: <__main__.Test object at 0x2aba1c0cf890> Is there any way to get a hold of the memory address if you overload __repr__() , other then calling super(Class, obj).__repr__() and regexing it out? | The Python manual has this to say about id() : Return the "identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.) So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though. Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/121396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452521/"
]
} |
121,439 | I'm running Django 1.0 and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False. With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers. Any thoughts on how best to approach this issue? | Automatically log your 500s, that way: You know when they occur. You don't need to rely on users sending you stacktraces. Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktraces, urls, etc. that the developers can subscribe to. Showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site. Overly detailed error messages are one of the classic stepping stones to SQL injection attacks. Edit (added code sample to capture traceback): You can get the exception information from the sys.exc_info call. While formatting the traceback for display comes from the traceback module: import tracebackimport systry: raise Exception("Message")except: type, value, tb = sys.exc_info() print >> sys.stderr, type.__name__, ":", value print >> sys.stderr, '\n'.join(traceback.format_tb(tb)) Prints: Exception : Message File "exception.py", line 5, in <module> raise Exception("Message") | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
]
} |
121,499 | Suppose I attach an blur function to an HTML input box like this: <input id="myInput" onblur="function() { ... }"></input> Is there a way to get the ID of the element which caused the blur event to fire (the element which was clicked) inside the function? How? For example, suppose I have a span like this: <span id="mySpan">Hello World</span> If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was mySpan that was clicked? PS: If the onclick event of the span would occur before the onblur event of the input element my problem would be solved, because I could set some status value indicating a specific element had been clicked. PPS: The background of this problem is that I want to trigger an AJAX autocompleter control externally (from a clickable element) to show its suggestions, without the suggestions disappearing immediately because of the blur event on the input element. So I want to check in the blur function if one specific element has been clicked, and if so, ignore the blur event. | Hmm... In Firefox, you can use explicitOriginalTarget to pull the element that was clicked on. I expected toElement to do the same for IE, but it does not appear to work... However, you can pull the newly-focused element from the document: function showBlur(ev){ var target = ev.explicitOriginalTarget||document.activeElement; document.getElementById("focused").value = target ? target.id||target.tagName||target : '';}...<button id="btn1" onblur="showBlur(event)">Button 1</button><button id="btn2" onblur="showBlur(event)">Button 2</button><button id="btn3" onblur="showBlur(event)">Button 3</button><input id="focused" type="text" disabled="disabled" /> Caveat: This technique does not work for focus changes caused by tabbing through fields with the keyboard, and does not work at all in Chrome or Safari. The big problem with using activeElement (except in IE) is that it is not consistently updated until after the blur event has been processed, and may have no valid value at all during processing! This can be mitigated with a variation on the technique Michiel ended up using : function showBlur(ev){ // Use timeout to delay examination of activeElement until after blur/focus // events have been processed. setTimeout(function() { var target = document.activeElement; document.getElementById("focused").value = target ? target.id||target.tagName||target : ''; }, 1);} This should work in most modern browsers (tested in Chrome, IE, and Firefox), with the caveat that Chrome does not set focus on buttons that are clicked (vs. tabbed to). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/121499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6264/"
]
} |
121,511 | I have inherited a poorly written web application that seems to have errors when it tries to read in an xml document stored in the database that has an "&" in it. For example there will be a tag with the contents: "Prepaid & Charge". Is there some secret simple thing to do to have it not get an error parsing that character, or am I missing something obvious? EDIT:Are there any other characters that will cause this same type of parser error for not being well formed? | The problem is the xml is not well-formed. Properly generated xml would list the data like this: Prepaid & Charge I've fixed the same problem before, and I did it with this regex: Regex badAmpersand = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)"); Combine that with a string constant defined like this: const string goodAmpersand = "&"; Now you can say badAmpersand.Replace(<your input>, goodAmpersand); Note a simple String.Replace("&", "&") isn't good enough, since you can't know in advance for a given document whether any & characters will be coded correctly, incorrectly, or even both in the same document. The catches here are you have to do this to your xml document before loading it into your parser, which likely means an extra pass through the document. Also, it does not account for ampersands inside of a CDATA section. Finally, it only catches ampersands, not other illegal characters like <. Update: based on the comment, I need to update the expression for hex-coded (&#x...;) entities as well. Regarding which characters can cause problems, the actual rules are a little complex. For example, certain characters are allowed in data, but not as the first letter of an element name. And there's no simple list of illegal characters. Instead, large (non-contiguous) swaths of UNICODE are defined as legal , and anything outside that is illegal. When it comes down to it, you have to trust your document source to have at least a certain amount of compliance and consistency. For example, I've found people are often smart enough to make sure the tags work properly and escape <, even if they don't know that & isn't allowed, hence your problem today. However, the best thing would be to get this fixed at the source. Oh, and a note about the CDATA suggestion: I use that to make sure xml I'm creating is well-formed, but when dealing with existing xml from outside, I find the regex method easier. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13593/"
]
} |
121,579 | I don't know if anyone has seen this issue before but I'm just stumped. Here's the unhandled exception message that my error page is capturing. Error Message: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. Stack Trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.generic_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Source: System.Web Anybody have any ideas on how I could resolve this? Thanks. | I seem to recall that this error can occur if you click a button/link etc before the page has fully loaded. If this is the case, the error is caused by an ASP.net 2.0 feature called Event Validation. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered form tag, you'll see something like this: <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AEBnx7v.........tS" /> When a postback occurs, ASP.net uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception that you've been seeing. The problem you're seeing happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.net cannot validate your click. One work around is of course to just disable event validation, but you have to be aware of the security implications. Alternatively, just never post back before the form has finished rendering. Of course, that's hard to tell your users, but perhaps you could disable the UI until the form has rendered? from http://forums.asp.net/p/955145/1173230.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21165/"
]
} |
121,581 | In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar) | Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0) To run this on a column, replace GetDate() with your column name. The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8479/"
]
} |
121,599 | We're looking at CouchdDB for a CMS-ish application. What are some common patterns, best practices and workflow advice surrounding backing up our production database? I'm particularly interested in the process of cloning the database for use in development and testing. Is it sufficient to just copy the files on disk out from under a live running instance? Can you clone database data between two live running instances? Advice and description of the techniques you use will be greatly appreciated. | CouchDB supports replication, so just replicate to another instance of CouchDB and backup from there, avoiding disturbing where you write changes to. https://docs.couchdb.org/en/latest/maintenance/backups.html You literally send a POST request to your CouchDB instance telling it where to replicate to, and it Works(tm) EDIT: You can just cp out the .couch files in the data directory from under the running database as long as you can accept the I/O hit. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
} |
121,605 | What is the best way to reduce the size of the viewstate hidden field in JSF?I have noticed that my view state is approximately 40k this goes down to the client and back to the server on every request and response espically coming to the server this is a significant slowdown for the user. My Environment JSF 1.2, MyFaces, Tomcat, Tomahawk, RichFaces | Have you tried setting the state saving to server? This should only send an id to the client, and keep the full state on the server. Simply add the following to the file web.xml : <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>server</param-value> </context-param> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12148/"
]
} |
121,631 | Is there a difference in performance (in oracle) between Select * from Table1 T1 Inner Join Table2 T2 On T1.ID = T2.ID And Select * from Table1 T1, Table2 T2 Where T1.ID = T2.ID ? | No! The same execution plan, look at these two tables: CREATE TABLE table1 ( id INT, name VARCHAR(20));CREATE TABLE table2 ( id INT, name VARCHAR(20)); The execution plan for the query using the inner join: -- with inner joinEXPLAIN PLAN FORSELECT * FROM table1 t1INNER JOIN table2 t2 ON t1.id = t2.id;SELECT *FROM TABLE (DBMS_XPLAN.DISPLAY);-- 0 select statement-- 1 hash join (access("T1"."ID"="T2"."ID"))-- 2 table access full table1-- 3 table access full table2 And the execution plan for the query using a WHERE clause. -- with where clauseEXPLAIN PLAN FORSELECT * FROM table1 t1, table2 t2WHERE t1.id = t2.id;SELECT *FROM TABLE (DBMS_XPLAN.DISPLAY);-- 0 select statement-- 1 hash join (access("T1"."ID"="T2"."ID"))-- 2 table access full table1-- 3 table access full table2 | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/121631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
]
} |
121,665 | How does one invoke a groovy method that prints to stdout, appending the output to a string? | This demonstrates how you can do this. Paste this into a Groovy script file and run it. You will see the first call functions as normal. The second call produces no results. Finally, the last step in the main prints the results of the second call that were redirected to a ByteArrayOutputStream. Have fun! void doSomething() { println "i did something"}println "normal call\n---------------"doSomething()println ""def buf = new ByteArrayOutputStream()def newOut = new PrintStream(buf)def saveOut = System.outprintln "redirected call\n---------------"System.out = newOutdoSomething()System.out = saveOutprintln ""println "results of call\n---------------"println buf.toString() | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
121,674 | The CPU architecture landscape has changed, multiple cores is a trend that will change how we have to develop software. I've done multi-threaded development in C, C++ and Java, I've done multi-process development using various IPC mechanisms. Traditional approaches of using threads doesn't seem to make it easy, for the developer, to utilize hardware that supports a high degree of concurrency. What languages, libraries and development techniques are you aware of that help alleviate the traditional challenges of creating concurrent applications? I'm obviously thinking of issues like deadlocks and race conditions. Design techniques, libraries, tools, etc. are also interesting that help actually take advantage of and ensure that the available resources are being utilized - just writing a safe, robust threaded application doesn't ensure that it's using all the available cores. What I've seen so far is: Erlang : process based, message passing IPC, the 'actor's model of concurrency Dramatis : actors model library for Ruby and Python Scala : functional programming language for the JVM with some added concurrency support Clojure : functional programming language for the JVM with an actors library Termite : a port of Erlang's process approach and message passing to Scheme What else do you know about, what has worked for you and what do you think is interesting to watch? | I'd suggest two paradigm shifts: Software Transactional Memory You may want to take a look at the concept of Software Transactional Memory (STM). The idea is to use optimistic concurrency : any operation that runs in parallel to others try to complete its job in an isolated transaction; if at some point another transaction has been committed that invalidates data on which this transaction is working, the transaction's work is throwed away and the transaction run again. I think the first widely known implementation of the idea (if not the proof-of-concept and first one) is the one in Haskell : Papers and presentations about transactional memory in Haskell . Many other implementations are listed on Wikipedia's STM article . Event loops and promises Another very different way of dealing with concurrency is implemented in the [E programming language]( http://en.wikipedia.org/wiki/E_(programming_language%29) . Note that its way of dealing with concurrency, as well as other parts of the language design, is heavily based on the Actor model. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
} |
121,680 | I am 90% sure I saw this answer on stackoverflow before, in fact I had never seen the "int?" syntax before seeing it here, but no matter how I search I can't find the previous post, and it's driving me crazy. It's possible that I've been eating the funny mushrooms by accident, but if I'm not, can someone please point out the previous post if they can find it or re-explain it? My stackoverflow search-fu is apparently too low.... | int? is shorthand for Nullable<int> . This may be the post you were looking for. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/121680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8151/"
]
} |
121,722 | string percentage = e.Row.Cells[7].Text; I am trying to do some dynamic stuff with my GridView, so I have wired up some code to the RowDataBound event. I am trying to get the value from a particular cell, which is a TemplateField. But the code above always seems to be returning an empty string. Any ideas? To clarify, here is a bit the offending cell: <asp:TemplateField HeaderText="# Percentage click throughs"><ItemTemplate> <%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %></ItemTemplate></asp:TemplateField> On a related note, does anyone know if there is a better way of selecting the cell in the row. It sucks putting in cell[1] . Couldn't I do cell["mycellname"] , so if I decide to change the order of my cells, bugs wont appear? | why not pull the data directly out of the data source. DataBinder.Eval(e.Row.DataItem, "ColumnName") | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3193/"
]
} |
121,757 | I doubt it can be done portably, but are there any solutions out there? I think it could be done by creating an alternate stack and reseting SP,BP, and IP on function entry, and having yield save IP and restore SP+BP. Destructors and exception safety seem tricky but solvable. Has it been done? Is it impossible? | Yes it can be done without a problem. All you need is a little assembly code to move the call stack to a newly allocated stack on the heap. I would look at the boost::coroutine library . The one thing that you should watch out for is a stack overflow. On most operating systems overflowing the stack will cause a segfault because virtual memory page is not mapped. However if you allocate the stack on the heap you don't get any guarantee. Just keep that in mind. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/121757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19193/"
]
} |
121,762 | I have two threads in an Android application, one is the view thread, and the other is the worker thread. What I want to do is, sleep the worker thread until the view thread terminates the handling of the onDraw method. How i can do this? is there any wait for the signal or something? | Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can continue its work. Whenever the worker thread reaches a point where it should sleep, it does this: stick.wait(); When the view thread finishes its onDraw work, it calls this: stick.notify(); Note the requirement that the view thread owns the monitor on the object. In your case, this should be fairly simple to enforce with a small sync block: void onDraw() { ... synchronized (stick) { stick.notify(); }} // end onDraw() Consult the javadoc for java.lang.Object on these methods (and notifyAll, just in case); they're very well written. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7363/"
]
} |
121,795 | My question is, which version-naming scheme should be used for what type of project. Very common is major.minor.fix, but even this can lead to 4 number (i.e. Firefox 2.0.0.16). Some have a model that odd numbers indicate developer-versions and even numbers stable releases. And all sorts of additions can enter the mix, like -dev3, -rc1, SP2 etc. Exists reasons to prefer one scheme over another and should different type of projects (i.e. Open Source vs. Closed Source) have different version naming schemes? | There are two good answers for this (plus a lot of personal preferences; see gizmo's comment on religious wars). For public applications, the standard Major.Minor.Revision.Build works best IMO - public users can easily tell what version of the program they have and, to some degree, how far out of date their version is. For in house applications, where the users never asked for the application, the deployment is handled by IT, and users will be calling the help desk, I found the Year.Month.Day.Build to work better in a lot of situations. This version number can thus be decoded to provide more useful information to the help desk than the public versioning number scheme. However at the end of the day I would make one recommendation above all else - use a system you can keep consistent . If there is a system that you can setup/script your compiler to automatically use everytime, use that . The worst thing that can happen is you releasing binaries with the same version number as the previous ones - I've recently been dealing with automated network error reports (someone elses application), and came to the conclusion that the Year.Month.Day.Build version numbers shown in the core dumps where not even remotely up to date with the application itself (the application itself used a splash screen with the real numbers - which of course where not drawn from the binary as one might assume). The result is I have no way of knowing if crash dumps are coming from a 2 year old binary (what the version number indicates) or a 2 month old binary, and thus no way of getting the right source code (no source control either!) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/121795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
]
} |
121,817 | I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available. <div id="panel"> <div id="field_name">TEXT GOES HERE</div></div> Here's what the function will look like: function showPanel(fieldName) { var fieldNameElement = document.getElementById('field_name'); //Make replacement here} | You can simply use: fieldNameElement.innerHTML = "My new text!"; | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/121817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
]
} |
121,847 | I hear logarithms mentioned quite a lot in the programming context. They seem to be the solution to many problems and yet I can't seem to find a real-world way of making use of them. I've read the Wikipedia entry and that, quite frankly, leaves me none the wiser. So, where can I learn about the real-world programming problems that logarithms solve? Has anyone got any examples of problems they faced that were solved by implementing a logarithm? | Say you've got $1000, and it's in a savings account with 2.4% interest. How many years do you have to wait until you have $2000 to buy a new laptop? 1000 × 1.024 x = 2000 1.024 x = 2 x = log 1.024 2 = 29.23 years | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
]
} |
121,849 | I'm not sure how I should express this, but I'll give it a try. I recently started coding my portfolio in object-oriented PHP and I'm wondering if it's according to best practices to use a single page where the content changes depending on SQL data and the $_GET variable? If so/not, why? Edit: Take a look at my next post, more in-depth details. | Are you asking about using the front controller pattern, where a single file serves all of your requests? Often this is done with an index.php and mod_rewrite getting all of the requests with the rest of the URL being given to it as a parameter in the query string. http://www.onlamp.com/pub/a/php/2004/07/08/front_controller.html I would tend to recommend this pattern be used for applications, because it gives you a single place to handle things like authentication, and often you'll need to integrate things at a tighter level where having new features be classes that are registered with the controller via some mechanism makes a lot of sense. The concerns about the URLs others have mentioned aren't really accurate, because there is no real relationship between URL structure and file structure, unless you're using ancient techniques of building websites. A good chunk of apache functionality is based on the concept that file/directory structure and URL structure are distinct concepts (alias module, rewrite module, content negotiation, so on and so forth) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348430/"
]
} |
121,864 | As compared to say: REPLICATE(@padchar, @len - LEN(@str)) + @str | This is simply an inefficient use of SQL, no matter how you do it. perhaps something like right('XXXXXXXXXXXX'+ rtrim(@str), @n) where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length). But as I said you should really avoid doing this in your database. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/121864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18255/"
]
} |
121,866 | I'm preparing to deploy my Django app and I noticed that when I change the "DEBUG" setting to False, all references to static files (i.e., JavaScript, CSS, etc..) result in HTTP 500 errors. Any idea what's causing that issue (and how to fix it)? | I would highly recommend letting your web server handle the static requests, without getting to Django. In my urls.py , I only add the static request handler when debug is set to True. Technically, Django serving the static works fine though. Definitely read the short docs page, http://docs.djangoproject.com/en/dev/howto/static-files/ . You'll want to use an entry like this in urls.py (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
]
} |
121,962 | How can I consistently get the absolute, fully-qualified root or base url of the site regardless of whether the site is in a virtual directory and regardless of where my code is in the directory structure? I've tried every variable and function I can think of and haven't found a good way. I want to be able to get the url of the current site, i.e. http://www.example.com or if it's a virtual directory, http://www.example.com/DNN/ Here's some of the things I've tried and the result. The only one that includes the whole piece that I want ( http://localhost:4471/DNN441 ) is Request.URI.AbsoluteURI: Request.PhysicalPath: C:\WebSites\DNN441\Default.aspx Request.ApplicationPath: /DNN441 Request.PhysicalApplicationPath: C:\WebSites\DNN441\ MapPath:C:\WebSites\DNN441\DesktopModules\Articles\Templates\Default.aspx RawURL:/DNN441/ModuleTesting/Articles/tabid/56/ctl/Details/mid/374/ItemID/1/Default.aspx Request.Url.AbsoluteUri: http://localhost:4471/DNN441/Default.aspx Request.Url.AbsolutePath: /DNN441/Default.aspx Request.Url.LocalPath: /DNN441/Default.aspx Request.Url.Host: localhost Request.Url.PathAndQuery:/DNN441/Default.aspx?TabId=56&ctl=Details&mid=374&ItemID=1 | In reading through the answer provided in Rick Strahl's Blog I found what I really needed was quite simple. First you need to determine the relative path (which for me was the easy part), and pass that into the function defined below: VB.NET Public Shared Function GetFullyQualifiedURL(ByVal s as string) As String Dim Result as URI = New URI(HttpContext.Current.Request.Url, s) Return Result.ToStringEnd Function C# public static string GetFullyQualifiedURL(string s) { Uri Result = new Uri(HttpContext.Current.Request.Url, s); return Result.ToString();} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/121962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4318/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.