source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
163,563 | I have an issue - The javascript Date("mm-dd-yyyy") constructor doesn't work for FF. It works fine for IE. IE : new Date("04-02-2008") => "Wed Apr 2 00:00:00 EDT 2008" FF2 : new Date("04-02-2008") => Invalid Date So lets try another constructor. Trying this constructor Date("yyyy", "mm", "dd") IE : new Date("2008", "04", "02"); => "Fri May 2 00:00:00 EDT 2008" FF : new Date("2008", "04", "02"); => "Fri May 2 00:00:00 EDT 2008" IE : new Date("2008", "03", "02"); => "Wed Apr 2 00:00:00 EDT 2008" FF : new Date("2008", "03", "02"); => "Wed Apr 2 00:00:00 EDT 2008" So the Date("yyyy", "mm", "dd") constructor uses an index of 0 to represent January. Has anyone dealt with this? There must be a better way than subtracting 1 from the months. | It is the definition of the Date object to use values 0-11 for the month field. I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the constructor where you specify year/month/day as seperate parameters. BTW, in Firefox, new Date("04/02/2008"); works fine for me - it will interpret slashes, but not hyphens. I think this proves my point that using a String to construct a Date object is problemsome. Use explicit values for month/day/year instead: new Date(2008, 3, 2); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/163563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7617/"
]
} |
163,591 | In the GNOME Terminal, Bash does smart auto-completion. For example apt-get in<TAB> becomes apt-get install In Emacs shell-mode, this auto-completion doesn't work, even after I explicitly source /etc/bash_completion . The above example sticks as in or auto-completes with a filename in the current directory rather than a valid apt-get command option. Presumably, this is because Emacs is intercepting the Tab key-press. How do I enable smart auto-completion in shell-mode ? | I know this question is three years old, but it's something that I've also been interested in solving. A Web search directed me to a piece of elisp that makes Emacs use bash for completion in shell mode. It works for me, in any case. Check it out at https://github.com/szermatt/emacs-bash-completion . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/163591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
]
} |
163,610 | I run a browser based game at www.darknovagames.com. Recently, I've been working on reformatting the site with CSS, trying to get all of its pages to verify according to the HTML standard. I've been toying with this idea of having the navigation menu on the left AJAX the pages in (rather than taking the user to a separate page each time, requiring a reload of the title and nav bar, which almost never change) and I know that if I do so, I will probably break the Forward/Back buttons in the browser. My question I guess is, should I go ahead and AJAX the site, thus requiring the user to use the sites navigation to play the game, or should I leave the site as it currently stands, and use standard hyperlinks and things for navigation? The reason I ask I guess is that I built a forums system into the site, and a lot of times I would want to link say to a particular topic within the forums. I'm also open to suggestions. Is there a standard (preferably without traditional frames) way to make only the body area of the site reload, while still changing the URL so that users can bookmark and forward/back, etc? That could potentially solve my problem as well. I'm just asking for the best solution here, not an answer to a specific question. ^_^ Thanks | If you're going to enable AJAX, don't do it at the expense of having accessible URLs to every significant page on your site. This is the backbone of a navigable site that people can use. When you shovel all your functionality into AJAX calls and callbacks, you're basically forcing your users into a single path to access the features and content that they want -- which is totally against how the web is meant to function. People rely on the address bar and the back button. If you override all your links so that your site is essentially a single page that only updates through AJAX, you're limiting your users' ability to navigate your site and find what they need. It also stops your users from being able to share what they find (which, that's part of the point, right?). Think about a user's mental map of your site. If they know they came in through the home page, then they went to search for something, then they landed on a games page, then they started playing a particular game, that's four distinct units of action that the user took. They might have done a few other smaller, more insignificant actions on each of these pages -- but these are the main units. When they click the Back button, they should expect to go back through the path they came in on. If you are loading all these pages through AJAX calls, you're providing a site whose functionality runs contrary to what the user expects. Break your site out into every significant function (ie, search, home, profiles, games -- it'll be dictated by what your site is all about). Anywhere you link to these pages, do it through a regular link and a static URL. AJAX is fine. But the art of it is knowing when to use it and when not to. If you keep to the model I've sketched out above, your users will appreciate it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19521/"
]
} |
163,628 | When placing email addresses on a webpage do you place them as text like this: [email protected] or use a clever trick to try and fool the email address harvester bots? For example: HTML Escape Characters: joe.somebody@company.com Javascript Decrypter: function XOR_Crypt(EmailAddress){ Result = new String(); for (var i = 0; i < EmailAddress.length; i++) { Result += String.fromCharCode(EmailAddress.charCodeAt(i) ^ 128); } document.write(Result);}XOR_Crypt("êïå®óïíåâïäùÀãïíðáîù®ãïí"); Human Decode: [email protected] AT company.com What do you use or do you even bother? | I generally don't bother. I used to be on a mailing list that got several thousand spams every day. Our spam filter (spamassassin) let maybe 1 or 2 a day through. With filters this good, why make it difficult for legitimate people to contact you? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/163628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
]
} |
163,722 | Which profiler is better for general purpose profiling and heap analysis? 90% of our apps are standalone command line programs with substantial database and numeric processing. The other 10% are webapps/servlet container apps (with very little JSP and NO SCRIPLETS!). Target user would be Sr Software Engineer with 5-10 years of industry experience. We need support only for Sun JDK 5 and. As of writing this question (2008-10-02), JProfiler was at 5.1.4 and YourKit was 7.5. Looks like YourKit 8.0 will be released soon. | I've used both JProfiler 4 and YourKit 7.5, and YourKit wins hands down. It's so much less invasive than JProfile, in that I'll happy run production servers with the YourKit agent installed, which I would never do with JProfiler. Also, the analysis tool that comes with YourKit is more intuitive (in my opinion), making it easier to get the root cause of problems. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2601671/"
]
} |
163,732 | What would you recommend for class that needs to keep a list of unique integers? I'm going to want to Add() integers to the collection and also check for existence e.g. Contains(). Would be nice to also get them in a list as a string for display, ie. "1, 5, 10, 21". | HashSet : The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order... The capacity of a HashSet<T> object is the number of elements that the object can hold. A HashSet<T> object's capacity automatically increases as elements are added to the object. The HashSet<T> class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<TKey, TValue> or Hashtable collections. In simple terms, the HashSet<T> class can be thought of as a Dictionary<TKey, TValue> collection without values. A HashSet<T> collection is not sorted and cannot contain duplicate elements... | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16008/"
]
} |
163,803 | I would like to override the use of the standard app.config by passing a command line parameter. How do I change the default application configuration file so that when I access ConfigurationManager.AppSettings I am accessing the config file specified on the command line? Edit: It turns out that the correct way to load a config file that is different than the name of the EXE plus .config is to use OpenMappedExeConfiguration. E.g. ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Shell2.exe.config");currentConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None); This partially works. I can see all of the keys in the appSettings section but all the values are null. | So here is the code that actually allows me to actually access the appSettings section in a config file other than the default one. ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Alternate.config");Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");string MySetting = section.Settings["MySetting"].Value; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6819/"
]
} |
163,809 | I'm looking for an example algorithm of smart pagination. By smart, what I mean is that I only want to show, for example, 2 adjacent pages to the current page, so instead of ending up with a ridiculously long page list, I truncate it. Here's a quick example to make it clearer... this is what I have now: Pages: 1 2 3 4 [5] 6 7 8 9 10 11 This is what I want to end up with: Pages: ... 3 4 [5] 6 7 ... (In this example, I'm only showing 2 adjacent pages to the current page) I'm implementing it in PHP/Mysql, and the "basic" pagination (no trucating) is already coded, I'm just looking for an example to optimize it... It can be an example in any language, as long as it gives me an idea as to how to implement it... | Here is some code based on original code from this very old link . It uses markup compatible with Bootstrap's pagination component, and outputs page links like this: [1] 2 3 4 5 6 ... 1001 [2] 3 4 5 6 ... 100...1 2 ... 14 15 [16] 17 18 ... 100...1 2 ... 97 [98] 99 100 <?php// How many adjacent pages should be shown on each side?$adjacents = 3;//how many items to show per page$limit = 5;// if no page var is given, default to 1.$page = (int)$_GET["page"] ?? 1;//first item to display on this page$start = ($page - 1) * $limit;/* Get data. */$data = $db ->query("SELECT * FROM mytable LIMIT $start, $limit") ->fetchAll();$total_pages = count($data);/* Setup page vars for display. */$prev = $page - 1;$next = $page + 1;$lastpage = ceil($total_pages / $limit);//last page minus 1$lpm1 = $lastpage - 1;$first_pages = "<li class='page-item'><a class='page-link' href='?page=1'>1</a></li>" . "<li class='page-item'><a class='page-link' href='?page=2'>2</a>";$ellipsis = "<li class='page-item disabled'><span class='page-link'>...</span></li>";$last_pages = "<li class='page-item'><a class='page-link' href='?page=$lpm1'>$lpm1</a></li>" . "<li class='page-item'><a class='page-link' href='?page=$lastpage'>$lastpage</a>";$pagination = "<nav aria-label='page navigation'>";$pagincation .= "<ul class='pagination'>";//previous button$disabled = ($page === 1) ? "disabled" : "";$pagination.= "<li class='page-item $disabled'><a class='page-link' href='?page=$prev'>« previous</a></li>";//pages //not enough pages to bother breaking it upif ($lastpage < 7 + ($adjacents * 2)) { for ($i = 1; $i <= $lastpage; $i++) { $active = $i === $page ? "active" : ""; $pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>"; }} elseif($lastpage > 5 + ($adjacents * 2)) { //enough pages to hide some //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($i = 1; $i < 4 + ($adjacents * 2); $i++) { $active = $i === $page ? "active" : ""; $pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>"; } $pagination .= $ellipsis; $pagination .= $last_pages; } elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { //in middle; hide some front and some back $pagination .= $first_pages; $pagination .= $ellipsis for ($i = $page - $adjacents; $i <= $page + $adjacents; $i++) { $active = $i === $page ? "active" : ""; $pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>"; } $pagination .= $ellipsis; $pagination .= $last_pages; } else { //close to end; only hide early pages $pagination .= $first_pages; $pagination .= $ellipsis; $pagination .= "<li class='page-item disabled'><span class='page-link'>...</span></li>"; for ($i = $lastpage - (2 + ($adjacents * 2)); $i <= $lastpage; $i++) { $active = $i === $page ? "active" : ""; $pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>"; } }}//next button$disabled = ($page === $last) ? "disabled" : "";$pagination.= "<li class='page-item $disabled'><a class='page-link' href='?page=$next'>next »</a></li>";$pagination .= "</ul></nav>";if($lastpage <= 1) { $pagination = "";}echo $pagination;foreach ($data as $row) { // display your data}echo $pagination; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14981/"
]
} |
163,823 | I have a Person model that has a foreign key relationship to Book , which has a number of fields, but I'm most concerned about author (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display book.author using list_display : class PersonAdmin(admin.ModelAdmin): list_display = ['book.author',] I've tried all of the obvious methods for doing so, but nothing seems to work. Any suggestions? | As another option, you can do look ups like: class UserAdmin(admin.ModelAdmin): list_display = (..., 'get_author') def get_author(self, obj): return obj.book.author get_author.short_description = 'Author' get_author.admin_order_field = 'book__author' Since Django 3.2 you can use display() decorator: class UserAdmin(admin.ModelAdmin): list_display = (..., 'get_author') @admin.display(ordering='book__author', description='Author') def get_author(self, obj): return obj.book.author | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/163823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
]
} |
163,887 | Suppose I have a "tags" table with two columns: tagid and contentid . Each row represents a tag assigned to a piece of content. I want a query that will give me the contentid of every piece of content which is tagged with tagids 334, 338, and 342. The "easy" way to do this would be ( pseudocode ): select contentid from tags where tagid = 334 and contentid in ( select contentid from tags where tagid = 338 and contentid in ( select contentid from tags where tagid = 342 )) However, my gut tells me that there's a better, faster, more extensible way to do this. For example, what if I needed to find the intersection of 12 tags? This could quickly get horrendous. Any ideas? EDIT : Turns out that this is also covered in this excellent blog post . | SELECT contentIDFROM tagsWHERE tagID in (334, 338, 342)GROUP BY contentIDHAVING COUNT(DISTINCT tagID) = 3--In generalSELECT contentIDFROM tagsWHERE tagID in (...) --taglistGROUP BY contentIDHAVING COUNT(DISTINCT tagID) = ... --tagcount | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034/"
]
} |
163,913 | I'm having trouble deciding if I want a project of mine to be web-based (as in a web-app), desktop-based (a desktop application), or a desktop application that can sync or connect to the cloud. I don't know if anyone else would have an interest in this application, and it's only going to be for me, so I'm leaning toward desktop application. If, for some reason, I finish it, release it, and people actually like it, I might see about making it sync to the cloud as well (think v2). But I'm not sure how hard it is to make such a radical change, and I don't want to end up with something good that is useless because I made a poor choice before I even started the project. Is there any sort of guidance for this? Any rules of thumb or best practices? Any personal experiences? If the language matters, I'm thinking about Java simply because I'm most comfortable with it, and it would easily allow me to share it with my friends for testing and if I get stuck and need help from someone else in person. | I generally ask a few questions: Can it even be done on the web? Something I did not too long ago involved an image editing component, and had to be a web app. It involved much pain to get this work, and a desktop app would have been a far better way to go. Will I need to access it from anywhere? Yeah you could load it up on a thumb drive, but the web is far more feasible in this case. Will there be multiple users? This could go either way, but "long tail" stuff usually means web. What tech do you want to use? The latest and greatest WPF based UI? Desktop (yeah yeah, silverlight, let's not go there ok?). The brain dead stupid easy user management of Django or others? Web. If it were a web app, will you need to worry about common attack vectors like SQL Injection, XSS, etc? A desktop app has its own issues here too, but tend to have less exposure. How resource intensive is it? Will 10 users kill performance of a web server? Versioning on the desktop can be a pain, whereas with a webapp everyone is on the same version. This can bite you though, see the New Facebook user pushback. EDIT: Cost can be a factor too. A web app with a database backend typically means a web server. If you want to stick with, say, the Microsoft Stack, you'll need licenses for SQL Server which can get pricey. Open source is cheaper, but may not be an option in all cases. "Serving" a desktop app is generally cheaper. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
163,917 | I have never clearly understood the usage of MAXDOP . I do know that it makes the query faster and that it is the last item that I can use for Query Optimization. However, my question is, when and where it is best suited to use in a query? | As Kaboing mentioned, MAXDOP(n) actually controls the number of CPU cores that are being used in the query processor. On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER) which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN) reduce a query from 26 seconds to 1 second of execution time. Books Online goes on to say that possible values for MAXDOP are: 0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting. 1 - Suppresses parallel plan generation. The operation will be executed serially. 2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used. I'm not sure what the best usage of MAXDOP is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8) due to I/O limitations, but I could be wrong. Here are a few quick links I found about MAXDOP : Books Online: Degree of Parallelism General guidelines to use to configure the MAXDOP option | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21968/"
]
} |
163,923 | What are some good algorithms for automatically labeling text with the city / region or origin? That is, if a blog is about New York, how can I tell programatically. Are there packages / papers that claim to do this with any degree of certainty? I have looked at some tfidf based approaches, proper noun intersections, but so far, no spectacular successes, and I'd appreciate ideas! The more general question is about assigning texts to topics, given some list of topics. Simple / naive approaches preferred to full on Bayesian approaches, but I'm open. | You're looking for a named entity recognition system, or short NER. There are several good toolkits available to help you out. LingPipe in particular has a very decent tutorial . CAGEclass seems to be oriented around NER on geographical place names, but I haven't used it yet. Here's a nice blog entry about the difficulties of NER with geographical places names. If you're going with Java, I'd recommend using the LingPipe NER classes. OpenNLP also has some, but the former has a better documentation. If you're looking for some theoretical background, Chavez et al. (2005) have constructed an interesting syntem and documented it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
]
} |
163,998 | Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like: ArrayList<Integer> setA ...ArrayList<Integer> setB ...ArrayList<Integer> setAintersectionB = setA.intersection(setB);ArrayList<Integer> setAminusB = setA.subtract(setB); After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface? In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times. | Intersection is done with Collection.retainAll ; subtraction with Collection.removeAll ; union with Collection.addAll . In each case, as Set will act like a set and a List will act like a list. As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/163998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19147/"
]
} |
164,002 | I am writing a C library that reads a file into memory. It skips the first 54 bytes of the file (header) and then reads the remainder as data. I use fseek to determine the length of the file, and then use fread to read in the file. The loop runs once and then ends because the EOF is reached (no errors). At the end, bytesRead = 10624, ftell(stream) = 28726, and the buffer contains 28726 values. I expect fread to read 30,000 bytes and the file position to be 30054 when EOF is reached. C is not my native language so I suspect I've got a dumb beginner mistake somewhere. Code is as follows: const size_t headerLen = 54;FILE * stream;errno_t ferrno = fopen_s( &stream, filename.c_str(), "r" );if(ferrno!=0) { return -1;}fseek( stream, 0L, SEEK_END );size_t bytesTotal = (size_t)(ftell( stream )) - headerLen; //number of data bytes to readsize_t bytesRead = 0;BYTE* localBuffer = new BYTE[bytesTotal];fseek(stream,headerLen,SEEK_SET);while(!feof(stream) && !ferror(stream)) { size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-bytesRead,stream); bytesRead+=result;} Depending on the reference you use, it's quite apparent that adding a "b" to the mode flag is the answer. Seeking nominations for the bonehead-badge. :-) This reference talks about it in the second paragraph, second sentence (though not in their table). MSDN doesn't discuss the binary flag until halfway down the page. OpenGroup mentions the existance of the "b" tag, but states that it "shall have no effect". | perhaps it's a binary mode issue. Try opening the file with "r+b" as the mode. EDIT : as noted in a comment "rb" is likely a better match to your original intent since "r+b" will open it for read/write and "rb" is read-only. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/164002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17871/"
]
} |
164,048 | I'm about to start (with fellow programmers) a programming & algorithms club in my high school. The language of choice is C++ - sorry about that, I can't change this. We can assume students have little to no experience in the aforementioned topics. What do you think are the most basic concepts I should focus on? I know that teaching something that's already obvious to me isn't an easy task. I realize that the very first meeting should be given an extreme attention - to not scare students away - hence I ask you. Edit: I noticed that probably the main difference between programmers and beginners is "programmer's way of thinking" - I mean, conceptualizing problems as, you know, algorithms. I know it's just a matter of practice, but do you know any kind of exercises/concepts/things that could stimulate development in this area? | Make programming fun! Possible things to talk about would be Programming Competitions that either your club could hold itself or it could enter in locally. I compete in programming competitions at the University (ACM) level and I know for a fact that they have them at lower levels as well. Those kind of events can really draw out some competitive spirit and bring the club members closer. Things don't always have to be about programming either. Perhaps suggest having a LAN party where you play games, discuss programming, etc could be a good idea as well. In terms of actual topics to go over that are programming/algorithm related, I would suggest as a group attempting some of these programming problems in this programming competition primer " Programming Challenges ": Amazon Link They start out with fairly basic programming problems and slowly progress into problems that require various Data Structures like: Stacks Queues Dictionaries Trees Etc Most of the problems are given in C++. Eventually they progress into more advanced problems involving Graph Traversal and popular Graph algorithms ( Dijkstra's , etc) , Combinatrics problems, etc. Each problem is fun and given in small "story" like format. Be warned though, some of these are very hard! Edit:Pizza and Soda never hurts either when it comes to getting people to show up for your club meetings. Our ACM club has pizza every meeting (once a month). Even though most of us would still show up it is a nice ice breaker. Especially for new clubs or members. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19082/"
]
} |
164,053 | Should log classes open/close a log file stream on each write to the log file or should it keep the log file stream open throughout the application's lifetime until all logging is complete? I'm asking in context of a desktop application. I have seen people do it both ways and was wondering which approach yields the best all-around results for a logger. | If you have frequent read/writes it is more efficient to keep the file open for the lifetime with a single open/close . You might want to flush periodically or after each write though. If your application crashes you might not have all the data written to your file. Use fflush on Unix-based systems and FlushFileBuffers on Windows. If you are running on Windows as well you can use the CreateFile API with FILE_FLAG_NO_BUFFERING to go direct to the file on each write. It is also better to keep the file open for the lifetime, because each time you open/close you might have a failure if the file is in use. For example, you might have a backup application that runs and opens/closes your file as it's backing it up. And this might cause your program to not be able to access your own file . Ideally, you would want to keep your file open always and specify sharing flags on Windows (FILE_SHARE_READ). On Unix-based systems, sharing will be default. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133/"
]
} |
164,085 | I need to execute a callback when an IFRAME has finished loading. I have no control over the content in the IFRAME, so I can't fire the callback from there. This IFRAME is programmaticly created, and I need to pass its data as a variable in the callback, as well as destroy the iframe. Any ideas? EDIT: Here is what I have now: function xssRequest(url, callback){ var iFrameObj = document.createElement('IFRAME'); iFrameObj.src = url; document.body.appendChild(iFrameObj); $(iFrameObj).load(function() { document.body.removeChild(iFrameObj); callback(iFrameObj.innerHTML); });} This callsback before the iFrame has loaded, so the callback has no data returned. | First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe. On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine: // possibly excessive use of jQuery - but I've got a live working example in production$('#myUniqueID').load(function () { if (typeof callback == 'function') { callback($('body', this.contentWindow.document).html()); } setTimeout(function () {$('#frameId').remove();}, 50);}); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
164,088 | When designing a collection class, is there any reason not to implement locking privately to make it thread safe? Or should I leave that responsibility up to the consumer of the collection? | is there any reason not to implement locking privately to make it thread safe? It depends. Is your goal to write a collection class which is accessed by multiple threads?If so, make it thread safe. If not, don't waste your time. This kind of thing is what people refer to when they talk about 'premature optimization' Solve the problems that you have. Don't try to solve future problems that you think you may have some years in the future, because you can't see the future, and you'll invariably be wrong. Note: You still need to write your code in a maintainable way, such that if you did need to come along and add locking to the collection, it wouldn't be terribly hard. My point is "don't implement features that you don't need and won't use" | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
]
} |
164,102 | For example, suppose I have a class: class Foo{public: std::string& Name() { m_maybe_modified = true; return m_name; } const std::string& Name() const { return m_name; }protected: std::string m_name; bool m_maybe_modified;}; And somewhere else in the code, I have something like this: Foo *a;// Do stuff...std::string name = a->Name(); // <-- chooses the non-const version Does anyone know why the compiler would choose the non-const version in this case? This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point. | Two answers spring to mind: The non-const version is a closer match. If it called the const overload for the non-const case, then under what circumstances would it ever call the non-const overload? You can get it to use the other overload by casting a to a const Foo * . Edit: From C++ Annotations Earlier, in section 2.5.11 the conceptof function overloading wasintroduced. There it noted that memberfunctions may be overloaded merely bytheir const attribute. In those cases,the compiler will use the memberfunction matching most closely theconst-qualification of the object: | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9876/"
]
} |
164,143 | What exactly are the advantages and disadvantages to using a register-based virtual machine versus using a stack-based virtual machine? To me, it would seem as though a register based machine would be more straight-forward to program and more efficient. So why is it that the JVM, the CLR, and the Python VM are all stack-based? | Implemented in hardware, a register-based machine is going to be more efficient simply because there are fewer accesses to the slower RAM. In software, however, even a register based architecture will most likely have the "registers" in RAM. A stack based machine is going to be just as efficient in that case. In addition a stack-based VM is going to make it a lot easier to write compilers. You don't have to deal with register allocation strategies. You have, essentially, an unlimited number of registers to work with. Update: I wrote this answer assuming an interpreted VM. It may not hold true for a JIT compiled VM. I ran across this paper which seems to indicate that a JIT compiled VM may be more efficient using a register architecture. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
164,162 | Which is a better format to store graphic assets for a Flex application, SWF or SWC? Are there any real differences, and if so what are they? | Assets in a seperate SWF are loaded and included at runtime. Assets in a SWC are loaded and included / compiled at compile time. You can also directly embed assets within the main app SWF at compile time (check out the Embed meta data). Of course, you can also load individual assets (such as a PNG) directly at runtime. As far as which is better, it really depends on what you are trying to do, and how the assets are used. mike | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10875/"
]
} |
164,163 | When implementing Quicksort, one of the things you have to do is to choose a pivot. But when I look at pseudocode like the one below, it is not clear how I should choose the pivot. First element of list? Something else? function quicksort(array) var list less, greater if length(array) ≤ 1 return array select and remove a pivot value pivot from array for each x in array if x ≤ pivot then append x to less else append x to greater return concatenate(quicksort(less), pivot, quicksort(greater)) Can someone help me grasp the concept of choosing a pivot and whether or not different scenarios call for different strategies. | Choosing a random pivot minimizes the chance that you will encounter worst-case O(n 2 ) performance (always choosing first or last would cause worst-case performance for nearly-sorted or nearly-reverse-sorted data). Choosing the middle element would also be acceptable in the majority of cases. Also, if you are implementing this yourself, there are versions of the algorithm that work in-place (i.e. without creating two new lists and then concatenating them). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/164163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20032/"
]
} |
164,168 | If I want to construct a std::string with a line like: std::string my_string("a\0b"); Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax? | Since C++14 we have been able to create literal std::string #include <iostream>#include <string>int main(){ using namespace std::string_literals; std::string s = "pl-\0-op"s; // <- Notice the "s" at the end // This is a std::string literal not // a C-String literal. std::cout << s << "\n";} Before C++14 The problem is the std::string constructor that takes a const char* assumes the input is a C-string. C-strings are \0 terminated and thus parsing stops when it reaches the \0 character. To compensate for this, you need to use the constructor that builds the string from a char array (not a C-String). This takes two parameters - a pointer to the array and a length: std::string x("pq\0rs"); // Two characters because input assumed to be C-Stringstd::string x("pq\0rs",5); // 5 Characters as the input is now a char array with 5 characters. Note: C++ std::string is NOT \0 -terminated (as suggested in other posts). However, you can extract a pointer to an internal buffer that contains a C-String with the method c_str() . Also check out Doug T's answer below about using a vector<char> . Also check out RiaD for a C++14 solution. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/164168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17958/"
]
} |
164,175 | For a complex web application that includes dynamic content and personalization, what is a good response time from the server (so excluding network latency and browser rendering time)? I'm thinking about sites like Facebook, Amazon, MyYahoo, etc. A related question is what is a good response time for a backend service? | There's a great deal of research on this. Here's a quick summary . Response Times: The 3 Important Limits by Jakob Nielsen on January 1, 1993 Summary: There are 3 main time limits (which are determined by human perceptual abilities) to keep in mind when optimizing web and application performance. Excerpt from Chapter 5 in my book Usability Engineering , from 1993: The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]: 0.1 second is about the limit for having the user feel that the system is reacting instantaneously , meaning that no special feedback is necessary except to display the result. 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data. 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/164175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3425/"
]
} |
164,181 | How can I fetch images from a server? I've got this bit of code which allows me to draw some images on a canvas. <html> <head> <script type="text/javascript"> function draw(){ var canvas = document.getElementById('canv'); var ctx = canvas.getContext('2d'); for (i=0;i<document.images.length;i++){ ctx.drawImage(document.images[i],i*150,i*130); } } </script> </head> <body onload="draw();"> <canvas id="canv" width="1024" height="1024"></canvas> <img src="http://www.google.com/intl/en_ALL/images/logo.gif"> <img src="http://l.yimg.com/a/i/ww/beta/y3.gif"> <img src="http://static.ak.fbcdn.net/images/welcome/welcome_page_map.png"> </body></html> Instead of looping over document.images, i would like to continually fetch images from a server. for (;;) { /* how to fetch myimage??? */ myimage = fetch???('http://myserver/nextimage.cgi'); ctx.drawImage(myimage, x, y);} | Use the built-in JavaScript Image object . Here is a very simple example of using the Image object: myimage = new Image();myimage.src = 'http://myserver/nextimage.cgi'; Here is a more appropriate mechanism for your scenario from the comments on this answer. Thanks olliej ! It's worth noting that you can't synchronously request a resource, so you should actually do something along the lines of: myimage = new Image();myimage.onload = function() { ctx.drawImage(myimage, x, y); }myimage.src = 'http://myserver/nextimage.cgi'; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
164,194 | The following code receives seg fault on line 2: char *str = "string";str[0] = 'z'; // could be also written as *str = 'z'printf("%s\n", str); While this works perfectly well: char str[] = "string";str[0] = 'z';printf("%s\n", str); Tested with MSVC and GCC. | See the C FAQ, Question 1.32 Q : What is the difference between these initializations? char a[] = "string literal"; char *p = "string literal"; My program crashes if I try to assign a new value to p[i] . A : A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways: As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size). Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element. Some compilers have a switch controlling whether string literals are writable or not (for compiling old code), and some may have options to cause string literals to be formally treated as arrays of const char (for better error catching). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/164194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24622/"
]
} |
164,197 | I am working on an ASP.Net web application that must print dynamically created labels on standard Avery-style label sheets (one particular size, so only one overall layout). The labels have a variable number of lines (3-6) and may contain either lines of text or a graphic barcode image. Our first cut, that I inherited, used monospaced fonts to reduce the formatting issues, but that did not allow enough text to the fit on the labels and the customer was dissatisfied. Basically it was formatted text. My next version used TABLEs, DIVs, CSS, and a bit of JavaScript calculations to format the labels using proportional fonts. It still required a bit of tweaking (the user had to set their print margins correctly and turn off the print headers and footers), but it seemed to work. However, it seems that there are some variations on how different printers render the text (WYS ain't WYG), so even though we tested on different browsers using at least two different printers (an inkjet and a laser printer), some user's labels don't line up. Slight margin variations can be adjusted by adjusting the margins on the page setup dialog, but the harder problem is that the inter-label spacing can be off by a tiny fraction of an inch, so that if the first label is pretty well centered, by the end of the page the label text and images have crawled off the top or bottom of the labels. We are about to the point of switching to generating Word, Excel, or PDF output which is going to take quite a bit of development time and possible add extra steps in the printing process. So, does anyone have any suggestions on how to do an HTML/CSS layout that will precisely render on different types of printers? I don't really care if the line/word breaks are a bit different, but I need to be able to predictably position the upper left corners of each label area. Right now the labels flow down the page in a table and we have been tweaking the box model of the cells and internal DIVs to make them a uniform height. I suspect that using absolute positioning of each element may be the best answer, but that is going to be tricky as well due to the ASP.Net generation of the label elements. If I knew for sure that would work, I would rather try it than throw away everything we have to go to a different generation method. Slight Update:Right now I'm doing some tests with absolute positioning - setting only the top and left coordinate of a containing block element. So far there are minor variations on the offset onto the page (margins, paper alignment, etc.), but all browsers and printers tested put the elements in exactly the right spots relative to each other. I appreciate the PDF tips, but does anyone know of additional "gotchas" on using absolute positioning this way? Update: For the record, I rewrote the label printing portion using iTextSharp and it works perfectly - definitely the way to do this in the future... | Forget HTML and make a PDF. HTML printing is extremely variable - not just across browsers but across different versions of the same browser. PDF is a lot easier. Even if you get it exactly right with one browser / font setup / printer / phase of the moon, it will be the most fragile thing you've ever had to maintain. No matter how long you think it will take to make a PDF (and it's not really that hard as there are some free libraries out there), HTML will ultimately take a lot more of your time. PDF readers are widely deployed and print more consistently than even Word files. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14894/"
]
} |
164,282 | Specifically, we've got some external JavaScript tracking code on our sites that throws itself into an infinite loop each time an anchor is clicked on. We don't maintain the tracking code, so we don't know exactly how it works. Since the code causes the browser to lock up almost immediately, I was wondering if there's anyway to log the results of Firebug's 'profile' functionality to an external file for review? | Forget HTML and make a PDF. HTML printing is extremely variable - not just across browsers but across different versions of the same browser. PDF is a lot easier. Even if you get it exactly right with one browser / font setup / printer / phase of the moon, it will be the most fragile thing you've ever had to maintain. No matter how long you think it will take to make a PDF (and it's not really that hard as there are some free libraries out there), HTML will ultimately take a lot more of your time. PDF readers are widely deployed and print more consistently than even Word files. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22468/"
]
} |
164,307 | With the MacPorts version of ImageMagick 6.4.4 installed, I'm getting an error installing the RMagick gem. /opt/local/bin/ruby extconf.rb update rmagickchecking for Ruby version >= 1.8.2... yeschecking for /usr/bin/gcc-4.0... yeschecking for Magick-config... noCan't install RMagick 2.7.0. Can't find Magick-config in /System/Library/Frameworks/JavaVM.framework/Versions/1.5/Commands: /Users/jason/.bin:/opt/local/bin:/usr/local/bin:/usr/local/mysql/bin: /usr/local/ec2-api-tools/bin:/opt/local/bin:/usr/bin: /usr/local/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin I've installed older versions of rmagick successfully. I've seen references to a dev package of ImageMagick, but it doesn't seem to be available from MacPorts. How can I install RMagick 2.7 on Mac OS X with ImageMagick 6.4.4 from MacPorts? | I suggest using Homebrew instead of Macports. After installing Homebrew, run: brew install imagemagickgem install rmagick | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11078/"
]
} |
164,319 | I learned something simple about SQL the other day: SELECT c FROM myTbl GROUP BY C Has the same result as: SELECT DISTINCT C FROM myTbl What I am curious of, is there anything different in the way an SQL engine processes the command, or are they truly the same thing? I personally prefer the distinct syntax, but I am sure it's more out of habit than anything else. EDIT: This is not a question about aggregates. The use of GROUP BY with aggregate functions is understood. | MusiGenesis ' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using "Group By" and not using any aggregate functions, then what you actually mean is "Distinct" - and therefore it generates an execution plan as if you'd simply used "Distinct." However, I think it's important to note Hank 's response as well - cavalier treatment of "Group By" and "Distinct" could lead to some pernicious gotchas down the line if you're not careful. It's not entirely correct to say that this is "not a question about aggregates" because you're asking about the functional difference between two SQL query keywords, one of which is meant to be used with aggregates and one of which is not. A hammer can work to drive in a screw sometimes, but if you've got a screwdriver handy, why bother? (for the purposes of this analogy, Hammer : Screwdriver :: GroupBy : Distinct and screw => get list of unique values in a table column ) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/164319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5836/"
]
} |
164,335 | Any XPath like /NodeName/position() would give you the position of the Node w.r.t it's parent node. There is no method on the XElement (Linq to XML) object that can get the position of the Element. Is there? | Actually NodesBeforeSelf().Count doesn't work because it gets everything even of type XText Question was about XElement object.So I figured it's int position = obj.ElementsBeforeSelf().Count(); that should be used, Thanks to Bryant for the direction. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1747/"
]
} |
164,342 | I'm considering one of two IRepository interfaces, one that is a descendant of IQueryable and one that contains IQueryable. Like this: public interface IRepository<T> : IQueryable<T>{ T Save(T entity); void Delete(T entity);} Or this: public interface IRepository<T>{ T Save(T entity); void Delete(T entity); IQueryable<T> Query();} LINQ usage would be: from dosin ServiceLocator.Current.GetInstance<IRepository<DomainObject>>()where dos.Id == idselect dos Or... from dosin ServiceLocator.Current.GetInstance<IRepository<DomainObject>>().Querywhere dos.Id == idselect dos I kinda like the first one, but it's problematic to mock. How have other people implemented LINQable, mockable repositories? | Depends on if you want a Has-A or an Is-A relationship. The first one is an Is-A relationship. The IRepository interface is a IQueryable interface. The second is a has-a. The IRepository has an IQueryable interface. In the process of writing this, I actually like the second better then the first, simply because when use your second IRepository, I can give the Query() method ANYTHING that returns IQueryable. To me, that is more flexible then the first implementation. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3759/"
]
} |
164,343 | I'm playing around with BCEL. I'm not using it to generate bytecode, but instead I'm trying to inspect the structure of existing compiled classes. I need to be able to point to an arbitrary .class file anywhere on my hard drive and load a JavaClass object based on that. Ideally I'd like to avoid having to add the given class to my classpath. | The straightforward way is to create a ClassParser with the file name and call parse(). Alternatively you can use SyntheticRepository and supply a classpath (that is not your classpath, IYSWIM). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247/"
]
} |
164,344 | How can I make my std::fstream object start reading a text file from the second line? | Use getline() to read the first line, then begin reading the rest of the stream. ifstream stream("filename.txt");string dummyLine;getline(stream, dummyLine);// Begin reading your stream herewhile (stream) ... (Changed to std::getline (thanks dalle.myopenid.com)) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
164,356 | For example, I'm writing a multi-threaded time-critical application that processes and streams audio in real-time. Interruptions in the audio are totally unacceptable. Does this mean I cannot use the STL because of the potential slow down when an exception is thrown? | Generally, the only exceptions that STL containers will throw by themselves is an std::bad_alloc if new fails. The only other times are when user code (for example constructors, assignments, copy constructors) throws. If your user code never throws then you only have to guard against new throwing, which you would have had to do anyways most likely. Other things that can throw exceptions:- at() functions can throw std::out_of_range if you access them out of bounds. This is a serious program error anyways. Secondly, exceptions aren't always slow. If an exception occurs in your audio processing, its probably because of a serious error that you will need to handle anyways. The error handling code is probably going to be significantly more expensive than the exception handling code to transport the exception to the catch site. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13760/"
]
} |
164,378 | I'm working on a project where we're doing a lot of remote object transfer between a Java service and clients written in other various languages. Given our current constraints I've decided to see what it would take to generate code based on an existing Java class. Basically I need to take a .class file (or a collection of them) parse the bytecode to determine all of the data members and perhaps getters/setters and then write something that can output code in a different language to create a class with the same structure. I'm not looking for standard decompilers such as JAD. I need to be able to take a .class file and create an object model of its data members and methods. Is this possible at all? | I've used BCEL and find it really quite awkward. ASM is much better. It very extensively uses visitors (which can be a little confusing) and does not create an object model. Not creating an object model turns out to be a bonus, as any model you do want to create is unlikely to look like a literal interpretation of all the data. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247/"
]
} |
164,393 | In the quest for localization I need to find all the string literals littered amongst our source code. I was looking for a way to script this into a post-modification source repository check. (I.E. after some one checks something in have a box setup to check this stat) I'll probably use NAnt and CruiseControl or something to handle the management of the CVS (Well StarTeam in my case :( ) But do you know of any scriptable (or command line) utility to accurately cycle through source code looking for string literals? I realize I could do simple string look up based on regular expressions but want a little more bang for my buck. (Maybe analyze the string or put it into categories) Because a lot of times the string may not necessarily require translation. Any ideas? | Visual Studio 2010 and earlier: Find In Files (CTRL+SHIFT+F) Use: Regular Expressions Find: :q (quoted string) Find All Find Results window will now contain a report of all files, with line numbers and the line itself with the quoted string. For Visual Studio 2012 and later search for ((\".+?\")|('.+?')) ( reference , hat-tip to @CincauHangus ) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
]
} |
164,395 | I'm wondering if its possible to add new class data members at run-time in PHP? | Yes. $prop = 'newname';$obj->$prop = 42; will do the same thing as: $obj->newname = 42; Either one will add "newname" as a property in $obj if it does not yet exist. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
]
} |
164,397 | How can I print a message to the error console, preferably including a variable? For example, something like: print('x=%d', x); | Install Firebug and then you can use console.log(...) and console.debug(...) , etc. (see the documentation for more). | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/164397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
164,414 | I'm processing a file, line-by-line, and I'd like to do an inverse match. For instance, I want to match lines where there is a string of six letters, but only if these six letters are not ' Andrea '. How should I do that? I'm using RegexBuddy , but still having trouble. | (?!Andrea).{6} Assuming your regexp engine supports negative lookaheads... ...or maybe you'd prefer to use [A-Za-z]{6} in place of .{6} Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching; they leave that to whatever language you are using them with. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/164414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21384/"
]
} |
164,425 | I am building a fun little app to determine if I should bike to work. I would like to test to see if it is either Raining or Thunderstorm(ing). public enum WeatherType : byte{ Sunny = 0, Cloudy = 1, Thunderstorm = 2, Raining = 4, Snowing = 8, MostlyCloudy = 16 } I was thinking I could do something like: WeatherType _badWeatherTypes = WeatherType.Thunderstorm | WeatherType.Raining;if(currentWeather.Type == _badWeatherTypes){ return false;//don't bike} but this doesn't work because _badWeatherTypes is a combination of both types. I would like to keep them separated out because this is supposed to be a learning experience and having it separate may be useful in other situations (IE, Invoice not paid reason's etc...). I would also rather not do: (this would remove the ability to be configured for multiple people) if(WeatherType.Thunderstorm){ return false; //don't bike}etc... | Your current code will say whether it's exactly "raining and thundery". To find out whether it's "raining and thundery and possibly something else" you need: if ((currentWeather.Type & _badWeatherTypes) == _badWeatherTypes) To find out whether it's "raining or thundery, and possibly something else" you need: if ((currentWeather.Type & _badWeatherTypes) != 0) EDIT (for completeness): It would be good to use the FlagsAttribute , i.e. decorate the type with [Flags] . This is not necessary for the sake of this bitwise logic, but affects how ToString() behaves. The C# compiler ignores this attribute (at least at the moment; the C# 3.0 spec doesn't mention it) but it's generally a good idea for enums which are effectively flags, and it documents the intended use of the type. At the same time, the convention is that when you use flags, you pluralise the enum name - so you'd change it to WeatherTypes (because any actual value is effectively 0 or more weather types). It would also be worth thinking about what "Sunny" really means. It's currently got a value of 0, which means it's the absence of everything else; you couldn't have it sunny and raining at the same time (which is physically possible, of course). Please don't write code to prohibit rainbows! ;) On the other hand, if in your real use case you genuinely want a value which means "the absence of all other values" then you're fine. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18821/"
]
} |
164,427 | I've made a Django site, but I've drank the Koolaid and I want to make an IPhone version. After putting much thought into I've come up with two options: Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework. Find some time of middleware that reads the user-agent, and changes the template directories dynamically. I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation discourages changing settings on the fly . I found a snippet that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user. Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites? Update I went with a combination of middleware and tweaking the template call. For the middleware, I used minidetector . I like it because it detects a plethora of mobile user-agents. All I have to do is check request.mobile in my views. For the template call tweak: def check_mobile(request, template_name): if request.mobile: return 'mobile-%s'%template_name return template_name I use this for any view that I know I have both versions. TODO: Figure out how to access request.mobile in an extended version of render_to_response so I don't have to use check_mobile('template_name.html') Using the previous automagically fallback to the regular template if no mobile version exists. | Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render_to_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24630/"
]
} |
164,430 | I know it is customary, but why? Are there real technical reasons why any other way would be a really bad idea or is it just based on the history of encoding and backwards compatibility? In addition, what are the dangers of not using UTF-8 , but some other encoding (most notably, UTF-16 )? Edit : By interacting, I mostly mean the shell and libc . | Partly because the file systems expect NUL ('\0') bytes to terminate file names, so UTF-16 would not work well. You'd have to modify a lot of code to make that change. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13760/"
]
} |
164,433 | When I debug a C# program and I get an exception throwed (either thrown by code OR thrown by the framework), the IDE stops and get me to the corresponding line in my code. Everything is fine for now. I then press "F5" to continue. From this moment, it seams like I'm in an infinite loop. The IDE always get me back to the exception line. I have to Shift + F5 (stop debugging/terminate the program) to get out of his. I talked with some co-workers here and they told me that this happens sometime to them too. What's happening? | You probably have the option " Unwind the callstack on unhandled exceptions " checked in Visual Studio. When this option is on Visual Studio will unwind to right before the exception, so hitting F5 will keep ramming into the same exception. If you uncheck the option Visual Studio will break at the exception, but hitting F5 will proceed past that line. This option is under menu Tools → Options → Debugging → General . Update: According to Microsoft , this option was removed from Visual Studio in VS2017, and maybe earlier. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17766/"
]
} |
164,468 | The IT department of a subsidiary of ours had a consulting company write them an ASP.NET application. Now it's having intermittent problems with mixing up who the current user is and has been known to show Joe some of Bob's data by mistake. The consultants were brought back to troubleshoot and we were invited to listen in on their explanation. Two things stuck out. First, the consultant lead provided this pseudo-code: void MyFunction(){ Session["UserID"] = SomeProprietarySessionManagementLookup(); Response.Redirect("SomeOtherPage.aspx");} He went on to say that the assignment of the session variable is asynchronous, which seemed untrue. Granted the call into the lookup function could do something asynchronously, but this seems unwise. Given that alleged asynchronousness, his theory was that the session variable was not being assigned before the redirect's inevitable ThreadAbort exception was raised. This faulure then prevented SomeOtherPage from displaying the correct user's data. Second, he gave an example of a coding best practice he recommends. Rather than writing: int MyFunction(int x, int x){ try { return x / y; } catch(Exception ex) { // log it throw; }} the technique he recommended was: int MyFunction(int x, int y, out bool isSuccessful) { isSuccessful = false; if (y == 0) return 0; isSuccessful = true; return x / y; } This will certainly work and could be better from a performance perspective in some situations. However, from these and other discussion points it just seemed to us that this team was not well-versed technically. Opinions? | I would agree. These guys seem quite incompetent. (BTW, I'd check to see if in "SomeProprietarySessionManagementLookup," they're using static data. Saw this -- with behavior exactly as you describe on a project I inherited several months ago. It was a total head-slap moment when we finally saw it ... And wished we could get face to face with the guys who wrote it ... ) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12260/"
]
} |
164,496 | I've been reading about thread-safe singleton patterns here: http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29 And it says at the bottom that the only safe way is to use pthread_once - which isn't available on Windows. Is that the only way of guaranteeing thread safe initialisation? I've read this thread on SO: Thread safe lazy construction of a singleton in C++ And seems to hint at an atomic OS level swap and compare function, which I assume on Windows is: http://msdn.microsoft.com/en-us/library/ms683568.aspx Can this do what I want? Edit: I would like lazy initialisation and for there to only ever be one instance of the class. Someone on another site mentioned using a global inside a namespace (and he described a singleton as an anti-pattern) - how can it be an "anti-pattern"? Accepted Answer: I've accepted Josh's answer as I'm using Visual Studio 2008 - NB: For future readers, if you aren't using this compiler (or 2005) - Don't use the accepted answer!! Edit: The code works fine except the return statement - I get an error:error C2440: 'return' : cannot convert from 'volatile Singleton *' to 'Singleton *'.Should I modify the return value to be volatile Singleton *? Edit: Apparently const_cast<> will remove the volatile qualifier. Thanks again to Josh. | If you are are using Visual C++ 2005/2008 you can use the double checked locking pattern, since " volatile variables behave as fences ". This is the most efficient way to implement a lazy-initialized singleton. From MSDN Magazine: Singleton* GetSingleton(){ volatile static Singleton* pSingleton = 0; if (pSingleton == NULL) { EnterCriticalSection(&cs); if (pSingleton == NULL) { try { pSingleton = new Singleton(); } catch (...) { // Something went wrong. } } LeaveCriticalSection(&cs); } return const_cast<Singleton*>(pSingleton);} Whenever you need access to the singleton, just call GetSingleton(). The first time it is called, the static pointer will be initialized. After it's initialized, the NULL check will prevent locking for just reading the pointer. DO NOT use this on just any compiler, as it's not portable. The standard makes no guarantees on how this will work. Visual C++ 2005 explicitly adds to the semantics of volatile to make this possible. You'll have to declare and initialize the CRITICAL SECTION elsewhere in code. But that initialization is cheap, so lazy initialization is usually not important. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
]
} |
164,527 | In .NET, if a class contains a member that is a class object, should that member be exposed as a property or with a method? | If all you are doing is exposing an object instance that is relevant to the state of the current object you should use a property. A method should be used when you have some logic that is doing more than accessing an in memory object and returning that value or when you are performing an action that has a broad affect on the state of the current object. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19065/"
]
} |
164,600 | I would like to see the threads currently active in my application while debugging it. How can I do this using Visual Studio? | Yes, go to Debug->Windows->Threads | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
} |
164,642 | How do I create a grails war file so that it doesn't have the version number (e.g. foo-0.1.war) attached to the end when I execute the 'grails war' command? | I think you can specify the war name in the war command. grails war foo.war Also check the latest Grails documentation for where to set this as a configuration option. See the other answers for details. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
164,643 | In my C# source code I may have declared integers as: int i = 5; or Int32 i = 5; In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same? int i = 5;Int64 i = 5; | No. The C# specification rigidly defines that int is an alias for System.Int32 with exactly 32 bits. Changing this would be a major breaking change. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/164643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
164,645 | Is there any way that I can change how a Literal of a code snippet renders when it is used in the code that the snippet generates? Specifically I'd like to know if I can have a literal called say, $PropertyName$ and then get the snippet engine to render "_$PropertyName$ where the first character is made lowercase. I can't afford R#. Please help :) | Unfortunately there seems to be no way. Snippets offer amazingly limited support for transformation functions as you can see. You have to stick with the VS standard solution, which is to write two literals: one for the property name, and the other for the member variable name. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19452/"
]
} |
164,831 | I'd like to rank a collection of landscape images by making a game whereby site visitors can rate them, in order to find out which images people find the most appealing. What would be a good method of doing that? Hot-or-Not style ? I.e. show a single image, ask the user to rank it from 1-10. As I see it, this allows me to average the scores, and I would just need to ensure that I get an even distribution of votes across all the images. Fairly simple to implement. Pick A-or-B ? I.e. show two images, ask user to pick the better one. This is appealing as there is no numerical ranking, it's just a comparison. But how would I implement it? My first thought was to do it as a quicksort, with the comparison operations being provided by humans, and once completed, simply repeat the sort ad-infinitum. How would you do it? If you need numbers, I'm talking about one million images, on a site with 20,000 daily visits. I'd imagine a small proportion might play the game, for the sake of argument, lets say I can generate 2,000 human sort operations a day! It's a non-profit website, and the terminally curious will find it through my profile :) | As others have said, ranking 1-10 does not work that well because people have different levels. The problem with the Pick A-or-B method is that its not guaranteed for the system to be transitive (A can beat B, but B beats C, and C beats A). Having nontransitive comparison operators breaks sorting algorithms . With quicksort, against this example, the letters not chosen as the pivot will be incorrectly ranked against each other. At any given time, you want an absolute ranking of all the pictures (even if some/all of them are tied). You also want your ranking not to change unless someone votes . I would use the Pick A-or-B (or tie) method, but determine ranking similar to the Elo ratings system which is used for rankings in 2 player games (originally chess): The Elo player-rating system compares players’ match records against their opponents’ match records and determines the probability of the player winning the matchup. This probability factor determines how many points a players’ rating goes up or down based on the results of each match. When a player defeats an opponent with a higher rating, the player’s rating goes up more than if he or she defeated a player with a lower rating (since players should defeat opponents who have lower ratings). The Elo System: All new players start out with a base rating of 1600 WinProbability = 1/(10^(( Opponent’s Current Rating–Player’s Current Rating)/400) + 1) ScoringPt = 1 point if they win the match, 0 if they lose, and 0.5 for a draw. Player’s New Rating = Player’s Old Rating + (K-Value * (ScoringPt–Player’s Win Probability)) Replace "players" with pictures and you have a simple way of adjusting both pictures' rating based on a formula. You can then perform a ranking using those numeric scores. (K-Value here is the "Level" of the tournament. It's 8-16 for small local tournaments and 24-32 for larger invitationals/regionals. You can just use a constant like 20). With this method, you only need to keep one number for each picture which is a lot less memory intensive than keeping the individual ranks of each picture to each other picture. EDIT: Added a little more meat based on comments. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/164831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6521/"
]
} |
164,847 | Vi and Vim allow for really awesome customization, typically stored inside a .vimrc file. Typical features for a programmer would be syntax highlighting, smart indenting and so on. What other tricks for productive programming have you got, hidden in your .vimrc? I am mostly interested in refactorings, auto classes and similar productivity macros, especially for C#. | You asked for it :-) "{{{Auto Commands" Automatically cd into the directory that the file is inautocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')" Remove any trailing whitespace that is in the fileautocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif" Restore cursor position to where it was beforeaugroup JumpCursorOnEdit au! autocmd BufReadPost * \ if expand("<afile>:p:h") !=? $TEMP | \ if line("'\"") > 1 && line("'\"") <= line("$") | \ let JumpCursorOnEdit_foo = line("'\"") | \ let b:doopenfold = 1 | \ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) | \ let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 | \ let b:doopenfold = 2 | \ endif | \ exe JumpCursorOnEdit_foo | \ endif | \ endif " Need to postpone using "zv" until after reading the modelines. autocmd BufWinEnter * \ if exists("b:doopenfold") | \ exe "normal zv" | \ if(b:doopenfold > 1) | \ exe "+".1 | \ endif | \ unlet b:doopenfold | \ endifaugroup END"}}}"{{{Misc Settings" Necesary for lots of cool vim thingsset nocompatible" This shows what you are typing as a command. I love this!set showcmd" Folding Stuffsset foldmethod=marker" Needed for Syntax Highlighting and stufffiletype onfiletype plugin onsyntax enableset grepprg=grep\ -nH\ $*" Who doesn't like autoindent?set autoindent" Spaces are better than a tab characterset expandtabset smarttab" Who wants an 8 character tab? Not me!set shiftwidth=3set softtabstop=3" Use english for spellchecking, but don't spellcheck by defaultif version >= 700 set spl=en spell set nospellendif" Real men use gcc"compiler gcc" Cool tab completion stuffset wildmenuset wildmode=list:longest,full" Enable mouse support in consoleset mouse=a" Got backspace?set backspace=2" Line Numbers PWN!set number" Ignoring case is a fun trickset ignorecase" And so is Artificial Intellegence!set smartcase" This is totally awesome - remap jj to escape in insert mode. You'll never type jj anyway, so it's great!inoremap jj <Esc>nnoremap JJJJ <Nop>" Incremental searching is sexyset incsearch" Highlight things that we find with the searchset hlsearch" Since I use linux, I want thislet g:clipbrdDefaultReg = '+'" When I close a tab, remove the bufferset nohidden" Set off the other parenhighlight MatchParen ctermbg=4" }}}"{{{Look and Feel" Favorite Color Schemeif has("gui_running") colorscheme inkpot " Remove Toolbar set guioptions-=T "Terminus is AWESOME set guifont=Terminus\ 9else colorscheme metacosmendif"Status line gnarlinessset laststatus=2set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%]" }}}"{{{ Functions"{{{ Open URL in browserfunction! Browser () let line = getline (".") let line = matchstr (line, "http[^ ]*") exec "!konqueror ".lineendfunction"}}}"{{{Theme Rotatinglet themeindex=0function! RotateColorTheme() let y = -1 while y == -1 let colorstring = "inkpot#ron#blue#elflord#evening#koehler#murphy#pablo#desert#torte#" let x = match( colorstring, "#", g:themeindex ) let y = match( colorstring, "#", x + 1 ) let g:themeindex = x + 1 if y == -1 let g:themeindex = 0 else let themestring = strpart(colorstring, x + 1, y - x - 1) return ":colorscheme ".themestring endif endwhileendfunction" }}}"{{{ Paste Togglelet paste_mode = 0 " 0 = normal, 1 = pastefunc! Paste_on_off() if g:paste_mode == 0 set paste let g:paste_mode = 1 else set nopaste let g:paste_mode = 0 endif returnendfunc"}}}"{{{ Todo List Modefunction! TodoListMode() e ~/.todo.otl Calendar wincmd l set foldlevel=1 tabnew ~/.notes.txt tabfirst " or 'norm! zMzr'endfunction"}}}"}}}"{{{ Mappings" Open Url on this line with the browser \wmap <Leader>w :call Browser ()<CR>" Open the Project Plugin <F2>nnoremap <silent> <F2> :Project<CR>" Open the Project Pluginnnoremap <silent> <Leader>pal :Project .vimproject<CR>" TODO Modennoremap <silent> <Leader>todo :execute TodoListMode()<CR>" Open the TagList Plugin <F3>nnoremap <silent> <F3> :Tlist<CR>" Next Tabnnoremap <silent> <C-Right> :tabnext<CR>" Previous Tabnnoremap <silent> <C-Left> :tabprevious<CR>" New Tabnnoremap <silent> <C-t> :tabnew<CR>" Rotate Color Scheme <F8>nnoremap <silent> <F8> :execute RotateColorTheme()<CR>" DOS is for fools.nnoremap <silent> <F9> :%s/$//g<CR>:%s// /g<CR>" Paste Mode! Dang! <F10>nnoremap <silent> <F10> :call Paste_on_off()<CR>set pastetoggle=<F10>" Edit vimrc \evnnoremap <silent> <Leader>ev :tabnew<CR>:e ~/.vimrc<CR>" Edit gvimrc \gvnnoremap <silent> <Leader>gv :tabnew<CR>:e ~/.gvimrc<CR>" Up and down are more logical with g..nnoremap <silent> k gknnoremap <silent> j gjinoremap <silent> <Up> <Esc>gkainoremap <silent> <Down> <Esc>gja" Good call Benjie (r for i)nnoremap <silent> <Home> i <Esc>rnnoremap <silent> <End> a <Esc>r" Create Blank Newlines and stay in Normal modennoremap <silent> zj o<Esc>nnoremap <silent> zk O<Esc>" Space will toggle folds!nnoremap <space> za" Search mappings: These will make it so that going to the next one in a" search will center on the line it's found in.map N Nzzmap n nzz" Testingset completeopt=longest,menuone,previewinoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>"inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"" Swap ; and : Convenient.nnoremap ; :nnoremap : ;" Fix email paragraphsnnoremap <leader>par :%s/^>$//<CR>"ly$O#{{{ "lpjjj_%A#}}}jjzajj"}}}"{{{Taglist configurationlet Tlist_Use_Right_Window = 1let Tlist_Enable_Fold_Column = 0let Tlist_Exit_OnlyWindow = 1let Tlist_Use_SingleClick = 1let Tlist_Inc_Winwidth = 0"}}}let g:rct_completion_use_fri = 1"let g:Tex_DefaultTargetFormat = "pdf"let g:Tex_ViewRule_pdf = "kpdf"filetype plugin indent onsyntax on | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/164847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
]
} |
164,865 | Here at work, we are working on a newsletter system that our clients can use. As an intern one of my jobs is to help with the smaller pieces of the puzzle. In this case what I need to do is scan the logs of the email server for bounced messages and add the emails and the reason the email bounced to a "bad email database". The bad emails table has two columns: 'email' and 'reason'I use the following statement to get the information from the logs and send it to the Perl script grep " 550 " /var/log/exim/main.log | awk '{print $5 "|" $23 " " $24 " " $25 " " $26 " " $27 " " $28 " " $29 " " $30 " " $31 " " $32 " " $33}' | perl /devl/bademails/getbademails.pl If you have sugestions on a more efficient awk script, then I would be glad to hear those too but my main focus is the Perl script. The awk pipes "[email protected]|reason for bounce" to the Perl script. I want to take in these strings, split them at the | and put the two different parts into their respective columns in the database. Here's what I have: #!usr/bin/perl use strict;use warnings;use DBI;my $dbpath = "dbi:mysql:database=system;host=localhost:3306";my $dbh = DBI->connect($dbpath, "root", "******") or die "Can't open database: $DBI::errstr";while(<STDIN>) { my $line = $_; my @list = # ? this is where i am confused for (my($i) = 0; $i < 1; $i++) { if (defined($list[$i])) { my @val = split('|', $list[$i]); print "Email: $val[0]\n"; print "Reason: $val[1]"; my $sth = $dbh->prepare(qq{INSERT INTO bademails VALUES('$val[0]', '$val[1]')}); $sth->execute(); $sth->finish(); } }}exit 0; | Something like this would work: while(<STDIN>) { my $line = $_; chomp($line); my ($email,$reason) = split(/\|/, $line); print "Email: $email\n"; print "Reason: $reason"; my $sth = $dbh->prepare(qq{INSERT INTO bademails VALUES(?, ?)}); $sth->execute($email, $reason); $sth->finish(); } You might find it easier to just do the whole thing in Perl. "next unless / 550 /" could replace the grep and a regex could probably replace the awk. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
]
} |
164,879 | How can I write from Java to the Windows Event Log? | Log4J is a Java-based logging utility. The class NTEventLogAppender can be used to "append to the NT event log system". See the documentation here: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/nt/NTEventLogAppender.html Edit: There is a newer version, Log4j 2 "that provides significant improvements over its predecessor." | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/164879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8934/"
]
} |
164,896 | In the installation documentation to RoR it mentions that there are many limitations to running Ruby on Rails on Windows, and in some cases, whole libraries do not work. How bad are these limitations, should I always default to Linux to code / run RoR, and is Iron Ruby expected to fix these limitations or are they core to the OS itself? EDIT Thanks for the answer around installation and running on Linux, but I am really trying to understand the limitations in functionality as referenced in the installation documentation, and non-working libraries - I am trying to find a link to the comment, but it was referenced in an installation read me when I installed the msi package I think EDIT Thanks for the references to IronRuby lately, it is certainly a project to watch, and as it, obviously, is a .NET language, it will be invaluable if it lives up to the promises. Eventually, however, in my case, I just bit the bullet and installed an Ubuntu server. <bias> I should've done it years ago </bias> | Here's an overview of the current issues with Rails on Windows: Ruby and Rails are slower on Windows than they are on Unix-like OS's. A few gems and libraries don't work on Windows. Some Unix-isms aren't available on Windows ( examples ). The community is mostly on either Mac or Linux ( This is a particularly hard one to deal with; nobody wants to be alone on one island when the rest of the tribe are partying, having fun and getting along great over on the other island. Community is important. It seems that most Windows developers that start with Rails quickly switch to a Mac or Linux. However , the small community of Windows Ruby users that do persist are extremely friendly, dedicated and knowledgeable - go say hi . ) Note much of the advice that follows is now outdated due to the magnificent efforts of the RubyInstaller team in bringing stability, compatibility and performance to Ruby on Windows. I no longer have to use VirtualBox, which says a lot about how far Ruby on Windows has come. If you want more technical detail, the following are required reading. : Ruby for Windows - Part 1 Is Windows a supported platform for Ruby? I guess not Testing the new One-Click Ruby Installer for Windows Still playing with Ruby on Windows Chatting with Luis Lavena (Ruby on Windows) Choice quote from that last one is: AkitaOnRails: The most obvious thing is that any Gem with C Extensions without proper binaries for Windows will fail. Trying to execute shell commands will fail and RubyInline as well. What else? Luis Lavena: Hehe, that's just the tip of the iceberg Having said all that, I don't find developing with Rails on Windows too painful. Using Ruby is, for the most part, a pleasure. I'd avoid InstantRails because, to be frank, it's just as easy to install Ruby properly using the one-click installer, then doing a gem install rails . If you need Apache and MySQL, WAMP is a good bet, although even these aren't required if you just stick with Mongrel and SQLite. What I've taken to doing recently is running VirtualBox with an instance of Ubuntu Server that closely mirrors the deployment server. I map a network drive to the Ubuntu Server, then I edit and run my code directly on the VM. It uses hardly any memory (it's currently using ~43MB; contrast that with Firefox, which is using ~230MB) and Rails actually performs better than running it natively on Windows. Plus you can experiment with your virtual server in relative safety. It's a really nice setup, I highly recommend it. Finally, here are a couple of Ruby/Rails blogs aimed at Windows users: DEV_MEM.dump_to(:blog) (Luis Lavena) Softies on Rails Ruby On Windows | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/164896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
]
} |
164,901 | Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on. I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup. | Don't try and obfuscate or encrypt the code - it will never work. I would suggest selling the Django application "as a service" - either host it for them, or sell them the code and support . Write up a contract that forbids them from redistributing it. That said, if you were determined to obfuscate the code in some way - you can distribute python applications entirely as .pyc (Python compiled byte-code).. It's how Py2App works. It will still be re-distributable, but it will be very difficult to edit the files - so you could add some basic licensing stuff, and not have it foiled by a few # s.. As I said, I don't think you'll succeed in anti-piracy via encryption or obfuscation etc.. Depending on your clients, a simple contract, and maybe some really basic checks will go a long much further than some complicated decryption system (And make the experience of using your application better , instead of hopefully not any worse ) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/164901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
]
} |
164,903 | How can I capture enter keypresses anywhere on my form and force it to fire the submit button event? | If you set your Form 's AcceptButton property to one of the Button s on the Form , you'll get that behaviour by default. Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event. You can check for the Enter key and take the necessary action. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/164903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
164,926 | When displaying the value of a decimal currently with .ToString() , it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places. Do I use a variation of .ToString() for this? | decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m or decimalVar.ToString("0.##"); // returns "0.5" when decimalVar == 0.5m or decimalVar.ToString("0.00"); // returns "0.50" when decimalVar == 0.5m | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/164926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692/"
]
} |
164,931 | I'm looking at introducing multi-lingual support to a mature CGI application written in Perl. I had originally considered rolling my own solution using a Perl hash (stored on disk) for translation files but then I came across a CPAN module which appears to do just what I want ( i18n ). Does anyone have any experience with internationalization (specifically the i18n CPAN module) in Perl? Is the i18n module the preferred method for multi-lingual support or should I reconsider a custom solution? Thanks | There is a Perl Journal article on software localisation. It will provide you with a good idea of what you can expect when adding multi-lingual support. It's beautifully written and humourous. Specifically, the article is written by the folks who wrote and maintain Locale::Maketext , so I would recommend that module simply based upon the amount of pain it is clear the authors have had to endure to make it work correctly. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20790/"
]
} |
164,964 | I'm trying to determine the asymptotic run-time of one of my algorithms, which uses exponents, but I'm not sure of how exponents are calculated programmatically. I'm specifically looking for the pow() algorithm used for double-precision, floating point numbers. | I've had a chance to look at fdlibm's implementation. The comments describe the algorithm used: * n * Method: Let x = 2 * (1+f) * 1. Compute and return log2(x) in two pieces: * log2(x) = w1 + w2, * where w1 has 53-24 = 29 bit trailing zeros. * 2. Perform y*log2(x) = n+y' by simulating muti-precision * arithmetic, where |y'|<=0.5. * 3. Return x**y = 2**n*exp(y'*log2) followed by a listing of all the special cases handled (0, 1, inf, nan). The most intense sections of the code, after all the special-case handling, involve the log2 and 2** calculations. And there are no loops in either of those. So, the complexity of floating-point primitives notwithstanding, it looks like a asymptotically constant-time algorithm. Floating-point experts (of which I'm not one) are welcome to comment. :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55/"
]
} |
164,967 | I have an Excel application in which I want to present the user with a list of the Data Source Names (ie: DSN's), whereby s/he can choose what data source to use. Hopefully once I've got the list, I can easily access the DSN properties to connect to the appropriate database. Please note, I do not want to use a DSN-less connection. | The DSN entries are stored in the registry in the following keys. HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data SourcesHKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources This contains the list of all defined DSN. This acts as an global index and the specific details for each DSN are stored in a key with the DSN name under: HKEY_CURRENT_USER\Software\ODBC\ODBC.INIHKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI Create some entries in both User DSN and System DSN tabs from Data Sources (ODBC) control panel applet and check how these values are stored in the registry. The following example enumerate the DSN defined for the user trough Control Panel > Administrative Tools > Data Sources (ODBC) [User Dsn Tab]. http://support.microsoft.com/kb/178755 Option Explicit Private Declare Function RegOpenKeyEx Lib "advapi32.dll" _ Alias "RegOpenKeyExA" _ (ByVal hKey As Long, _ ByVal lpSubKey As String, _ ByVal ulOptions As Long, _ ByVal samDesired As Long, phkResult As Long) As Long Private Declare Function RegEnumValue Lib "advapi32.dll" _ Alias "RegEnumValueA" _ (ByVal hKey As Long, _ ByVal dwIndex As Long, _ ByVal lpValueName As String, _ lpcbValueName As Long, _ ByVal lpReserved As Long, _ lpType As Long, _ lpData As Any, _ lpcbData As Long) As Long Private Declare Function RegCloseKey Lib "advapi32.dll" _ (ByVal hKey As Long) As Long Const HKEY_CLASSES_ROOT = &H80000000 Const HKEY_CURRENT_USER = &H80000001 Const HKEY_LOCAL_MACHINE = &H80000002 Const HKEY_USERS = &H80000003 Const ERROR_SUCCESS = 0& Const SYNCHRONIZE = &H100000 Const STANDARD_RIGHTS_READ = &H20000 Const STANDARD_RIGHTS_WRITE = &H20000 Const STANDARD_RIGHTS_EXECUTE = &H20000 Const STANDARD_RIGHTS_REQUIRED = &HF0000 Const STANDARD_RIGHTS_ALL = &H1F0000 Const KEY_QUERY_VALUE = &H1 Const KEY_SET_VALUE = &H2 Const KEY_CREATE_SUB_KEY = &H4 Const KEY_ENUMERATE_SUB_KEYS = &H8 Const KEY_NOTIFY = &H10 Const KEY_CREATE_LINK = &H20 Const KEY_READ = ((STANDARD_RIGHTS_READ Or _ KEY_QUERY_VALUE Or _ KEY_ENUMERATE_SUB_KEYS Or _ KEY_NOTIFY) And _ (Not SYNCHRONIZE)) Const REG_DWORD = 4 Const REG_BINARY = 3 Const REG_SZ = 1 Private Sub Command1_Click() Dim lngKeyHandle As Long Dim lngResult As Long Dim lngCurIdx As Long Dim strValue As String Dim lngValueLen As Long Dim lngData As Long Dim lngDataLen As Long Dim strResult As String lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, _ "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", _ 0&, _ KEY_READ, _ lngKeyHandle) If lngResult <> ERROR_SUCCESS Then MsgBox "Cannot open key" Exit Sub End If lngCurIdx = 0 Do lngValueLen = 2000 strValue = String(lngValueLen, 0) lngDataLen = 2000 lngResult = RegEnumValue(lngKeyHandle, _ lngCurIdx, _ ByVal strValue, _ lngValueLen, _ 0&, _ REG_DWORD, _ ByVal lngData, _ lngDataLen) lngCurIdx = lngCurIdx + 1 If lngResult = ERROR_SUCCESS Then strResult = strResult & lngCurIdx & ": " & Left(strValue, lngValueLen) & vbCrLf End If Loop While lngResult = ERROR_SUCCESS Call RegCloseKey(lngKeyHandle) Call MsgBox(strResult, vbInformation) End Sub | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/164967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354/"
]
} |
164,979 | I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance: Matches CW3 9SS SE5 0EG SE50EG se5 0eg WC2H 7LT No Match aWC2H 7LT WC2H 7LTa WC2H How do I solve this problem? | I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; archive of XML , see Wikipedia for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given. The RegEx supplied by the UK Government was: ([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2}) As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/164979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
]
} |
164,981 | I have a PHP script that uses the system() call to execute other (potentially long-running) programs (for interest: NCBI BLAST, phrap, primer3 and other programs for doing DNA sequence analysis and assembly). I'm running under Windows XP, using the CLI version of PHP from a command prompt, or as a service. (In either case I communicate with it via a queue of tasks in a database table). Under PHP4: when I hit Ctrl + C the script is stopped and any child process running at the time is also stopped.Under PHP5: when I hit Ctrl + C the script stops, but the child is left running. Similarly, when running the script as a service, stopping the service when running it with PHP4 stops the child, with PHP5 the child continues to run. I have tried writing a minimal test application, and found the same behaviour. The test PHP script just uses system() to execute a C program (that just sleeps for 30 seconds) and then waits for a key to be pressed. I had a look at the source for PHP 4.4.9 and 5.2.6 but could see no differences in the system() code that looked like they would cause this. I also had a quick look at the startup code for the CLI application and didn't see any differences in signal handling. Any hints on what might have caused this, or a workaround, would be appreciated. Thanks. | I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; archive of XML , see Wikipedia for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given. The RegEx supplied by the UK Government was: ([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2}) As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/164981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
164,990 | This is a continuation question from a previous question I have asked I now have a /externals directory in the root of my project tree. Inside this I have a reference to another project. I'm able to script the build of all my externals in the main project NAnt script. The result of these builds are as follows: /externals/external-project1/build/buildartifacts/{dlls|html|js} /externals/external-project2/build/buildartifacts/{dlls|html|js} This is all well and good, but now I'm curious as to how my main project should reference these build artifacts. For example, let's say that external project builds a DLL that some of my codebase depends on. Should I simply reference the DLL in the build artifacts directory or should I implement another NAnt task that copies these to a /thirdparty/libs/ folder? This means that my build is now dependent on the ability to build this external project (which could either be internal, or thirdparty). Is it a good idea to check in the latest set of build artifacts to ensure that the main build won't break because of dependent builds breaking? Hope that's clear enough. Just writing this down has a least clarified the problem for me :-). --Edit-- Thanks guys. I think I'm going to implement the "checkout a revision", but since the builds are so quick I'm not going to check in any build artifiacts. Also going to have to figure out how to deal with the dependencies of the external project (eg: prototype, swfobject, etc). | I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; archive of XML , see Wikipedia for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given. The RegEx supplied by the UK Government was: ([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2}) As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/164990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894/"
]
} |
165,042 | Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date? I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date. I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect. | I have found that putting an '=' before the double quotes will accomplish what you want. It forces the data to be text. eg. ="2008-10-03",="more text" EDIT (according to other posts) : because of the Excel 2007 bug noted by Jeffiekins one should use the solution proposed by Andrew : "=""2008-10-03""" | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/165042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
165,043 | This is an excerpt of code from a class I am working with in Java (below). Obviously the code is defining a static variable named EPSILON with the data type double. What I don't understand is the "1E-14" part. What kind of number is that? What does it mean? final double EPSILON = 1E-14; | In your case, this is equivalent to writing: final double EPSILON = 0.00000000000001; except you don't have to count the zeros. This is called scientific notation and is helpful when writing very large or very small numbers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
165,066 | I'm having a problem running a VS 2005 app on some machines and not others. I looked up the error message on google and found a post by someone who had the same error and fixed it by uninstalling and reinstalling the .NET framework. When I try to do that, Windows won't let me because it is in use. Am I expected to uninstall everything that is using the framework first, then uninstall the framework, then reinstall, etc.? Does anyone know of an easier way? | Check out Aaron Stebner's .NET Framework Cleanup Tool . Works quite nicely. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
165,082 | I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate: <table><tr><td class="case">123456</td></tr></table> I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz). So I'd like that "123456" to be changed to a link of this form: <a href="http://bugs.example.com/fogbugz/default.php?123456">123456</a> Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number. | Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript.. function makeCasesClickable(){ var cells = document.getElementsByTagName('td') for (var i = 0, cell; cell = cells[i]; i++){ if (cell.className != 'case') continue var caseId = cell.innerHTML cell.innerHTML = '' var link = document.createElement('a') link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId link.appendChild(document.createTextNode(caseId)) cell.appendChild(link) }} You can apply it with something like onload = makeCasesClickable , or simply include it right at the end of the page. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19207/"
]
} |
165,092 | Basically I wanted to do something like git push mybranch to repo1, repo2, repo3 right now I'm just typing push many times, and if I'm in a hurry to the the pushing done, I just send them all to the background git push repo1 & git push repo2 & I'm just wondering if git natively supports what I want to do, or if maybe there's a clever script out there, or maybe a way to edit the local repo config file to say a branch should be pushed to multiple remotes. | You can have several URLs per remote in git, even though the git remote command did not appear to expose this last I checked. In .git/config , put something like this: [remote "public"] url = [email protected]:kch/inheritable_templates.git url = kch@homeserver:projects/inheritable_templates.git Now you can say “ git push public ” to push to both repos at once. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/165092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
]
} |
165,101 | The following code: template <typename S, typename T>struct foo { void bar();};template <typename T>void foo <int, T>::bar() {} gives me the error invalid use of incomplete type 'struct foo<int, T>'declaration of 'struct foo<int, T>' (I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument: template <typename S>struct foo { void bar();};template <>void foo <int>::bar() {} then it compiles correctly. | You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. template <typename U = T> struct Nested ) would work. Or else you can try deriving from another template that partially specializes (works if you use the this->member notation, otherwise you will encounter compiler errors). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/165101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
]
} |
165,102 | What's wrong with Linq to SQL? Or - what about Linq to SQL would make it unsuitable for a project, either new or existing? I want to hear about why you would not choose Linq to SQL for a particular project - including what project parameters make it unsuitable. | It is not very adaptable to changes in the database schema. You have to rebuild the dbml layer and regenerate your data contexts. Like any ORM (I am not getting into the debate as to whether it is an ORM or not), you do have to be aware what SQL is being generated, and how that will influence your calls. Inserts are not batched, so can be high cost in performance. It's being sunsetted in favour of Entity Framework Despite the fact it is using a provider model that will allow providers to be built for other DBMS platforms, only SQL Server is supported. [ EDIT @ AugustLights - In my experience: ] Lazy loading may take a bit of hacking to get working. That being said, I think it it is very handy if used correctly | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16942/"
]
} |
165,156 | In mysql, how do I get the primary key used for an insert operation, when it is autoincrementing. Basically, i want the new autoincremented value to be returned when the statement completes. Thanks! | Your clarification comment says that you're interested in making sure that LAST_INSERT_ID() doesn't give the wrong result if another concurrent INSERT happens. Rest assured that it is safe to use LAST_INSERT_ID() regardless of other concurrent activity. LAST_INSERT_ID() returns only the most recent ID generated during the current session. You can try it yourself: Open two shell windows, run mysqlclient in each and connect todatabase. Shell 1: INSERT into a table with anAUTO_INCREMENT key. Shell 1: SELECT LAST_INSERT_ID(),see result. Shell 2: INSERT into the same table. Shell 2: SELECT LAST_INSERT_ID(),see result different from shell 1. Shell 1: SELECT LAST_INSERT_ID()again, see a repeat of earlierresult. If you think about it, this is the only way that makes sense. All databases that support auto-incrementing key mechanisms must act this way. If the result depends on a race condition with other clients possibly INSERTing concurrently, then there would be no dependable way to get the last inserted ID value in your current session. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24694/"
]
} |
165,170 | I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix. For example, the day this question was asked would display "Thu Oct 2nd". I'm using Ruby 1.8.7, and Time.strftime just doesn't seem to do this. I'd prefer a standard library if one exists. | Use the ordinalize method from 'active_support'. >> time = Time.new=> Fri Oct 03 01:24:48 +0100 2008>> time.strftime("%a %b #{time.day.ordinalize}")=> "Fri Oct 3rd" Note, if you are using IRB with Ruby 2.0, you must first run: require 'active_support/core_ext/integer/inflections' | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/165170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12887/"
]
} |
165,175 | I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable x is equal to the int 0 . If this is true the ABSOLUTE value of the variable y is returned... this is when I lose the plot, why would the return statement then go on to include <= ESPILON ? Surely this means less than or equal to the value of epsilon? if so how is that working? If it doesn't mean that then what does it mean? (JAVA CODE) final double EPSILON = 1E-14;if (x == 0) return Math.abs(y) <= EPSILON; | Floating-point math is by its nature inaccurate, so rather than testing for equivalence (which is always a bad idea), instead the developer has chosen a small number (1x10^-14 in this case) as the acceptable tolerance for proximity to zero. The return statement returns a comparison, so what this will do is take the absolute value of y, and return true if and only if it is sufficiently close to zero, where sufficiently close is defined by EPSILON. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
165,188 | I have some c(++) code that uses sprintf to convert a uint_64 to a string. This needs to be portable to both linux and Solaris. On linux we use %ju, but there does not appear to be any equivalent on Solaris. The closest I can find is %lu, but this produces incorrect output. Some sample code: #include <stdio.h>#include <sys/types.h>#ifdef SunOStypedef uint64_t u_int64_t;#endifint main(int argc, char **argv) { u_int64_t val = 123456789123L;#ifdef SunOS printf("%lu\n", val);#else printf("%ju\n", val);#endif} On linux, the output is as expected; on Solaris 9 (don't ask), it's "28" What can I use? | If you have have inttypes.h available you can use the macros it provides: printf( "%" PRIu64 "\n", val); Not pretty (I seem to be saying that a lot recently), but it works. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16977/"
]
} |
165,212 | How can I check the umask of a program which is currently running? [update: another process, not the current process.] | You can attach gdb to a running process and then call umask in the debugger: (gdb) attach <your pid>...(gdb) call umask(0)[Switching to Thread -1217489200 (LWP 11037)]$1 = 18 # this is the umask(gdb) call umask(18) # reset umask$2 = 0(gdb) (note: 18 corresponds to a umask of O22 in this example) This suggests that there may be a really ugly way to get the umask using ptrace. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/165212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
165,231 | Although I played with it before, I'm finally starting to use Dvorak (Simplified) regularly. I've been in a steady relationship with Vim for several years now, and I'm trying to figure out the best way to remap the key bindings to suit my newfound Dvorak skills. How do you remap Vim's key bindings to best work with Dvorak? Explanations encouraged! | I use one of the more common recommended keybindings : Dvorak it!no d hno h jno t kno n lno s :no S :no j dno l nno L NAdded benefitsno - $no _ ^no N <C-w><C-w>no T <C-w><C-r>no H 8<Down>no T 8<Up>no D <C-w><C-r> Movement keys stay in the same location. Other changes: Delete 'd' -> Junk 'j' Next 'n' -> Look 'l' Previous 'N' -> Look Back 'L' There were also some changes for familiarity, 's'/'S' can be used to access command mode (the old location of the :, which still works). Added Benefits End of line '$' -also- '-' Beginning of line '^' -also- '_' Move up 8 'T' Move down 8 'H' Next window <C-w><C-w> -also- 'N' Swap windows <C-w><C-r> -also- 'D' -Adam | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/165231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
} |
165,253 | If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of draw() . How can I force myimg not to be cached? <html> <head> <script type="text/javascript"> function draw(){ var canvas = document.getElementById('canv'); var ctx = canvas.getContext('2d'); var rx; var ry; var i; myimg = new Image(); myimg.src = 'http://ohm:8080/cgi-bin/nextimg' rx=Math.floor(Math.random()*100)*10 ry=Math.floor(Math.random()*100)*10 ctx.drawImage(myimg,rx,ry); window.setTimeout('draw()',0); } </script> </head> <body onload="draw();"> <canvas id="canv" width="1024" height="1024"></canvas> </body></html> | The easiest way is to sling an ever-changing querystring onto the end: var url = 'http://.../?' + escape(new Date()) Some people prefer using Math.random() for that instead of escape(new Date()) . But the correct way is probably to alter the headers the web server sends to disallow caching. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
165,314 | I've always assumed that before I can use the Dvorak layout I need to purchase a Dvorak keyboard. But I can't find one on Amazon. Is it simply a matter of popping the keys off a Qwerty keyboard and moving them around? | To help you learn your way around the keyboard layout, you can physically rearrange the keys on your Qwerty keyboard. Or you can simply re-label the keys with stickers. I personally learned to type using the Dvorak layout without re-labeling or re-arranging keys, and found that it was not difficult. Most modern OSes allow you to remap any keyboard to the Dvorak layout. Windows XP/Vista: you can setyour mappings through ControlPanel->Regional and LanguageOptions->Languages->Details.... Mac OSX: System Preferences -> International -> Input Menu (thanks jmah) Ubuntu: System -> Preferences -> Keyboard, Layouts Tab, Add..., Select the Devorak layout of your choice and optionaly set as default. You can then right-click your panel, select "Add to panel" and choose keyboard indicator. You can then switch between layouts. (Thanks Vagnerr) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
]
} |
165,316 | From the MSDN article on STAThread: Indicates that the COM threading model for an application is single-threaded apartment (STA). (For reference, that's the entire article .) Single-threaded apartment... OK, that went over my head. Also, I read somewhere that unless your application uses COM interop, this attribute actually does nothing at all. So what exactly does it do, and how does it affect multithreaded applications? Should multithreaded applications (which includes anything from anyone using Timer s to asynchronous method calls, not just threadpools and the like) use MTAThread, even if it's 'just to be safe'? What does STAThread and MTAThread actually do? | Apartment threading is a COM concept; if you're not using COM, and none of the APIs you call use COM "under the covers", then you don't need to worry about apartments. If you do need to be aware of apartments, then the details can get a little complicated ; a probably-oversimplified version is that COM objects tagged as STA must be run on an STAThread, and COM objects marked MTA must be run on an MTA thread. Using these rules, COM can optimize calls between these different objects, avoiding marshaling where it isn't necessary. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/165316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
]
} |
165,383 | We have an SQL 2005 database backend for our website, currently about 10GB in size. There are a lot more reads than writes, though I don't have the exact statistics. We're upgrading our database server and I was thinking of getting 4 disks and setting them up in two RAID 1 arrays - one for the data files and the other for the OS and log files. Would this be the optimal set-up or would RAID 5 be better for the data files? RAID 10 gets a bit pricey and is probably overkill for us. At this stage SQL Server should keep much of the database in RAM (8GB), but it will grow, so I don't want to entirely rely on that. Edit: we definitely want redundancy on a production server, so RAID 0 by itself is out. RAID 10 is nice, but might be a bit expensive for us. | Your concept of using independent RAID 1 mirrors is the correct strategy. We have implemented similar scenarios at my work and they work very well. RAID 1 RAID 1 gives you the speed of 1 disk for writing but 2 disks for reading. When you write data to a RAID 1 array, it has to write that data to both disks, so you do not gain any performance increase, however this is where you get your data security. When reading from a RAID 1 array the controller will read from both disks as they have the same data on them. RAID 5 This is useful for protecting larger amounts of data. The cost of RAID 5 increases a lot slower than RAID 1 (or RAID 0+1 once you are doing capacities beyond the size of the individual disks) for the same amount of data. If you want to protect 600gb in with RAID 5 you can achieve that with 4x200gb drives or 3x300gb drives, requiring 800-900gb of total purchased drive space. RAID 1 would be 2x600gb drives requiring 1,200gb of purchased space (with 600gb drives being quite more expensive) or RAID 0+1 allowing you to use less expensive capacity drives (ie: 4x300gb or 6x200gb) but still requires a total of 1,200gb of purchased space. RAID 0+1 Offers similar advantages as RAID 1 taking it up another notch with the striping across disks. I am assuming that if you are concerned about higher simultaneous reads, you will also be using multi-processors/multi-cores. You will be processing multiple queries at once and so the striping isn't going to help as much. You would see a better advantage on a RAID 0+1 for single applications using large data files, such as video editing. When I was researching this same issue a while ago for a customer I found this article to be very interesting http://blogs.zdnet.com/Ou/?p=484 . On the second page he dicusses the change from a RAID 0+1 to independent RAID 1 arrays creating a lot of performance improvements. This was on a much larger scale (a 20 disk and 16 disk SAN) but same concepts. The ability for SQL Server to load balance the data between multiple volumes instead of using just basic uninformed striping of RAID 0+1 is a great concept. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20336/"
]
} |
165,401 | I'm looking for a way to validate the SQL schema on a production DB after updating an application version. If the application does not match the DB schema version, there should be a way to warn the user and list the changes needed. Is there a tool or a framework (to use programatically) with built-in features to do that?Or is there some simple algorithm to run this comparison? Update: Red gate lists "from $395". Anything free? Or more foolproof than just keeping the version number? | Try this SQL. - Run it against each database. - Save the output to text files. - Diff the text files. /* get list of objects in the database */SELECT name, type FROM sysobjectsORDER BY type, name/* get list of columns in each table / parameters for each stored procedure */SELECT so.name, so.type, sc.name, sc.number, sc.colid, sc.status, sc.type, sc.length, sc.usertype , sc.scale FROM sysobjects so , syscolumns sc WHERE so.id = sc.id ORDER BY so.type, so.name, sc.name/* get definition of each stored procedure */SELECT so.name, so.type, sc.number, sc.text FROM sysobjects so , syscomments sc WHERE so.id = sc.id ORDER BY so.type, so.name, sc.number | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/165401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1363/"
]
} |
165,404 | I'm looking for some good references for learning how to model 2d physics in games. I am not looking for a library to do it for me - I want to think and learn, not blindly use someone else's work. I've done a good bit of Googling, and while I've found a few tutorials on GameDev, etc., I find their tutorials hard to understand because they are either written poorly, or assume a level of mathematical understanding that I don't yet possess. For specifics - I'm looking for how to model a top-down 2d game, sort of like a tank combat game - and I want to accurately model (among other things) acceleration and speed, heat buildup of 'components,' collisions between models and level boundaries, and missile-type weapons. Websites, recommended books, blogs, code examples - all are welcome if they will aid understanding. I'm considering using C# and F# to build my game, so code examples in either of those languages would be great - but don't let language stop you from posting a good link. =) Edit : I don't mean that I don't understand math - it's more the case that I don't know what I need to know in order to understand the systems involved, and don't really know how to find the resources that will teach me in an understandable way. | Here are some resources I assembled a few years ago. Of note is the Verlet Integration.I am also including links to some open source and commercial physics engines I found at that time. There is a stackoverflow article on this subject here: 2d game physics? Physics Methods Verlet Integration (Wikipedia Article) Advanced Character Physics (Great article! Includes movement, collisions, joints, and other constraints.) Books "Game Physics Engine Development" , Ian Millington -- I own this book and highly recommend it. The book builds a physics engine in C++ from scratch. The Author starts with basic particle physics and then adds "laws of motion", constraints, rigid-body physics and on and on. He includes well documented source code all the way through. Physics Engines Tokamak (Open source physics API) APE (Actionscript Physics Engine) FLADE (Flash Dynamics Engine) Fisix Engine (another Flash Actionscript engine) Simple Physics Engine (commercial) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16942/"
]
} |
165,424 | I have a ListBox which until recently was displaying a flat list of items. I was able to use myList.ItemContainerGenerator.ConainerFromItem(thing) to retrieve the ListBoxItem hosting "thing" in the list. This week I've modified the ListBox slightly in that the CollectionViewSource that it binds to for its items has grouping enabled. Now the items within the ListBox are grouped underneath nice headers. However, since doing this, ItemContainerGenerator.ContainerFromItem has stopped working - it returns null even for items I know are in the ListBox. Heck - ContainerFromIndex(0) is returning null even when the ListBox is populated with many items! How do I retrieve a ListBoxItem from a ListBox that's displaying grouped items? Edit: Here's the XAML and code-behind for a trimmed-down example. This raises a NullReferenceException because ContainerFromIndex(1) is returning null even though there are four items in the list. XAML: <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" Title="Window1"> <Window.Resources> <XmlDataProvider x:Key="myTasks" XPath="Tasks/Task"> <x:XData> <Tasks xmlns=""> <Task Name="Groceries" Type="Home"/> <Task Name="Cleaning" Type="Home"/> <Task Name="Coding" Type="Work"/> <Task Name="Meetings" Type="Work"/> </Tasks> </x:XData> </XmlDataProvider> <CollectionViewSource x:Key="mySortedTasks" Source="{StaticResource myTasks}"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="@Type" /> <scm:SortDescription PropertyName="@Name" /> </CollectionViewSource.SortDescriptions> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="@Type" /> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> </Window.Resources> <ListBox x:Name="listBox1" ItemsSource="{Binding Source={StaticResource mySortedTasks}}" DisplayMemberPath="@Name" > <ListBox.GroupStyle> <GroupStyle> <GroupStyle.HeaderTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </GroupStyle.HeaderTemplate> </GroupStyle> </ListBox.GroupStyle> </ListBox></Window> CS: public Window1(){ InitializeComponent(); listBox1.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;}void ItemContainerGenerator_StatusChanged(object sender, EventArgs e){ if (listBox1.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { listBox1.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; var i = listBox1.ItemContainerGenerator.ContainerFromIndex(1) as ListBoxItem; // select and keyboard-focus the second item i.IsSelected = true; i.Focus(); }} | You have to listen and react to the ItemsGenerator.StatusChanged Event and wait until the ItemContainers are generated before you can access them with ContainerFromElement. Searching further, I've found a thread in the MSDN forum from someone who has the same problem. This seems to be a bug in WPF, when one has a GroupStyle set. The solution is to punt the access of the ItemGenerator after the rendering process. Below is the code for your question. I tried this, and it works: void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { if (listBox1.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { listBox1.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input, new Action(DelayedAction)); } } void DelayedAction() { var i = listBox1.ItemContainerGenerator.ContainerFromIndex(1) as ListBoxItem; // select and keyboard-focus the second item i.IsSelected = true; i.Focus(); } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/165424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
]
} |
165,455 | Just wondering why people like case sensitivity in a programming language? I'm not trying to start a flame war just curious thats all. Personally I have never really liked it because I find my productivity goes down when ever I have tried a language that has case sensitivity, mind you I am slowly warming up/getting used to it now that I'm using C# and F# alot more then I used to. So why do you like it? Cheers | Consistency. Code is more difficult to read if "foo", "Foo", "fOO", and "fOo" are considered to be identical. SOME PEOPLE WOULD WRITE EVERYTHING IN ALL CAPS, MAKING EVERYTHING LESS READABLE. Case sensitivity makes it easy to use the "same name" in different ways, according to a capitalization convention, e.g., Foo foo = ... // "Foo" is a type, "foo" is a variable with that type | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/165455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
]
} |
165,458 | Which is the most correct code? if (HttpContext.Current.Response.Cookies[authCookieName] != null) { HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";} or if (HttpContext.Current != null) if (HttpContext.Current.Response != null) if (HttpContext.Current.Response.Cookies != null) if (HttpContext.Current.Response.Cookies[authCookieName] != null) HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value"; | If any one of HttpContext, HttpContext.Current, HttpContext.Current.Response, or Http.Current.Response.Cookies is null, you're already in trouble. Let the exception happen and fix your web server. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24395/"
]
} |
165,495 | How can I detect mouse clicks regardless of the window the mouse is in? Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out. I found this on microsoft's site: http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx But I don't see how I can detect or pick up the notifications listed. Tried using pygame's pygame.mouse.get_pos() function as follows: import pygamepygame.init()while True: print pygame.mouse.get_pos() This just returns 0,0.I'm not familiar with pygame, is something missing? In anycase I'd prefer a method without the need to install a 3rd party module.(other than pywin32 http://sourceforge.net/projects/pywin32/ ) | The only way to detect mouse events outside your program is to install a Windows hook using SetWindowsHookEx . The pyHook module encapsulates the nitty-gritty details. Here's a sample that will print the location of every mouse click: import pyHookimport pythoncomdef onclick(event): print event.Position return Truehm = pyHook.HookManager()hm.SubscribeMouseAllButtonsDown(onclick)hm.HookMouse()pythoncom.PumpMessages()hm.UnhookMouse() You can check the example.py script that is installed with the module for more info about the event parameter. pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the tutorial : Any application that wishes to receive notifications of global input events must have a Windows message pump. The easiest way to get one of these is to use the PumpMessages method in the Win32 Extensions package for Python. [...] When run, this program just sits idle and waits for Windows events. If you are using a GUI toolkit (e.g. wxPython), this loop is unnecessary since the toolkit provides its own. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/165495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24718/"
]
} |
165,496 | So i have a piece of assembly that needs to call a function with the fastcall calling convention on windows, but gcc doesn't (afaict) support it. GCC does provide the regparm attribute but that expects the first 3 parameters to be passed in eax, edx and ecx, whereas fastcall expects the first two parameters to be passed in ecx and edx. I'm merely trying to avoid effectively duplicating a few code paths, so this isn't exactly critical, but it would be great if it were avoidable. | GCC does support fastcall , via __attribute__((fastcall)) . It appears to have been introduced in GCC 3.4. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784/"
]
} |
165,539 | Can the iPhone SDK take advantage of the iPhone's proximity sensors? If so, why hasn't anyone taken advantage of them? I could picture a few decent uses. For example, in a racing game, you could put your finger on the proximity sensor to go instead of taking up screen real-estate with your thumb. Of course though, if this was your only option, then iPod touch users wouldn't be able to use the application. Does the proximity sensor tell how close you are, or just that something is in front of it? | Assuming you mean the sensor that shuts off the screen when you hold it to your ear, I'm pretty sure that is just an infrared sensor inside the ear speaker. If you start the phone app (you don't have to be making a call) and hold something to cast a shadow over the ear speaker, you can make the display shut off. When you asked this question it was not accessible via the public API. You can now access the sensor's state via UIDevice's proximityState property. However, it wouldn't be that useful for games, since it is only an on/off thing, not a near/far measure. Plus, it's only available on the iPhone and not the iPod touch. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
]
} |
165,637 | Whenever I use the signal/slot editor dialog box, I have to choose from the existing list of slots. So the question is how do I create a custom named slot? | This does seem to be possible in the version of Qt Designer 4.5.2, but it can't be done from the Signal/Slot Editor dock-widget in the main window. This is what worked for me Switch to Edit Signals/Slots mode (F4) Drag and drop from the widget which is to emit the signal, to the widget which is to receive the signal. A Configure Connection dialog appears, showing the signals for the emitting widget, and the slots for the receiving widget. Click Edit... below the slots column on the right. A Signals/Slots of ReceivingWidget dialog appears. In here its is possible to click the plus icon beneath slots to add a new slot of any name. You can then go back and connect to your new slot in the Configure Connection dialog, or indeed in the Signal/Slot Editor dockwidget back in the main window. Caveat: I'm using PyQt, and I've only tried to use slots added in this way from Python, not from C++, so your mileage may vary... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24560/"
]
} |
165,648 | How can I display a calendar control (date picker) in Oracle forms 9/10? | This does seem to be possible in the version of Qt Designer 4.5.2, but it can't be done from the Signal/Slot Editor dock-widget in the main window. This is what worked for me Switch to Edit Signals/Slots mode (F4) Drag and drop from the widget which is to emit the signal, to the widget which is to receive the signal. A Configure Connection dialog appears, showing the signals for the emitting widget, and the slots for the receiving widget. Click Edit... below the slots column on the right. A Signals/Slots of ReceivingWidget dialog appears. In here its is possible to click the plus icon beneath slots to add a new slot of any name. You can then go back and connect to your new slot in the Configure Connection dialog, or indeed in the Signal/Slot Editor dockwidget back in the main window. Caveat: I'm using PyQt, and I've only tried to use slots added in this way from Python, not from C++, so your mileage may vary... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10557/"
]
} |
165,650 | I need to add a tooltip/alt to a "td" element inside of my tables with jquery. Can someone help me out? I tried: var tTip ="Hello world";$(this).attr("onmouseover", tip(tTip)); where I have verified that I am using the "td" as "this". **Edit:**I am able to capture the "td" element through using the "alert" command and it worked. So for some reason the "tip" function doesn't work. Anyone know why this would be? | $(this).mouseover(function() { tip(tTip);}); a better way might be to put title attributes in your HTML. That way, if someone has javascript turned off, they'll still get a tool tip (albeit not as pretty/flexible as you can do with jQuery). <table id="myTable"> <tbody> <tr> <td title="Tip 1">Cell 1</td> <td title="Tip 2">Cell 2</td> </tr> </tbody></table> and then use this code: $('#myTable td[title]') .hover(function() { showTooltip($(this)); }, function() { hideTooltip(); });function showTooltip($el) { // insert code here to position your tooltip element (which i'll call $tip) $tip.html($el.attr('title'));}function hideTooltip() { $tip.hide();} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
]
} |
165,719 | Could you please explain what the practical usage is for the internal keyword in C#? I know that the internal modifier limits access to the current assembly, but when and in which circumstance should I use it? | Utility or helper classes/methods that you would like to access from many other classes within the same assembly, but that you want to ensure code in other assemblies can't access. From MSDN (via archive.org): A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework. You can also use the internal modifier along with the InternalsVisibleTo assembly level attribute to create "friend" assemblies that are granted special access to the target assembly internal classes. This can be useful for creation of unit testing assemblies that are then allowed to call internal members of the assembly to be tested. Of course no other assemblies are granted this level of access, so when you release your system, encapsulation is maintained. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/165719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
]
} |
165,720 | I'm looking for an easy way to debug RESTful services. For example, most webapps can be debugged using your average web browser. Unfortunately that same browser won't allow me to test HTTP PUT, DELETE, and to a certain degree even HTTP POST. I am not looking to automate tests. I'd like to run new services through a quick sanity check, ideally without having to writing my own client. | Use an existing 'REST client' tool that makes it easy to inspect the requests and responses, like RESTClient . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/165720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14731/"
]
} |
165,723 | I've noticed RAII has been getting lots of attention on Stackoverflow, but in my circles (mostly C++) RAII is so obvious its like asking what's a class or a destructor. So I'm really curious if that's because I'm surrounded daily, by hard-core C++ programmers, and RAII just isn't that well known in general (including C++), or if all this questioning on Stackoverflow is due to the fact that I'm now in contact with programmers that didn't grow up with C++, and in other languages people just don't use/know about RAII? | For people who are commenting in this thread about RAII (resource acquisition is initialisation), here's a motivational example. class StdioFile { FILE* file_; std::string mode_; static FILE* fcheck(FILE* stream) { if (!stream) throw std::runtime_error("Cannot open file"); return stream; } FILE* fdup() const { int dupfd(dup(fileno(file_))); if (dupfd == -1) throw std::runtime_error("Cannot dup file descriptor"); return fdopen(dupfd, mode_.c_str()); }public: StdioFile(char const* name, char const* mode) : file_(fcheck(fopen(name, mode))), mode_(mode) { } StdioFile(StdioFile const& rhs) : file_(fcheck(rhs.fdup())), mode_(rhs.mode_) { } ~StdioFile() { fclose(file_); } StdioFile& operator=(StdioFile const& rhs) { FILE* dupstr = fcheck(rhs.fdup()); if (fclose(file_) == EOF) { fclose(dupstr); // XXX ignore failed close throw std::runtime_error("Cannot close stream"); } file_ = dupstr; return *this; } int read(std::vector<char>& buffer) { int result(fread(&buffer[0], 1, buffer.size(), file_)); if (ferror(file_)) throw std::runtime_error(strerror(errno)); return result; } int write(std::vector<char> const& buffer) { int result(fwrite(&buffer[0], 1, buffer.size(), file_)); if (ferror(file_)) throw std::runtime_error(strerror(errno)); return result; }};intmain(int argc, char** argv){ StdioFile file(argv[1], "r"); std::vector<char> buffer(1024); while (int hasRead = file.read(buffer)) { // process hasRead bytes, then shift them off the buffer }} Here, when a StdioFile instance is created, the resource (a file stream, in this case) is acquired; when it's destroyed, the resource is released. There is no try or finally block required; if the reading causes an exception, fclose is called automatically, because it's in the destructor. The destructor is guaranteed to be called when the function leaves main , whether normally or by exception. In this case, the file stream is cleaned up. The world is safe once again. :-D | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
]
} |
165,735 | I have a form showing progress messages as a fairly long process runs. It's a call to a web service so I can't really show a percentage complete figure on a progress bar meaningfully. (I don't particularly like the Marquee property of the progress bar) I would like to show an animated GIF to give the process the feel of some activity (e.g. files flying from one computer to another like Windows copy process). How do you do this? | It's not too hard. Drop a picturebox onto your form. Add the .gif file as the image in the picturebox Show the picturebox when you are loading. Things to take into consideration: Disabling the picturebox will prevent the gif from being animated. Another way of doing it: Another way that I have found that works quite well is the async dialog control that I found on the code project | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/165735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
]
} |
165,779 | I've seen a couple questions around here like How to debug RESTful services , which mentions: Unfortunately that same browser won't allow me to test HTTP PUT, DELETE, and to a certain degree even HTTP POST. I've also heard that browsers support only GET and POST, from some other sources like: http://www.packetizer.com/ws/rest.html http://www.mail-archive.com/[email protected]/msg13518.html http://www.xml.com/cs/user/view/cs_msg/1098 However, a few quick tests in Firefox show that sending PUT and DELETE requests works as expected -- the XMLHttpRequest completes successfully, and the request shows up in the server logs with the right method. Is there some aspect to this I'm missing, such as cross-browser compatibility or non-obvious limitations? | No. The HTML 5 spec mentions: The method and formmethod content attributes are enumerated attributes with the following keywords and states: The keyword get , mapping to the state GET, indicating the HTTP GET method. The GET method should only request and retrieve data and should have no other effect. The keyword post , mapping to the state POST, indicating the HTTP POST method. The POST method requests that the server accept the submitted form's data to be processed, which may result in an item being added to a database, the creation of a new web page resource, the updating of the existing page, or all of the mentioned outcomes. The keyword dialog , mapping to the state dialog, indicating that submitting the form is intended to close the dialog box in which the form finds itself, if any, and otherwise not submit. The invalid value default for these attributes is the GET state I.e. HTML forms only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly. However, GET , POST , PUT and DELETE are supported by the implementations of XMLHttpRequest (i.e. AJAX calls) in all the major web browsers (IE, Firefox, Safari, Chrome, Opera). | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/165779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3560/"
]
} |
165,783 | It seems pretty common to want to let your javascript know a particular dom node corresponds to a record in the database. So, how do you do it? One way I've seen that's pretty common is to use a class for the type and an id for the id: <div class="thing" id="5"><script> myThing = select(".thing#5") </script> There's a slight html standards issue with this though -- if you have more than one type of record on the page, you may end up duplicating IDs. But that doesn't do anything bad, does it? An alternative is to use data attributes: <div data-thing-id="5"><script> myThing = select("[data-thing-id=5]") </script> This gets around the duplicate IDs problem, but it does mean you have to deal with attributes instead of IDs, which is sometimes more difficult. What do you guys think? | Note that an ID cannot start with a digit, so: <div class="thing" id="5"> is invalid HTML. See What are valid values for the id attribute in HTML? In your case, I would use ID's like thing5 or thing.5 . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/165783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.