source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
179,512
Given that Chrome and Safari use webkit has anyone yet found anything that renders differently on Chrome than Safari? Is there any reason at the moment to test sites on both, or would testing Safari be sufficient for right now?
Part of this is knowing what is dependent on the rendering engine and what isn't. Javascript, for example, is handled differently in both browsers (google has their own custom javascript renderer), so if your page uses javascript substantially I'd test it in both. This is probably a good place to note that Chrome has been added to BrowserShots so you don't even need to have it installed to test on it and Safari.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14092/" ] }
179,543
for a FILE* stream, if I read as much data as possible, feof(stream) returns me non-zero. Then, If I fclose stream, it feof(stream) will continue to returns me a non-zero value?Is it GUARANTEED?
Calling feof() on a closed file is meaningless (actually worse than meaningless - it's undefined so anything can happen). From the C standard: The value of a pointer to a FILE object is indeterminate after the associated file is closed (including the standard text streams). and A successful call to the fclose function causes the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. Whether or not the call succeeds, the stream is disassociated from the file and any buffer set by the setbuf or setvbuf function is disassociated from the stream (and deallocated if it was automatically allocated).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25888/" ] }
179,556
Like the title says, If I place an app_offline.htm in the application root, will it cut off currently running requests, or just new ones?
Here is my lame experiment; I created an ASPX page with the following code: protected void Page_Load(object sender, EventArgs e){ Response.BufferOutput = false; Response.Write("Step 1<br />"); System.Threading.Thread.Sleep(10000); Response.Write("Step 2<br />"); System.Threading.Thread.Sleep(10000); Response.Write("Step 3<br />");} This code simply introduces some loooong page loads. I accessed the page and while it was loading, I created an "app_offline.htm" file. I then loaded another web browser and confirmed the application was offline. I then re-visited my "loading" request...it completed all the way to step 3. This confirms that current requests finish loading and new requests are turned away.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/179556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16172/" ] }
179,559
According to Wikipedia, on the Comparison of programming languages page, it says that F# uses CLI. Does that mean that F# is designed for the purpose of making command-line applications and not graphical applications, or is there another meaning of CLI?
in .NET it's the Common Language Infrastructure. http://en.wikipedia.org/wiki/Common_Language_Infrastructure
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
179,565
If yes, on which operating system, shell or whatever? Consider the following java program (I'm using java just as an example, any language would be good for this question, which is more about operation systems): public class ExitCode { public static void main(String args[]) { System.exit(Integer.parseInt(args[0])); }} Running it on Linux and bash, it returns always values less equal 255, e.g. ( echo $? prints the exit code of the previous executed command) > java ExitCode 2; echo $?2> java ExitCode 128; echo $?128> java ExitCode 255; echo $?255> java ExitCode 256; echo $?0> java ExitCode 65536; echo $?0 EDITED: the (only, so far) answer below fully explain what happens on UNIXes. I'm still wondering about other OSes.
Using wait() or waitpid() It is not possible on Unix and derivatives using POSIX functions like wait() and waitpid() . The exit status information returned consists of two 8-bit fields, one containing the exit status, and the other containing information about the cause of death (0 implying orderly exit under program control, other values indicating that a signal killed it, and indicating whether a core was dumped). Using sigaction() with SA_SIGINFO If you work hard, and read the POSIX specification of sigaction() and <signal.h> and Signal Actions , you will find that you can get hold of the 32-bit value passed to exit() by a child process. However, it is not completely straight-forward. #include <errno.h>#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/wait.h>#include <time.h>#include <unistd.h>static siginfo_t sig_info = { 0 };static volatile sig_atomic_t sig_num = 0;static void *sig_ctxt = 0;static void catcher(int signum, siginfo_t *info, void *vp){ sig_num = signum; sig_info = *info; sig_ctxt = vp;}static void set_handler(int signum){ struct sigaction sa; sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = catcher; sigemptyset(&sa.sa_mask); if (sigaction(signum, &sa, 0) != 0) { int errnum = errno; fprintf(stderr, "Failed to set signal handler (%d: %s)\n", errnum, strerror(errnum)); exit(1); }}static void prt_interrupt(FILE *fp){ if (sig_num != 0) { fprintf(fp, "Signal %d from PID %d (status 0x%.8X; UID %d)\n", sig_info.si_signo, (int)sig_info.si_pid, sig_info.si_status, (int)sig_info.si_uid); sig_num = 0; }}static void five_kids(void){ const int base = 0xCC00FF40; for (int i = 0; i < 5; i++) { pid_t pid = fork(); if (pid < 0) break; else if (pid == 0) { printf("PID %d - exiting with status %d (0x%.8X)\n", (int)getpid(), base + i, base + i); exit(base + i); } else { int status = 0; pid_t corpse = wait(&status); if (corpse != -1) printf("Child: %d; Corpse: %d; Status = 0x%.4X - waited\n", pid, corpse, (status & 0xFFFF)); struct timespec nap = { .tv_sec = 0, .tv_nsec = 1000000 }; // 1 millisecond nanosleep(&nap, 0); prt_interrupt(stdout); fflush(0); } }}int main(void){ set_handler(SIGCHLD); five_kids();} When run (program sigexit73 compiled from sigexit73.c ), this produces output like: $ sigexit73PID 26599 - exiting with status -872349888 (0xCC00FF40)Signal 20 from PID 26599 (status 0xCC00FF40; UID 501)Child: 26600; Corpse: 26599; Status = 0x4000 - waitedPID 26600 - exiting with status -872349887 (0xCC00FF41)Signal 20 from PID 26600 (status 0xCC00FF41; UID 501)Child: 26601; Corpse: 26600; Status = 0x4100 - waitedPID 26601 - exiting with status -872349886 (0xCC00FF42)Signal 20 from PID 26601 (status 0xCC00FF42; UID 501)Child: 26602; Corpse: 26601; Status = 0x4200 - waitedPID 26602 - exiting with status -872349885 (0xCC00FF43)Signal 20 from PID 26602 (status 0xCC00FF43; UID 501)Child: 26603; Corpse: 26602; Status = 0x4300 - waitedPID 26603 - exiting with status -872349884 (0xCC00FF44)Signal 20 from PID 26603 (status 0xCC00FF44; UID 501)$ With the one millisecond call to nanosleep() removed, the output is apt to look like: $ sigexit73sigexit23PID 26621 - exiting with status -872349888 (0xCC00FF40)Signal 20 from PID 26621 (status 0xCC00FF40; UID 501)Child: 26622; Corpse: 26621; Status = 0x4000 - waitedPID 26622 - exiting with status -872349887 (0xCC00FF41)PID 26623 - exiting with status -872349886 (0xCC00FF42)Signal 20 from PID 26622 (status 0xCC00FF41; UID 501)Child: 26624; Corpse: 26623; Status = 0x4200 - waitedSignal 20 from PID 26623 (status 0xCC00FF42; UID 501)Child: 26625; Corpse: 26622; Status = 0x4100 - waitedPID 26624 - exiting with status -872349885 (0xCC00FF43)PID 26625 - exiting with status -872349884 (0xCC00FF44)$ Note that there are only three lines starting Signal here, and also only three lines ending waited ; some of the signals and exit statuses are lost. This is likely to be because of timing issues between the SIGCHLD signals being set to the parent process. However, the key point is that 4 bytes of data can be transmitted in the exit() status when the code uses sigaction() , SIGCHLD , SA_SIGINFO to track the status. Just for the record, the testing was performed on a MacBook Pro running macOS Mojave 10.14.6, using GCC 9.2.0 and XCode 11.3.1. The code is also available in my SOQ (Stack Overflow Questions) repository on GitHub as file sigexit73.c in the src/so-1843-7779 sub-directory.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/179565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25891/" ] }
179,605
Does anyone know a way to convert from VB6 code to C#? Is there a tool that can do this for me? Is there any migration process that I can follow to do this?
VisualStudio offers (or at least offered) a wizard to do a conversion from VB6 to VB.NET (which could then be converted to C# with a bit of work, possibly helped by #develop's VB.NET <-> C# converter), but when last I used it, for anything non-trivial there was a lot of manual work needing to be done so I suspect you're probably better rewriting or porting by hand if this is a large and/or important application.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25892/" ] }
179,625
In SQL Server 2017, you can use this syntax, but not in earlier versions: SELECT Name = TRIM(Name) FROM dbo.Customer;
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/179625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6522/" ] }
179,668
I tried doing this: root.addEventListener("click", function () { navigateToURL(ClickURLRequest,"_self"); }); And it does add the event listener. I like using closures because they work well in this situation, however, removing the event listener requires a reference to the original function, and since I used an anonymous closure, it does not work, I tried: root.removeEventListener("click", function () { navigateToURL(ClickURLRequest,"_self"); }); as well as: root.removeEventListener("click", function () {} ); The only way I found it would work was to ditch the anonymous closure and point the event listeners at a pre-existing function: function OnClick (e:Event) { navigateToURL(ClickURLRequest,"_self"); } root.addEventListener("click", OnClick); root.removeEventListener("click", OnClick); Does anyone know a way to use anonymous closures for event handlers while still retaining the ability to remove them?
Here's a generic way of removing event listeners that i have used on production projects addEventListener( Event.ACTIVATE, function(event:Event):void { (event.target as EventDispatcher).removeEventListener(event.type, arguments.callee) })
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ] }
179,676
What is the best way to get a file (in this case, a .PDF, but any file will do) from a WebResponse and put it into a MemoryStream? Using .GetResponseStream() from WebResponse gets a Stream object, but if you want to convert that Stream to a specific type of stream, what do you do?
There is a serious issue with SoloBold's answer that I discovered while testing it. When using it to read a file via an FtpWebRequest into a MemoryStream it intermittently failed to read the entire stream into memory. I tracked this down to Peek() sometimes returning -1 after the first 1460 bytes even though a Read() would have succeeded (the file was significantly larger than this). Instead I propose the solution below: MemoryStream memStream;using (Stream response = request.GetResponseStream()) { memStream = new MemoryStream(); byte[] buffer = new byte[1024]; int byteCount; do { byteCount = stream.Read(buffer, 0, buffer.Length); memStream.Write(buffer, 0, byteCount); } while (byteCount > 0);}// If you're going to be reading from the stream afterwords you're going to want to seek back to the beginning.memStream.Seek(0, SeekOrigin.Begin);// Use memStream as required
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
179,690
I've always had a thing for C++/CLI. Maybe because not many developers use it... or just because it's different. Suppose Microsoft fully supported C++/CLI as they do VB.NET and C# (ie. LINQ, WPF, etc.). Would you use it? If not, why?
I do use it. Even with the relative lack of tool support, it still beats raw P/Invoke for dealing with Win32. As for LINQ, i don't really care to see too much more hacked into the C++ language. LINQ is usable enough as-is - if they're gonna enhance the compiler, they should work on C++ 0x support...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2982/" ] }
179,700
Is there a way to take a class name and convert it to a string in C#? As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class. Thus, is there a way that I could do this: class Foo{}tblBar.Include ( Foo.GetType().ToString() ); I don't think I can do GetType() without an instance. Any ideas?
You can't use .GetType() without an instance because GetType is a method. You can get the name from the type though like this: typeof(Foo).Name And as pointed out by Chris, if you need the assembly qualified name you can use typeof(Foo).AssemblyQualifiedName
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/179700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24841/" ] }
179,713
How can you change the href attribute (link target) for a hyperlink using jQuery?
Using $("a").attr("href", "http://www.google.com/") will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags: <a name="MyLinks"></a><a href="http://www.codeproject.com/">The CodeProject</a> ...Then you probably don't want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute: $("a[href]") //... Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href , you might use something like this: $("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/') This will find links where the href exactly matches the string http://www.google.com/ . A more involved task might be matching, then updating only part of the href : $("a[href^='http://stackoverflow.com']") .each(function() { this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, "http://stackoverflow.com"); }); The first part selects only links where the href starts with http://stackoverflow.com . Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/179713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ] }
179,720
On Windows NTFS there is a nice but mostly unused feature called "Alternate Data Streams" (ADS) which I recently used in a hobby-dev project. On Mac HFS+ there is also a similarly nice but mostly unused feature called "named forks". I am thinking of porting this project to Linux, but I do not know if any Filesystem on linux has such a feature?
There are file systems on both Windows and Linux (and other OSes) that support extended attributes (EAs). The Windows support was added for OS/2 compat and does not have any documented interface, except for a hacky method through the backup API (that's what Cygwin does). EAs are designed to store small values only. On Windows, each EA has an ASCII name (whereas almost all other names are Unicode) and the combined size of all EAs on a file can't be larger than 64k. EAs are not files: you can't open a file handle to an EA and read it like a normal file. Alternate data streams are a separate feature provided by NTFS which allows you to provide alternate subfiles inside of a file. Every file has a default unnamed data stream that is automatically opened unless you specify an alternate one. You can open a handle to an ADS and read (even execute) it like a normal file, with a single (Unicode) filename. An ADS can be as large as any disk file. There is no exact analog to ADSes on Linux that I know of, but you may be able to use EAs on the Linux port instead if the data values are small.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23264/" ] }
179,723
By that I mean, what do I need to do to have useful assertions in my code? MFC is quite easy, i just use ASSERT(something). What's the non-MFC way? Edit: Is it possible to stop assert breaking in assert.c rather than than my file which called assert()? Edit: What's the difference between <assert.h> & <cassert> ? Accepted Answer: Loads of great answers in this post, I wish I could accept more than one answer (or someone would combine them all). So answer gets awarded to Ferruccio (for first answer).
#include <cassert>assert(something); and for compile-time checking, Boost's static asserts are pretty useful: #include <boost/static_assert.hpp>BOOST_STATIC_ASSERT(sizeof(int) == 4); // compile fails if ints aren't 32-bit
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/179723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ] }
179,735
I'm messing around with 2D game development using C++ and DirectX in my spare time. I'm finding that the enterprisey problem domain modeling approach doesn't help as much as I'd like ;) I'm more or less looking for a "best practices" equivalent to basic game engine design. How entities should interact with each other, how animations and sounds should be represented in an ideal world, and so on. Anyone have good resources they can recommend?
Gamedev.net is usually where I turn to get an idea of what other people in the game development community are doing. That said, I'm afraid that you'll find that the idea of "best practices" in game development is more volatile than most. Games tend to be such specialized applications that it's near impossible to give any "one size fits all" answers. What works great for Tetris is going to be useless with Asteroids, and a model that works perfectly for Halo is likely to fail miserably for Mario. You'll also find quickly that there's no such thing as an "industry standard" for texture, mesh, level, sound, or animation formats. Everyone just rolls their own or uses whatever is convenient to the platform. You do occasionally see things like COLLADA , which is nice, but it's still just an intermediate format designed to make writing exporters easier. If you're new to game development, my advice would be this: Don't kill yourself over your code structure on your first go. Try a simple game, like asteroids, and just hack away until it works, no matter how "ugly" the code is. Use simple formats that you are familiar with without worrying about how well they'll hold up in larger projects. Don't worry about plugins, skins, editors, or any of that other fluff. Just make it WORK! Then, when you're done with that first, all important game, pick another, and this time around clean up one or two aspects of your code (but don't go overboard!) From there, iterate! I promise you that this will get you farther faster than any amount of poking around online for the "right way" ever could (this coming from someone who's done a LOT of poking). And one last thought for you: If you feel more comfortable working in a more well defined space, take a look at XNA or a similar library. They'll pre-define some of the "best" formats to use and give you tools to work with them, which takes some of the initial guesswork out. Good luck, and above all else remember: Games (and their development) are supposed to be FUN! Don't get too caught up on the small stuff!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473493/" ] }
179,741
I wrote a C# application for a client a couple of years ago, but I no longer have the source code. All I have is the EXE that I deployed on the client's PC. Is there a way I can generate C# source code from the EXE?
Reflector and its add-in FileDisassembler . Reflector will allow to see the source code. FileDisassembler will allow you to convert it into a VS solution.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/179741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ] }
179,743
In my understanding of Servlet, the Servlet will be instantiated by the Container, its init() method will be called once, and the servlet will live like a singleton until the JVM shuts down. I do not expect my servlet to be serialized, since it will be constructed new when the app server recovers or is starts up normally. The servlet should hold no session-specific members, so it does not make sense for it to be written to disk and re-instantiated.Is there a practical use for this? My concerns are, that I put some non-serializable fields within there and then my app will mysteriously fail in a production environment where a different sort of session replication will take place.
Technically, I believe the servlet container is allowed to "passivate" the servlet object to disk, in a similar way that EJB session beans can be. So you're correct to ask the question if your app will fail due to non-serializable fields. In practise, I've never heard of a container doing this, so it's really just legacy baggage from the bad old days of early J2EE. I wouldn't worry about it.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/179743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16542/" ] }
179,764
I've been developing GPL'd software for years, but now I need a more restrictive license. This is for a commercial application, and I want to share my source code with the whole world, regardless of whether they've purchased the application from me or not. I also want to allow people to produce derivative works, but I want to prohibit binary distribution of both my original work, and that of any derivative work. Basically, if someone has already purchased the original work, he/she can compile and use the original source code, or any derivative work. Otherwise, they can only study my source code, or that of a derivative work. Does anyone know a license that fits my needs, or do I need to write my own? Thanks, UPDATE: First of all, thanks everyone for the answers. Let me clear up a few things: This application has not yet been released. So I'm not adopting a new license like XFree86, I'm trying to pick a license for a new application. I usually use the term "free software" instead of open source, so that's why I used the term open source here. The source will be "open" indeed, just not the way the OSI defines it. I'm all for GPL, and almost all software I've written before was released under the GNU GPL v2. But this one has to be an exception. I don't really care if people violate the license. I wouldn't dream of suing anyone for that, unless they're selling my software. Now I'm not suggesting I've written a very special piece of software, but I just don't want people making money by stealing my code. But I also want the tech-savvy users to be able to modify the software anyway they see fit. Oh, and finally, the application is written in a compiled language (Objective-C, to be precise *cough*iPhone*cough*).
that's not OS , it sounds like shared source. Specifically, it's a lot like Ms-RSL. From WikiPedia : Microsoft Reference Source License (Ms-RSL) This is the most restrictive of the Microsoft Shared Source licenses. The source code is made available to view for reference purposes only.[14] Developers may not distribute or modify the code for commercial or non-commercial purposes.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2119/" ] }
179,779
I am writing code for a search results page that needs to highlight search terms. The terms happen to occur within table cells (the app is iterating through GridView Row Cells), and these table cells may have HTML. Currently, my code looks like this (relevant hunks shown below): const string highlightPattern = @"<span class=""Highlight"">$0</span>";DataBoundLiteralControl litCustomerComments = (DataBoundLiteralControl)e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Controls[0];// Turn "term1 term2" into "(term1|term2)"string spaceDelimited = txtTextFilter.Text.Trim();string pipeDelimited = string.Join("|", spaceDelimited.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries));string searchPattern = "(" + pipeDelimited + ")";// Highlight search terms in Customer - Comments columne.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Text = Regex.Replace(litCustomerComments.Text, searchPattern, highlightPattern, RegexOptions.IgnoreCase); Amazingly it works. BUT, sometimes the text I am matching on is HTML that looks like this: <span class="CustomerName">Fred</span> was a classy individual. And if you search for "class" I want the highlight code to wrap the "class" in "classy" but of course not the HTML attribute "class" that happens to be in there! If you search for "Fred", that should be highlighted. So what's a good regex that will make sure matches happen only OUTSIDE the html tags? It doesn't have to be super hardcore. Simply making sure the match is not between < and > would work fine, I think.
This regex should do the job : (?<!<[^>]*)(regex you want to check: Fred|span) It checks that it is impossible to match the regex <[^>]* going backward starting from a matching string. Modified code below: const string notInsideBracketsRegex = @"(?<!<[^>]*)";const string highlightPattern = @"<span class=""Highlight"">$0</span>";DataBoundLiteralControl litCustomerComments = (DataBoundLiteralControl)e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Controls[0];// Turn "term1 term2" into "(term1|term2)"string spaceDelimited = txtTextFilter.Text.Trim();string pipeDelimited = string.Join("|", spaceDelimited.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries));string searchPattern = "(" + pipeDelimited + ")";searchPattern = notInsideBracketsRegex + searchPattern;// Highlight search terms in Customer - Comments columne.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Text = Regex.Replace(litCustomerComments.Text, searchPattern, highlightPattern, RegexOptions.IgnoreCase);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700/" ] }
179,791
In Visual Source Safe 6.0, you could "reset" a working folder by setting it to a blank string. This meant that the working folder would be determined by the working folder of the parent. How do I do this in Visual Source Safe 2005?
This can't be done in the normal VSS 2005 "Set Working Folder" dialog. However, if you hold the shift key while invoking the "Set Working Folder" dialog , it shows the old VSS 6.0 dialog. Here you can reset the working folder by deleting the string and pressing OK.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/179791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ] }
179,849
I work in an Oracle shop. There's a toolset that consists of roughly 1000 Oracle Forms (using the Forms builder from 6i, early 90's software) with Oracle 10g on the back end. It's serving roughly 500 unique people a month, with 200 concurrent connections at any given time during the work day. Obviously this is something that needs to be addressed to get rid of the Forms runtime and move to a web based solution. The tools need to be accessed from Windows, Linux, various UNIX's, VMS and Solaris. What options out there exist that would be feasible to migrate to? Not only does it need to be feasible for migration but the development will need to be done by 8 or so engineers who support the tool set (and many of which who would prefer to stay put and not modernize this tool set). Oracle offers a few solutions that convert Oracle Forms into a crappy Java Applet (it's a very terrible temporary solution). My solution of choice has been migrating to Ruby on Rails (which I'm a big proponent of Rails) but this will involve a learning curve (which we'll hit with any solution) for other developers. Also, the other difficulty in this is converting some very complex forms to HTML forms. Has anyone tackled such a solution? Are there any packages offered by anyone outside of Oracle? Any specific Java Web frameworks? Would GWT, jQuery UI, ExtJS or any other JavaScript UI frameworks offer the rich user experience needed? .NET is a consideration but a last resort (mostly because of license costs, there's no room in the budget in addition to what we're paying for Oracle licenses).
That's exactly what I am currently doing using... Oracle Application Express The learning curve is much smaller than most web-based alternatives for Forms developers, as all the code is in PL/SQL (unless you start getting fancy with Javascript, which you can). Also, in the latest release of Application Express (3.2), there is a tool to convert Forms applications to Apex . It comes free with Oracle versions since 9.2.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23909/" ] }
179,868
It seems that the System.Diagnostics.Debug , and System.Diagnostics.Trace are largely the same, with the notable exception that Debug usage is compiled out in a release configuration. When would you use one and not the other? The only answer to this I've dug up so far is just that you use the Debug class to generate output that you only see in debug configuration, and Trace will remain in a release configuration, but that doesn't really answer the question in my head. If you're going to instrument your code, why would you ever use Debug , since Trace can be turned off without a recompile?
The main difference is the one you indicate: Debug is not included in release, while Trace is. The intended difference, as I understand it, is that development teams might use Debug to emit rich, descriptive messages that might prove too detailed (or revealing) for the consumer(s) of a product, while Trace is intended to emit the kinds of messages that are more specifically geared toward instrumenting an application. To answer your last question, I can't think of a reason to use Debug to instrument a piece of code I intended to release. Hope this helps.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/179868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ] }
179,904
I've been recently asked to learn some MATLAB basics for a class. What does make it so cool for researchers and people that works in university?I saw it's cool to work with matrices and plotting things... (things that can be done easily in Python using some libraries). Writing a function or parsing a file is just painful. I'm still at the start, what am I missing? In the "real" world, what should I think to use it for? When should it can do better than Python? For better I mean: easy way to write something performing. UPDATE 1: One of the things I'd like to know the most is "Am I missing something?" :D UPDATE 2: Thank you for your answers. My question is not about buy or not to buy MATLAB. The university has the possibility to give me a copy of an old version of MATLAB (MATLAB 5 I guess) for free, without breaking the license. I'm interested in its capabilities and if it deserves a deeper study (I won't need anything more than basic MATLAB in oder to pass the exam :P ) it will really be better than Python for a specific kind of task in the real world.
Adam is only partially right. Many, if not most, mathematicians will never touch it. If there is a computer tool used at all, it's going to be something like Mathematica or Maple . Engineering departments, on the other hand, often rely on it and there are definitely useful things for some applied mathematicians. It's also used heavily in industry in some areas. Something you have to realize about MATLAB is that it started off as a wrapper on Fortran libraries for linear algebra. For a long time, it had an attitude that "all the world is an array of doubles (floats)". As a language, it has grown very organically, and there are some flaws that are very much baked in, if you look at it just as a programming language. However, if you look at it as an environment for doing certain types of research in, it has some real strengths. It's about as good as it gets for doing floating point linear algebra. The notation is simple and powerful, the implementation fast and trusted. It is very good at generating plots and other interactive tasks. There are a large number of `toolboxes' with good code for particular tasks, that are affordable. There is a large community of users that share numerical codes (Python + NumPy has nothing in the same league, at least yet) Python, warts and all, is a much better programming language (as are many others). However, it's a decade or so behind in terms of the tools. The key point is that the majority of people who use MATLAB are not programmers really, and don't want to be. It's a lousy choice for a general programming language; it's quirky, slow for many tasks (you need to vectorize things to get efficient codes), and not easy to integrate with the outside world. On the other hand, for the things it is good at, it is very very good. Very few things compare. There's a company with reasonable support and who knows how many man-years put into it. This can matter in industry. Strictly looking at your Python vs. MATLAB comparison, they are mostly different tools for different jobs. In the areas where they do overlap a bit, it's hard to say what the better route to go is (depends a lot on what you're trying to do). But mostly Python isn't all that good at MATLAB's core strengths, and vice versa.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/179904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21384/" ] }
179,927
In visual studio, I have an asp.net 3.5 project that is using MS Enterprise Library 4.0 application blocks. When I have my web config file open, my Error list fills up with 99 messages with things like Could not find schema information for the element 'dataConfiguration'. Could not find schema information for the attribute 'defaultDatabase'. Could not find schema information for the element 'loggingConfiguration'. Could not find schema information for the attribute 'tracingEnabled'. Could not find schema information for the attribute 'defaultCategory'. If I close the Web.config file they go away (but they come back as soon as I need to open the file again). After doing some looking, I found that this is becauase there is an XSD or schema file missing that Visual Studio needs in order to properly 'understand' the schema that is in the web.config file and provide intellisense for it. Does anyone know how to either supply VS with the appropriate schema information, or to turn off these messages? @Franci - Thanks for the info, I have tried that tool as well as the MMC snap in (they tend to blow up the formatting in the Web.config) but they still do not resolve the irritating warnings I receive. Thanks for trying.
I've created a new scheme based on my current app.config to get the messages to disappear.I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me. Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16391/" ] }
179,934
This is my first time attempting to call an ASP.NET page method from jQuery. I am getting a status 500 error with the responseText message that the web method cannot be found. Here is my jQuery $.ajax call: function callCancelPlan(activePlanId, ntLogin) { var paramList = '{"activePlanId":"' + activePlanId + '","ntLogin":"' + ntLogin + '"}'; $.ajax({ type: "POST", url: "ArpWorkItem.aspx/CancelPlan", data: paramList, contentType: "application/json; charset=utf-8", dataType: "json", success: function() { alert("success"); }, error: function(xml,textStatus,errorThrown) { alert(xml.status + "||" + xml.responseText); } });} And here is the page method I am trying to call: [WebMethod()]private static void CancelPlan(int activePlanId, string ntLogin){ StrategyRetrievalPresenter presenter = new StrategyRetrievalPresenter(); presenter.CancelExistingPlan(offer, ntLogin); } I have tried this by decorating the Web Method with and without the parens'()'. Anyone have an idea?
Your web method needs to be public and static.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/179934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ] }
179,938
i'm want to have a repeater generate a bunch of checkboxes, e.g.: <tr><td><input type="checkbox" name="t" value="11cbf4deb87" /> <input type="checkbox" name="a" value="33cbf4deb87" />stackoverflow.com</td></tr><tr><td><input type="checkbox" name="t" value="11cbf4deb88" /> <input type="checkbox" name="a" value="33cbf4deb87" />microsoft.com</td></tr><tr><td><input type="checkbox" name="t" value="11cd3f33a89" /> <input type="checkbox" name="a" value="33cbf4deb87" />gmail.com</td></tr><tr><td><input type="checkbox" name="t" value="1138fecd337" /> <input type="checkbox" name="a" value="33cbf4deb87" />youporn.com</td></tr><tr><td><input type="checkbox" name="t" value="11009efdacc" /> <input type="checkbox" name="a" value="33bf4deb87" />fantasti.cc</td></tr> Question 1: How do i individually reference each checkbox when the repeater is running so i can set the unique value? Do i data-bind it with something like: <itemtemplate> <tr> <td> <input type="checkbox" name="t" value="<%# ((Item)Container.DataItem).TangoUniquifier %>" /> <input type="checkbox" name="a" value="<%# ((Item)Container.DataItem).AlphaUniquifier %>" /> <%# ((Item)Container.DataItem).SiteName %> </td> </tr></itemtemplate> Or am i supposed to set it somehow in the OnItemDataBound? <asp:repeater id="ItemsRepeater" OnItemDataBound="ItemsRepeater_OnItemDataBound" runat="server"> ... <itemtemplate> <tr> <td> <input id="chkTango" type="checkbox" name="t" runat="server" /> <input id="chkAlpha" type="checkbox" name="a" runat="server" /> <%# ((Item)Container.DataItem).SiteName %> </td> </tr> </itemtemplate> ...</asp:repeater>protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e){ // if the data bound item is an item or alternating item (not the header etc) if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // get the associated item Item item = (Item)e.Item.DataItem; //??? this.chkTango.Value = item.TangoUniquifier; this.chkAlpha.Value = item.AlphaUniquifier; }} But if i'm supposed to reference it in the code-behind, how do i reference it in the code-behind? Am i supposed to reference it using the (server-side) id property of an <INPUT> control? i realize that the ID of a control on the server-side is not the same as the ID that will be present on the client. Or do i have to do something where i have to find an INPUT control with a name of "t" and another with a name of "a"? And what kind of control is a CheckBox that allows me to set it's input value? protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e){ // if the data bound item is an item or alternating item (not the header etc) if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // get the associated item Item item = (Item)e.Item.DataItem; CheckBox chkTango = (CheckBox)e.Item.FindControl("chkTango"); chkTango.Value = item.TangoUniquifier; CheckBox chkAlpha = (CheckBox)e.Item.FindControl("chkAlpha"); chkAlpha.Value = item.AlphaUniquifier; }} Question 2:When the user later clicks SUBMIT, how do i find all the checked checkboxes, or more specifically their VALUES? Do i have to FindControl? protected void DoStuffWithLinks_Click(object sender, EventArgs e){ // loop through the repeater items foreach (RepeaterItem repeaterItem in actionItemRepeater.Items) { Item item = repeaterItem.DataItem as Item; // grab the checkboxes CheckBox chkAlpha = (CheckBox)repeaterItem.FindControl("chkAlpha"); CheckBox chkTango = (CheckBox)repeaterItem.FindControl("chkTango"); if (chkAlpha.Checked) { item.DoAlphaStuff(chkAlpha.Name); } if (chkTango.Checked) { item.DoTangoStuff(chkTango.Name); } }} Is the repeater items DataItem still there on a click event handler?
Use the server control instead of making an input control runat=server <asp:CheckBox id="whatever" runat="Server" /> When you set the value in your ItemDataBound, you use FindControl CheckBox checkBox = (CheckBox)e.Item.FindControl("whatever");checkBox.Checked = true; When you get the items, you also use FindControl from the item in a foreach construct. Also, depending on how you databound it, the DataItem may no longer be there after a postback. foreach (RepeaterItem item in myRepeater.Items){ if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { CheckBox checkBox = (CheckBox)item.FindControl("whatever"); if (checkBox.Checked) { /* do something */ } }} Many people are tempted to 'safe cast' using the as operator with FindControl() . I don't like that because when you change the control name on the form, you can silently ignore a development error and make it harder to track down. I try to only use the as operator if the control isn't guaranteed to be there. Update for: Which CheckBox is which? In the rendered html you'll end up having all these checkbox name like ctl00_cph0_ParentContainer_MyRepeater_ctl01_MyCheckboxctl00_cph0_ParentContainer_MyRepeater_ctl02_MyCheckboxctl00_cph0_ParentContainer_MyRepeater_ctl03_MyCheckbox You don't care what the names are because the foreach item.FindControl() gets them for you, and you shouldn't assume anything about them. However, when you iterate via foreach, you usually need a way to reference that back to something. Most of the time this is done by also having an asp:HiddenField control alongside each CheckBox to hold an identifier to match it back up to the correct entity. Security note : there is a security issue with using hidden fields because a hidden field can be altered in javascript; always be conscious that this value could have been modified by the user before the form was submitted.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ] }
179,940
We are developing a C# application for a web-service client. This will run on Windows XP PC's. One of the fields returned by the web service is a DateTime field. The server returns a field in GMT format i.e. with a "Z" at the end. However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out. The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving. CultureInfo ci = new CultureInfo("en-NZ");string date = "Web service date".ToString("R", ci);DateTime convertedDate = DateTime.Parse(date); As per this date site : UTC/GMT Offset Standard time zone: UTC/GMT +12 hours Daylight saving time: +1 hour Current time zone offset: UTC/GMT +13 hours How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?
For strings such as 2012-09-19 01:27:30.000 , DateTime.Parse cannot tell what time zone the date and time are from. DateTime has a Kind property, which can have one of three time zone options: Unspecified Local Utc NOTE If you are wishing to represent a date/time other than UTC or your local time zone, then you should use DateTimeOffset . So for the code in your question: DateTime convertedDate = DateTime.Parse(dateStr);var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified You say you know what kind it is, so tell it. DateTime convertedDate = DateTime.SpecifyKind( DateTime.Parse(dateStr), DateTimeKind.Utc);var kind = convertedDate.Kind; // will equal DateTimeKind.Utc Now, once the system knows its in UTC time, you can just call ToLocalTime : DateTime dt = convertedDate.ToLocalTime(); This will give you the result you require.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/179940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9922/" ] }
179,955
Many Java Apps don't use anti-aliased fonts by default, despite the capability of Swing to provide them. How can you coerce an arbitrary java application to use AA fonts? (both for applications I'm running, and applications I'm developing)
If you have access to the source, you can do this in the main method: // enable anti-aliased text: System.setProperty("awt.useSystemAAFontSettings","on"); or, (and if you do not have access to the source, or if this is easier) you can simply pass the system properties above into the jvm by adding these options to the command line: -Dawt.useSystemAAFontSettings=on
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/179955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ] }
179,987
I am in a situation where I must update an existing database structure from varchar to nvarchar using a script. Since this script is run everytime a configuration application is run, I would rather determine if a column has already been changed to nvarchar and not perform an alter on the table. The databases which I must support are SQL Server 2000, 2005 and 2008.
You can run the following script which will give you a set of ALTER commands: SELECT 'ALTER TABLE ' + isnull(schema_name(syo.id), 'dbo') + '.' + syo.name + ' ALTER COLUMN ' + syc.name + ' NVARCHAR(' + case syc.length when -1 then 'MAX' ELSE convert(nvarchar(10),syc.length) end + ');' FROM sysobjects syo JOIN syscolumns syc ON syc.id = syo.id JOIN systypes syt ON syt.xtype = syc.xtype WHERE syt.name = 'varchar' and syo.xtype='U' There are, however, a couple of quick caveats for you. This will only do tables. You'll want to scan all of your sprocs and functions to make sure they are changed to NVARCHAR as well. If you have a VARCHAR > 4000 you will need to modify it to be NVARCHAR(MAX) But those should be easily doable with this template. If you want this to run automagically you can set it in a WHILE clause.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/179987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441/" ] }
180,030
In windows XP "FileInfo.LastWriteTime" will return the date a picture is taken - regardless of how many times the file is moved around in the filesystem. In Vista it instead returns the date that the picture is copied from the camera. How can I find out when a picture is taken in Vista? In windows explorer this field is referred to as "Date Taken".
Here's as fast and clean as you can get it. By using FileStream, you can tell GDI+ not to load the whole image for verification. It runs over 10 × as fast on my machine. //we init this once so that if the function is repeatedly called//it isn't stressing the garbage manprivate static Regex r = new Regex(":");//retrieves the datetime WITHOUT loading the whole imagepublic static DateTime GetDateTakenFromImage(string path){ using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (Image myImage = Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(36867); string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); return DateTime.Parse(dateTaken); }} And yes, the correct id is 36867, not 306. The other Open Source projects below should take note of this. It is a huge performance hit when processing thousands of files.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25930/" ] }
180,032
Right now, I have a SQL Query like this one: SELECT X, Y FROM POINTS It returns results like so: X Y----------12 315 218 1220 29 I'd like to return results all in one row, like this (suitable for using in an HTML <AREA> tag): XYLIST----------12,3,15,2,18,12,20,29 Is there a way to do this using just SQL?
Thanks for the quick and helpful answers guys! I just found another fast way to do this too: SELECT STUFF(( SELECT ',' + X + ',' + Y FROM Points FOR XML PATH('') ), 1, 1, '') AS XYList Credit goes to this guy: Link
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/180032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8409/" ] }
180,052
Is it possible to check out subdirectories of a repository in Git? Imagine I am setting up a new WordPress installation. I will create two new directories for my plugin and theme customization: wordpress/wp-content/plugins/myplugins/ wordpress/wp-content/themes/mytheme/ I want to maintain these directories via Git. In Subversion, I would accomplish this by having trunk/myplugins/ and trunk/mytheme/ directories and checking out subdirectories. Does Git have a way to accomplish the same task using a single repository? I could just be missing the boat on some Git paradigm, as a long time SVN user with little exposure to Git. Edit: Multiple branches storing different content is an interesting way to handle this.
Sparse checkouts are now in Git 1.7 . Also see the question “ Is it possible to do a sparse checkout without checking out the whole repository first? ”. Note that sparse checkouts still require you to download the whole repository, even though some of the files Git downloads won't end up in your working tree.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7675/" ] }
180,075
If I create a Stored Procedure in SQL and call it ( EXEC spStoredProcedure ) within the BEGIN/END TRANSACTION, does this other stored procedure also fall into the transaction? I didn't know if it worked like try/catches in C#.
Yes, everything that you do between the Begin Transaction and Commit (or Rollback) is part of the transaction.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/180075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21828/" ] }
180,095
I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present. What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program. PS: This question/answer deals with the problem in a generic way; how specifically should I solve it?
Read up on the try: statement. try: # do somethingexcept socket.error, e: # A socket errorexcept IOError, e: if e.errno == errno.EPIPE: # EPIPE error else: # Other error
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24208/" ] }
180,097
I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc. The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types: doSomething int doubledoSomethingElse java.lang.String boolean If the input was something like java.lang.String , I know I could use Class.forName("java.lang.String") to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back? Edit: Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the ClassUtils class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.
The Class instances for the primitive types are obtainable as you said using e.g. int.class , but it is also possible to get the same values using something like Integer.TYPE . Each primitive wrapper class contains a static field, TYPE , which has the corresponding primitive class instance. You cannot obtain the primitive class via forName , but you can get it from a class which is readily available. If you absolutely must use reflection, you can try something like this: Class clazz = Class.forName("java.lang.Integer");Class intClass = clazz.getField("TYPE").get(null);intClass.equals(int.class); // => true
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3005/" ] }
180,103
I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document? <script type="text/javascript">$(document).ready(function() { // ???});</script>
The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag. <script type="text/javascript"> $(document).ready(function() { document.title = 'blah'; });</script>
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/180103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ] }
180,158
How do I get a method's execution time? Is there a Timer utility class for things like timing how long a task takes, etc? Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.
There is always the old-fashioned way: long startTime = System.nanoTime();methodToTime();long endTime = System.nanoTime();long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/180158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13140/" ] }
180,172
Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++? MyObject object; // ok - default ctorMyObject object(blah); // okMyObject object(); // error I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?
Most vexing parse This is related to what is known as "C++'s most vexing parse". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration. Another instance of the same problem: std::ifstream ifs("file.txt");std::vector<T> v(std::istream_iterator<T>(ifs), std::istream_iterator<T>()); v is interpreted as a declaration of function with 2 parameters. The workaround is to add another pair of parentheses: std::vector<T> v((std::istream_iterator<T>(ifs)), std::istream_iterator<T>()); Or, if you have C++11 and list-initialization (also known as uniform initialization) available: std::vector<T> v{std::istream_iterator<T>{ifs}, std::istream_iterator<T>{}}; With this, there is no way it could be interpreted as a function declaration.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/180172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10897/" ] }
180,211
To make click-able divs, I do: <div class="clickable" url="http://google.com"> blah blah</div> and then $("div.clickable").click(function(){ window.location = $(this).attr("url");}); I don't know if this is the best way, but it works perfectly with me, except for one issue:If the div contains a click-able element, such as <a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function AND follows the link in the 'url' attribute of the div. Anyway around this?
If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click). $("div.clickable").click(function(){ window.location = $(this).attr("url"); return false;}); See event.preventDefault() vs. return false for details on return false vs. preventDefault.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721/" ] }
180,272
Is it even possible? Basically, there's a remote repository from which I pull using just: git pull Now, I'd like to preview what this pull would change (a diff) without touching anything on my side. The reason is that thing I'm pulling might not be "good" and I want someone else to fix it before making my repository "dirty".
After doing a git fetch , do a git log HEAD..origin/master to show the log entries between your last common commit and the origin's master branch. To show the diffs, use either git log -p HEAD..origin/master to show each patch, or git diff HEAD...origin/master (three dots not two) to show a single diff. There normally isn't any need to undo a fetch, because doing a fetch only updates the remote branches and none of your branches. If you're not prepared to do a pull and merge in all the remote commits, you can use git cherry-pick to accept only the specific remote commits you want. Later, when you're ready to get everything, a git pull will merge in the rest of the commits. Update: I'm not entirely sure why you want to avoid the use of git fetch. All git fetch does is update your local copy of the remote branches. This local copy doesn't have anything to do with any of your branches, and it doesn't have anything to do with uncommitted local changes. I have heard of people who run git fetch in a cron job because it's so safe. (I wouldn't normally recommend doing that, though.)
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/180272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ] }
180,290
I have a memory of talking to people who have got so far in using Ruby on Rails and then had to abandon it when they have hit limits, or found it was ultimately too rigid. I forget the details but it may have had to do with using more than one database. So what I'd like is to know is what features/requirements fall outside of Ruby on Rails, or at least requires such contortions that it is better to use another more flexible framework, even though you may have to lose some elegance or write extra boilerplate code.
Rails (not ruby itself) is proud to be "Opinionated Software". What this means in practice is that the authors of rails have a certain target audience in mind (themselves basically) and aim rails specifically at that. If X feature isn't needed for that target audience, it doesn't get added. Off the top of my head, things that rails explicitly doesn't support that people may care about: Foreign keys in databases Connections to multiple DB's at once SOAP web services (since rails 2.0) Connections to multiple database servers at once That said, it is very easy to extend rails with plugins, and there are plugins which add all of the above functionality to rails, and a lot more, so I wouldn't really count these as limits. The only other caveat is that rails is built around the idea of creating CRUD web applications using MVC. If you're trying to do something which is NOT a CRUD web app (like twitter, which is actually a messaging system, or if you are insane and want to use a model like ASP.NET webforms) then you will also encounter problems. In this case you're better off not using rails, as you're essentially trying to build a boat out of bicycle parts. In all likelihood, the problems you will run into that can't just be fixed with a quick plugin or a day or 2 of coding are all inherent problems with the underlying C Ruby runtime (memory leaks, green threads, crap performance, etc).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3189/" ] }
180,320
I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done. Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to. This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage. So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like Inscrutable compiler errors inplaces where you don't expect them? Code bloat? Difficulty in tracing code? Setting Debugger Breakpoints?
Macros are a text substitution mechanism. Templates are a functional turing-complete language that is executed at compile time and is integrated into the C++ type system. You can think of them as a plugin mechanism for the language.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ] }
180,330
I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later. Can anybody tell me how to obtain the file path from the save dialog box to use it later?
Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later. SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments); saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ; saveFileDialog1.FilterIndex = 1; if(saveFileDialog1.ShowDialog() == DialogResult.OK) { Console.WriteLine(saveFileDialog1.FileName);//Do what you want here}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/180330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14441/" ] }
180,349
In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know which database to connect to. How do I dynamically and programatically connect ActiveRecord to the right db?
You can also do this easily without hardcoding anything and run migrations automatically: customer = CustomerModel.find(id)spec = CustomerModel.configurations[RAILS_ENV]new_spec = spec.clonenew_spec["database"] = customer.database_nameActiveRecord::Base.establish_connection(new_spec)ActiveRecord::Migrator.migrate("db/migrate_data/", nil) I find it useful to re-establish the old connection on a particular model afterwards: CustomerModel.establish_connection(spec)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470/" ] }
180,358
I'm a pretty experienced Java programmer that's been doing quite a bit of Win32 stuff in the last couple of years. Mainly I've been using VB6, but I really need to move to something better. I've spent a month or so playing with Delphi 2009. I like the VCL GUI stuff, Delphi seems more suited to Windows API calls than VB6, I really like the fact that it's much better at OO than VB6, and I like the unit-testing framework that comes with the IDE. But I really struggle with the fact that there's no widely-used garbage collector for Delphi - having to free every object manually or use interfaces for everything seems to have a pretty big impact on the way that you can do things effectively in an object oriented way. Also I'm not particularly keen on the syntax, or the fact that you have to declare variables all at the top of a method. I can handle Delphi, but I'm wondering if C++ Builder 2009 might be a better choice for me. I know very little about C++ Builder and C++, but then I know very little about Delphi either. I know there's a lot to the C++ language, but I suspect it's only necessary to know a subset of it to get things done productively... I have heard that the C++ of today is a lot more productive to program in than the C++ of 10 years ago. I'll be doing new development only so I wouldn't need to master every aspect of the C++ language - if I can find an equivalent for each of Java's language features I'll be happy enough, and as I progress I could start looking at the more advanced stuff a bit more. (Sorry if that sounds painfully naive - if so please set me straight!) So, for a Java programmer that's new to both Delphi and C++ Builder, which would you consider to be a better choice for productive development of Win32 exes and dlls, and why? What do you see to be the pros and cons of each?
Delphi or C++ Builder - it's a difficult choice! As you're aware, they're basically very similar, from the IDE and RAD point of view. The pros and cons of each - irrespective of background - are a bit like this. Both share a great 2-way RAD form designer and framework (VCL) that are ideal for native Windows development. Delphi: FOR: Large, active, enthusiastic community FOR: Delphi 2009 is the best version for many years FOR: Delphi "units" make C source/header file pairs seem archaic AGAINST: No automatic destruction as objects leave scope, hence lots of 'finally's in your code AGAINST: Language can be 'wordy', which is a matter of taste AGAINST: Using third-party DLL's or libraries in other languages (esp. C) requires Delphi header files to be written C++Builder FOR: C++Builder 2009 is probably the best version ever FOR: RAII idiom simplifies memory management hugely FOR: Templates are incredibly useful and powerful, even if the C++Builder implementation has some bugs with them. FOR: Support for BOOST and other modern template-based libraries (even though the Boost support is not 100%) FOR: Great interop with Delphi means most Delphi components can easily be used. FOR: Easy to use with third-part DLLs/libraries with C/C++ headers. FOR: C++ may look better on a CV than Delphi. AGAINST: CB2009 is "unicode only" - the implications of this for code portability are different and less well thought-out than for Delphi AGAINST: C++Builder user-base is much smaller than Delphi. Maybe 20% or less. AGAINST: Borland/Inprise nearly killed BCB a few years ago, and it was only resurrected after major efforts from the community. (However, Codegear/Embarcadero commitment does seem impressive) AGAINST: C++Builder is not top of the pile within Codegear. AGAINST: Third-party component vendors don't always understand/support C++Builder That's about it. Just to state my position, I'm a happy BCB2007/2009 user (since BCB5), and I also infrequently use Delphi. A few years back, I considered a switch from C++ to Delphi, but the lack of RAII idiom was the one thing that I found difficult to come to terms with.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961/" ] }
180,398
I'd like to have it yell hooray whenever an assert statement succeeds, or at the very least have it display the number of successful assert statements that were encountered. I'm using JUnit4. Any suggestions?
If you want to see some output for each successful assertion, another simple approach which requires no external dependencies or source code, would be to define your own Assert class which delegates all methods to the standard JUnit Assert class, as well as logging successful assertions (failed assertions will be reported as usual by the JUnit class). You then run a global search-and-replace on your test classes from "org.junit.Assert" => "com.myco.test.Assert", which should fix-up all regular and static import statements. You could also then easily migrate your approach to the quieter-is-better-camp and change the wrapper class to just report the total # of passed assertions per test or per class, etc.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ] }
180,401
I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition. How about these examples: int* test; int *test; int * test; int* test,test2; int *test,test2; int * test,test2; Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one. The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?
4, 5, and 6 are the same thing, only test is a pointer. If you want two pointers, you should use: int *test, *test2; Or, even better (to make everything clear): int* test;int* test2;
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
180,405
I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16. var users = from u in dc.Users where ((u.UserRolesBitmask & 1) == 1) || ((u.UserRolesBitmask & 4) == 4) || ((u.UserRolesBitmask & 16) == 16) select u; I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it: private List<User> GetUsersFromRoles(uint[] UserRoles) {} Any pointers on how to dynamically build my query? Thanks
You can use the PredicateBuilder class. PredicateBuilder has been released in the LINQKit NuGet package LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ] }
180,413
Classes that use other classes (as members, or as arguments to methods) need instances that behave properly for unit test. If you have these classes available and they introduce no additional dependencies, isn't it better to use the real thing instead of a mock?
I say use real classes whenever you can. I'm a big believer in expanding the boundaries of "unit" tests as much as possible. At this point they aren't really unit tests in the traditional sense, but rather just an automated regression suite for your application. I still practice TDD and write all my tests first, but my tests are a little bigger than most people's and my green-red-green cycles take a little longer. But now that I've been doing this for a little while I'm completely convinced that unit tests in the traditional sense aren't all they're cracked up to be. In my experience writing a bunch of tiny unit tests ends up being an impediment to refactoring in the future. If I have a class A that uses B and I unit test it by mocking out B, when I decide to move some functionality from A to B or vice versa all of my tests and mocks have to change. Now if I have tests that verify that the end to end flow through the system works as expected then my tests actually help me to identify places where my refactorings might have caused a change in the external behavior of the system. The bottom line is that mocks codify the contract of a particular class and often end up actually specifying some of the implementation details too. If you use mocks extensively throughout your test suite your code base ends up with a lot of extra inertia that will resist any future refactoring efforts.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ] }
180,451
Using answers to this question , I have been able to populate a select box based on the selection of another select box. ( I posted my answer here ) Pulling the data from an array structure built server-side, stored in a .js file and referenced in the html page. Now I would like to add a third select box. If I had 3 sets of data (model, make, options) something like this (pseudo code): cars : [Honda[Accord[Lx, Dx]], [Civic[2dr, Hatchback]], [Toyota[Camry[Blk, Red]], [Prius[2dr,4dr]] Ex: If Honda were selected, the next select box would have [Accord Civic] and if Accord were selected the next select box would have [Lx Dx] How can I 1) create an array structure to hold the data? such that 2) I can use the value from one select box to reference the needed values for the next select box Thanks EDIT I can create the following, but can't figure out the references in a way that would help populate a select box var cars = [ {"makes" : "Honda", "models" : [ {'Accord' : ["2dr","4dr"]} , {'CRV' : ["2dr","Hatchback"]} , {'Pilot': ["base","superDuper"] } ] }, {"makes" :"Toyota", "models" : [ {'Prius' : ["green","reallyGreen"]} , {'Camry' : ["sporty","square"]} , {'Corolla' : ["cheap","superFly"] } ] } ] ; alert(cars[0].models[0].Accord[0]); ---> 2dr
I prefer data structure like this: var carMakers = [ { name: 'Honda', models: [ { name: 'Accord', features: ['2dr', '4dr'] }, { name: 'CRV', features: ['2dr', 'Hatchback'] }, { name: 'Pilot', features: ['base', 'superDuper'] } ]}, { name: 'Toyota', models: [ { name: 'Prius', features: ['green', 'superGreen'] }, { name: 'Camry', features: ['sporty', 'square'] }, { name: 'Corolla', features: ['cheap', 'superFly'] } ]}]; Given the three select lists with id's: 'maker', 'model' and 'features' you can manipulate them with this (I believe this is pretty self explanatory): // returns array of elements whose 'prop' property is 'value'function filterByProperty(arr, prop, value) { return $.grep(arr, function (item) { return item[prop] == value });}// populates select list from array of items given as objects: { name: 'text', value: 'value' }function populateSelect(el, items) { el.options.length = 0; if (items.length > 0) el.options[0] = new Option('please select', ''); $.each(items, function () { el.options[el.options.length] = new Option(this.name, this.value); });}// initialization$(document).ready(function () { // populating 1st select list populateSelect($('#maker').get(0), $.map(carMakers, function(maker) { return { name: maker.name, value: maker.name} })); // populating 2nd select list $('#maker').bind('change', function() { var makerName = this.value, carMaker = filterByProperty(carMakers, 'name', makerName), models = []; if (carMaker.length > 0) models = $.map(carMaker[0].models, function(model) { return { name: model.name, value: makerName + '.' + model.name} }); populateSelect($('#model').get(0), models); $('#model').trigger('change'); }); // populating 3rd select list $('#model').bind('change', function () { var nameAndModel = this.value.split('.'), features = []; if (2 == nameAndModel.length) { var makerName = nameAndModel[0], carModel = nameAndModel[1], carMaker = filterByProperty(carMakers, 'name', makerName); if (carMaker.length > 0) { var model = filterByProperty(carMaker[0].models, 'name', carModel) if (model.length > 0) features = $.map(model[0].features, function(feature) { return { name: feature, value: makerName + '.' + carModel + '.' + feature} }) } } populateSelect($('#feature').get(0), features); }) // alerting value on 3rd select list change $('#feature').bind('change', function () { if (this.value.length > 0) alert(this.value); })});
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/180451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ] }
180,516
I have roughly the following code. Could this be made nicer or more efficient? Perhaps using std::remove_if ? Can you remove items from the map while traversing it? Can we avoid using the temporary map? typedef std::map<Action, What> Actions;static Actions _actions;bool expired(const Actions::value_type &action){ return <something>;}void bar(const Actions::value_type &action){ // do some stuff}void foo(){ // loop the actions finding expired items Actions actions; BOOST_FOREACH(Actions::value_type &action, _actions) { if (expired(action)) bar(action); else actions[action.first]=action.second; } } actions.swap(_actions);}
You could use erase(), but I don't know how BOOST_FOREACH will handle the invalidated iterator. The documentation for map::erase states that only the erased iterator will be invalidated, the others should be OK. Here's how I would restructure the inner loop: Actions::iterator it = _actions.begin();while (it != _actions.end()){ if (expired(*it)) { bar(*it); Actions::iterator toerase = it; ++it; _actions.erase(toerase); } else ++it;}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ] }
180,537
Is using SQL Express in a production environment a reasonable choice? I looked at Microsoft's comparison chart: https://www.microsoft.com/en-us/sql-server/sql-server-2019-comparison I would be using SQL Express with a small to mid-sized web site. I don't believe I would exceed the 4GB database size limit. Is SQL Express typically supported in shared hosting environments? Is there something I'm missing that would make SQL Express an unreasonable choice?
I know many people using SQL Express for production and it works well, the biggest limiting factor is the absence of SQL Agent for automated backups. To automate backups you have to either take a VM image (if on a VPS) or use windows scheduler or some other technology. The only other major limiting factor is the ram limitation, but for a small site I have not really noticed that being too much of an actual issue.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12689/" ] }
180,549
Being an aspiring Apple developer, I want to get the opinions of the community if it is better to learn C first before moving into Objective-C and ultimately the Cocoa Framework? My gut says learn C, which will give me a good foundation.
I would learn C first. I learned C (and did a lot in C) before moving to Obj-C. I have many colleagues who never were real C programmers, they started with Obj-C and learned only as much C as necessary. Every now and then I see how they solve a problem entirely in Obj-C, sometimes resulting in a very clumsy solutions. Usually I then replace some Obj-C code with pure C code (after all you can mix them as much as you like, the content of an Obj-C method can be entirely, pure C code). Without any intention to insult any Obj-C programmer, there are solutions that are very elegant in Obj-C, these are solutions that just work (and look) a lot better thanks to objects (OOP programming can make complex programs much more lovely than functional programming; polymorphism for example is a brilliant feature)... and I really like Obj-C (much more than C++! I hate the C++ syntax and some language features are plain overkill and lead to bad development patterns IMHO); however, when I sometimes re-write Obj-C code of my colleagues (and I really only do so, if I think this is absolutely necessary), the resulting code is usually 50% smaller, needs only 25% of the memory it used before and is about 400% faster at runtime. What I'm trying to say here: Every language has its pros and cons. C has pros and cons and so does Obj-C. However, the really great feature of Obj-C (that's why I even like it more than Java) is that you can jump to plain C at will and back again. Why this is such a great feature? Because just like Obj-C fixes many of the cons of pure C, pure C can fix some of the cons of Obj-C. If you mix them together you'll receive a very powerful team. If you only learn Obj-C and have no idea of C or only know the very basics of it and never tried how elegantly it can solve some common problems, you actually learned only half of Obj-C. C is a fundamental part of Obj-C. The ability to use C at any time and everywhere is a fundamental feature of it. A typical example was some code we used that had to encode data in base64, but we could not use an external library for that (no OpenSSL lib). We used a base64 encoder, entirely written using Cocoa classes. It was working okay, but when we made it encode 200 MB of binary data, it took an eternity and the memory overhead was unacceptable. I replaced it with a tiny, ultra compact base64 encoder written entirely as one C function (I copied the function body into the method body, method took NSData as input and returned NSString as output, however inside the function everything was C). The C encoder was so much more compact, it beat the pure Cocoa encoder by the factor 8 in speed and the memory overhead was also much less. Encoding/Decoding data, playing around with bits and similar low level tasks are just the strong points of C. Another example was some UI code that drew a lot of graphs. For storing the data necessary to paint the graphs, we used NSArray's. Actually NSMutableArray's, since the graph was animated. Result: Very slow graph animation. We replaced all NSArray's with normal C arrays, objects with structs (after all graph coordinate information is nothing you must have in objects), enumerator access with simple for loops and started moving data between the arrays with memcopy instead of taking data from one array to the other one, index for index. The result: A speed up by the factor 4. The graph animated smoothly, even on older PPC systems. The weakness of C is that every more complex program gets ugly in the long run. Keeping C applications readable, extensible and manageable demands a lot of discipline of a programmer. Many projects fail because this discipline is missing. Obj-C makes it easy for you to structure your application using classes, inheritance, protocols and so on. That said, I would not use pure C functionality across the borders of a method unless necessary. I prefer to keep all code in an Objective-C app within the method of an object; everything else defeats the purpose of an OO application. However within the method I sometimes use pure C exclusively.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8804/" ] }
180,601
My style of coding includes the following idiom: class Derived : public Base{ public : typedef Base super; // note that it could be hidden in // protected/private section, instead // Etc.} ; This enables me to use "super" as an alias to Base, for example, in constructors: Derived(int i, int j) : super(i), J(j){} Or even when calling the method from the base class inside its overridden version: void Derived::foo(){ super::foo() ; // ... And then, do something else} It can even be chained (I have still to find the use for that, though): class DerivedDerived : public Derived{ public : typedef Derived super; // note that it could be hidden in // protected/private section, instead // Etc.} ;void DerivedDerived::bar(){ super::bar() ; // will call Derived::bar super::super::bar ; // will call Base::bar // ... And then, do something else} Anyway, I find the use of "typedef super" very useful, for example, when Base is either verbose and/or templated. The fact is that super is implemented in Java, as well as in C# (where it is called "base", unless I'm wrong). But C++ lacks this keyword. So, my questions: is this use of typedef super common/rare/never seen in the code you work with? is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)? should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already? Edit: Roddy mentionned the fact the typedef should be private. This would mean any derived class would not be able to use it without redeclaring it. But I guess it would also prevent the super::super chaining (but who's gonna cry for that?). Edit 2: Now, some months after massively using "super", I wholeheartedly agree with Roddy's viewpoint: "super" should be private.
Bjarne Stroustrup mentions in Design and Evolution of C++ that super as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized. Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced. After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem. Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post. So, no, this will probably never get standardized. If you don't have a copy, Design and Evolution is well worth the cover price. Used copies can be had for about $10.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ] }
180,606
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
You are probably looking for 'chr()': >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]>>> ''.join(chr(i) for i in L)'hello, world'
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ] }
180,629
I am using VS 2008/C# and binding a local List of helper classes as the DataSource for a DataGridView control. Calling the Remove() method on my List of helper classes fires the CellFormatting event of the DataGridView, which makes sense (a bit). When removing whatever happens to be the DataBoundItem of the last row in the grid (so long as the grid has more than one row) the DataGridView's Rows collection is not updated before this event fires. So, in the CellFormatting event handler, I get an IndexOutOfRangeException as the Rows collection is one too large. I've tried removing the row using the DataGridView.Rows.Remove() method, and binding using a BindingSource rather than binding the List directly as the data source. I found a few references to this occurance via Google, but answers were either not forthcoming or said to use a Delete() method on either the DataGridView or the DataGridView.Rows collection - neither of which currently exist. Sorting does not appear to be the issue either, as performing/not performing a sort results in the same outcome. The only exception to the "last row" being a problem for removal is if the DataGridView contains only one row - in which case everything works fine.
I've had this problem in the past, and if I remember correctly there's one of two things you can do. When you remove the record from the collection, set the datasource property on your datagridview to null, and then rebind it to your list. That should do the trick. Alternatively, you can handle the DataError event on your dataGridview and in the method you can say e.Cancel = true to suppress the exception, or you can further deal with it there.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25971/" ] }
180,647
I am hoping to find a resource for lining up input elements in a HTML page. I find it difficult to get a select element and a text box to be the same width even when using the width style attribute, and it is even more difficult across browsers. Finally, file inputs seem impossible to get to the same width cross browser. Are there any good guides or tips for accomplishing this? Perhaps there are some default CSS attributes I should be setting.
I tested this out in Internet Explorer 7, Firefox 3 and Safari/Google Chrome. I definitely see the problem with <select> and <input type="file"> . My findings showed that if you styled all the inputs at the same width, the <select> would be about 5 pixels shorter in all browsers. Using the Eric Meyer CSS reset script does not help this issue, however if you simply make your <select> inputs 5 pixels wider you'll get very good (albeit not perfect) alignment in the major browsers. The only one that differs is Safari/Google Chrome, and it appears to be 1 or 2 pixels wider than all the other browsers. As far as the <input type="file"> is concerned, you don't have much flexibility with styling there. If JavaScript is an option for you, you can implement the method shown on quirksmode to achieve greater control over the styling of the file upload control. See my full working example below in XHTML 1.0 Strict for a typical form with consistent input widths. Note that this does not use the 100% width trick pointed out by others here because it has the same problem with inconsistent widths. Additionally there are no tables used to render the form as tables should only be used for tabular data and not layout. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Example Form</title> <style type="text/css"> label, input, select, textarea { display: block; width: 200px; float: left; margin-bottom: 1em; } select { width: 205px; } label { text-align: right; width: 100px; padding-right: 2em; } .clear { clear: both; } </style></head><body> <form action="#"> <fieldset> <legend>User Profile</legend> <label for="fname">First Name</label> <input id="fname" name="fname" type="text" /> <br class="clear" /> <label for="lname">Last Name</label> <input id="lname" name="lname" type="text" /> <br class="clear" /> <label for="fav_lang">Favorite Language</label> <select id="fav_lang" name="fav_lang"> <option value="c#">C#</option> <option value="java">Java</option> <option value="ruby">Ruby</option> <option value="python">Python</option> <option value="perl">Perl</option> </select> <br class="clear" /> <label for="bio">Biography</label> <textarea id="bio" name="bio" cols="14" rows="4"></textarea> <br class="clear" /> </fieldset> </form></body></html>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18926/" ] }
180,710
So, I'm working under the assumption that we have typed languages because we make a lot of mistakes... so typing is one way to have the compiler do a lot of checks for us and help us out a bit (please let me know if it is my assumptions that's incorrect). However, if we introduce casting to a typed language, don't we re-introduce most the problems we had when were not able to type variables? I'm also aware that my assumption isn't the only reason why we type variables. Please share some of the other reasons why we have typed languages.
The bottom line is that strong typing lets the compiler check things for you and casting lets you override the strong typing when necessary.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ] }
180,741
How do you iterate over each file in a directory with a .bat or .cmd file? For simplicity please provide an answer that just echoes the filename or file path.
Command line usage: for /f %f in ('dir /b c:\') do echo %f Batch file usage: for /f %%f in ('dir /b c:\') do echo %%f Update : if the directory contains files with space in the names, you need to change the delimiter the for /f command is using. for example, you can use the pipe char. for /f "delims=|" %%f in ('dir /b c:\') do echo %%f Update 2 : (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq option on the for : for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f And if you need to use output redirection or command piping, use the escape char ( ^ ): for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/180741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
180,746
I have an upcoming project which will have to be able to print simple reports from its data. It'll be WPF-based, and I'm wondering which way to go. I know that WPF introduces its own printing technology (based on XPS) which looks quite easy to use. However, part of me wonders whether it would just be easier to use the ReportViewer control and embed it in a Windows Forms host control, since that will give users the ability to export to a variety of formats as well as print. Has anyone had any experience with printing/reporting from WPF? Which direction would you recommend?
We had this same issue, and ended up using RDLC/ReportViewer for now. There's no native WPF reporting tool (that I know of) and RDLC is pretty simple to use, and is free. The runtime overhead for it is small (around 2Mb) but you must remember to distribute it as it isn't part of the .NET Framework.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ] }
180,754
What are the best free resources for learning advanced batch-file usage?
It's not free, but it's probably the best. "Windows NT Shell Scripting" by Tim Hill . That said, whenever I try to do something 'advanced' in cmd batch files, I always end up regretting it. Always. edit: some explanation of the shortcomings of batch files: math capabilities are pathetic quoting support is an afterthought - if you need to pass a quoted string as an argument to a command that needs to be quoted itself, reserve a spot at the asylum (actually, I'm not sure it's possible) string manipulation is a patchwork of half implemented functionality Then there are the seemingly never-ending bits of oddities, corner cases, and inconsistencies that you run into at every turn. The only thing going for batch files is that they're supported on every Windows box out there. If you just want to automate executing a few commands as a group, great. Maybe add a simple loop, a couple of subroutines, and some environment variables to parameterize things. Beyond that I strongly recommend you use something else.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
180,760
Can someone explain how to use if-then statements and for loops in Makefiles? I can't seem to find any good documentation with examples.
Conditional Forms Simple conditional-directivetext-if-trueendif Moderately Complex conditional-directivetext-if-trueelsetext-if-falseendif More Complex conditional-directivetext-if-one-is-trueelseconditional-directivetext-if-trueelsetext-if-falseendifendif Conditional Directives If Equal Syntax ifeq (arg1, arg2)ifeq 'arg1' 'arg2'ifeq "arg1" "arg2"ifeq "arg1" 'arg2'ifeq 'arg1' "arg2" If Not Equal Syntax ifneq (arg1, arg2)ifneq 'arg1' 'arg2'ifneq "arg1" "arg2"ifneq "arg1" 'arg2'ifneq 'arg1' "arg2" If Defined Syntax ifdef variable-name If Not Defined Syntax ifndef variable-name foreach Function foreach Function Syntax $(foreach var, list, text) foreach Semantics For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/180760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2039/" ] }
180,777
I have a ListBox which displays items of variable height. I want to show as many items as will fit in the available space, without showing a vertical scrollbar. Other than surgery on the ListBox item template, is there a way to only show the number of items which will fit without scrolling?
<ListBox ScrollViewer.VerticalScrollBarVisibility="Auto" /> the default is visible
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ] }
180,778
I looked at the AdaCore site, as well as for A# (which now appears to be owned by AdaCore) and neither appear to be free (although I could have misread something). Any recommendations?
GNAT is available for download here: https://libre.adacore.com/ Look for "GNAT GPL Edition". Not sure why it is so well hidden on that little known site.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
180,809
Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface? In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter the changed data. Using a better model structure would be one way of reducing the duplication of the data, but there may be situation where the duplicated data needs to be changed on an individual basis in the future.
You can save as by just enabling adding this to your ModelAdmin: save_as = True This replaces the "Save and add another" button with a "Save as" button. "Save as" means the object will be saved as a new object (with a new ID), rather than the old object.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23366/" ] }
180,841
Here are some gems: Literals: var obj = {}; // Object literal, equivalent to var obj = new Object();var arr = []; // Array literal, equivalent to var arr = new Array();var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something'); Defaults: arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:arg = !!arg ? arg : 'default'; Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great: (function() { ... })(); // Creates an anonymous function and executes it Question: What other great syntactic sugar is available in javascript?
Getting the current datetime as milliseconds: Date.now() For example, to time the execution of a section of code: var start = Date.now();// some codealert((Date.now() - start) + " ms elapsed");
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/180841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17964/" ] }
180,853
What is the maximum length for the text string contained in a CEdit control in MFC? I get a beep when trying to add a character after the character 30001 is this documented anywhere? Can I display longer texts in a CEdit? Should I use another control? As "Windows programmer" says down below, the text length limit is not the same when the user types as when we programatically set the text using SetWindowText. The limit for setting a text programatically is not mentioned anywhere. The default text lentgth limit for the user typing is wrong. (see my own post below). I'm guessing that after I call pEdit->SetLimitText(0) the limit for both programatically and user input text length is 7FFFFFFE bytes. Am I right? In vista, when pasting text longer than 40000 characters into a CEdit, it becomes unresponsive. It does not matter if I called SetLimitText(100000) previously.
I found the documentation is wrong when mentioning the default size for a single line CEdit control in vista. I ran this code: CWnd* pWnd = dlg.GetDlgItem(nItemId);CEdit *edit = static_cast<CEdit*>(pWnd); //dynamic_cast does not workif(edit != 0){ UINT limit = edit->GetLimitText(); //The current text limit, in bytes, for this CEdit object. //value returned: 30000 (0x7530) edit->SetLimitText(0); limit = edit->GetLimitText(); //value returned: 2147483646 (0x7FFFFFFE) } the documentation states: Before EM_SETLIMITTEXT is called, the default limit for the amount of text a user can enter in an edit control is 32,767 characters. which is apparently wrong.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14022/" ] }
180,858
I've been putting a lot of thought into procedural generation of content for a while and I've never seen much experimentation with procedural music. We have fantastic techniques for generating models, animations, textures, but music is still either completely static or simply layered loops (e.g. Spore). Because of that, I've been thinking up optimal music generation techniques, and I'm curious as to what other people have in mind. Even if you haven't previously considered it, what do you think will work well? One technique per answer please, and include examples where possible. The technique can use existing data or generate the music entirely from scratch, perhaps on some sort of input (mood, speed, whatever).
Cellular Automata - read . You can also try it out here . Edit: rakkarage has supplied another resource: http://www.ibm.com/developerworks/java/library/j-camusic/
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977/" ] }
180,860
What is the maximum length in characters a CString object can hold?
Up to your available memory or INT_MAX-1 (whichever is less).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14022/" ] }
180,870
What is the best encryption library in C/C++ In terms of: entropy quality ease of use readability portability performance What's your favorite and why do you like it?
We've used OpenSSL with good success. Portable, standards compliant and easy to use.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ] }
180,875
Is there a way to write a BitmapEffect in 100% Managed Code? I know that it would run a lot slower than using unmanaged code, but I'd like to write a BitmapEffect but its been a long time since I've done any C++ programing, plus the application might have to run in partial trust (so unmanaged code won't be permissible). The effect is going to be run very rarely on static content. Simply getting the Bitmap of the rendered content and handing back a bitmap of the altered content would suffice.
We've used OpenSSL with good success. Portable, standards compliant and easy to use.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
180,884
When using $('.foo').click(function(){ alert("I haz class alertz!"); return false; }); in application.js, and <a href = "" class = "foo" id = "foobar_1" >Teh Foobar </a> in any div that initializes with the page, when clicking "Teh Foobar" it alerts and doesn't follow the link. However, when using the same code in application.js, and <a href = "" class = "foo" id = "foobar_1" >Teh Foobar </a> is being returned into a div by a form_remote_tag when clicked, "Teh Foobar" fails to alert, and functions as a link. What is happening, and how do I get around it?
We've used OpenSSL with good success. Portable, standards compliant and easy to use.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23885/" ] }
180,910
If a file is set to read only mode, how do I change it to write mode and vice versa from within Emacs?
M-x read-only-mode in very old versions of Emacs, the command was: M-x toggle-read-only On my Windows box, that amounts to Alt-x to bring up the meta prompt and typing "read-only-mode" to call the correct elisp function. If you are using the default keyboard bindings, C-x C-q (which you read aloud as "Control-X Control-Q") will have the same effect. Remember, however, given that emacs is essentially infinitely re-configurable, your mileage may vary. Following up from the commentary: you should note that the writeable status of the buffer does not change the writeable permission of the file. If you try to write out to a read only file , you'll see a confirmation message. However, if you own the file, you can write out your changes without changing the permissions on the file. This is very convenient if you'd like to make a quick change to a file without having to go through the multiple steps of add write permission, write out changes, remove write permission. I tend to forget that last step, leaving potentially critical files open for accidental changes later on.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
180,937
It's my understanding that common wisdom says to only use exceptions for truly exceptional conditions (In fact, I've seen that statement here at SO several times). However, Krzysztof Cwalina says: One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions. From a framework design perspective, there is no such thing as an “exceptional condition”. Whether a condition is exceptional or not depends on the context of usage, --- but reusable libraries rarely know how they will be used. For example, OutOfMemoryException might be exceptional for a simple data entry application; it’s not so exceptional for applications doing their own memory management (e.g. SQL server). In other words, one man’s exceptional condition is another man’s chronic condition. He then also goes on to say that exceptions should be used for: Usage errors Program errors System failures Considering Krzysztof Cwalina is the PM for the CLR team at MS I ask: What do you think of his statement?
This sounds over-simplistic, but I think it makes sense to simply use exceptions where they are appropriate. In languages like Java and Python, exceptions are very common, especially in certain situations. Exceptions are appropriate for the type of error you want to bubble up through a code path and force the developer to explicitly catch. In my own coding, I consider the right time to add an exception when the error either can't be ignored, or it's simply more elegant to throw an exception instead of returning an error value to a function call etc. Some of the most appropriate places for exceptions that I can think of offhand: NotImplementedException - very appropriate way of designating that a particular method or function isn't available, rather than simply returning without doing anything. OutOfMemory exceptions - it's difficult to imagine a better way of handling this type of error, since it represents a process-wide or OS-wide memory allocation failure. This is essential to deal with, of course! NullPointerException - Accessing a null variable is a programmer mistake, and IMOthis is another good place to force an error to bubble to the surface ArrayIndexException - In an unforgiving language like C, buffer overflows are disastrous. Nicer languages might return a null value of some type, or in some implementations, even wrap around the array. In my opinion, throwing an exception is a much more elegant response. This is by no means a comprehensive list, but hopefully it illustrates the point. Use exceptions where they are elegant and logical. As always with programming, the right tool for the right job is good advice. There's no point going exception-crazy for nothing, but it's equally unwise to completely ignore a powerful and elegant tool at your disposal.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/180937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ] }
180,947
Is there a freely available Base64 decoding code snippet in C++?
See Encoding and decoding base 64 with C++ . Here is the implementation from that page: /* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger [email protected]*/static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/'));}std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret;}std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret;}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/180947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19104/" ] }
180,978
I have many years of experience in Java including Swing, Servlet and JDBC, but have never programmed for a Java EE server. Many job advertisements from large companies are specifically asking for Java EE experience. Are there specific skills or development environments that I should learn to qualify for these kinds of jobs?
Download JBoss and get to work on the sample applications in the documentation. If you've done java, you're 95% there. Java EE adds the container and naming aspect to the java you already know and love. With the advent of EJB3, beans got a lot simpler as you only need a couple of annotations to get rolling with EJB. Java EE can be a bit daunting with the acronym soup of technologies available, but concentrate on the basics: EJB3, JNDI, JMS, data access (like Hibernate/JDO), and container basics.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621/" ] }
180,979
I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly. Lets say that I am trying to shuffle the randomizer array. int[] randomizer = new int[] {200,300,212,111,6,2332}; Collections.shuffle(Arrays.asList(randomizer)); For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas?
Arrays.asList cannot be used with arrays of primitives. Use this instead: Integer[] randomizer = new Integer[] {200,300,212,111,6,2332}; Collections.shuffle(Arrays.asList(randomizer)); The same rule applies to most classes in the collections framework, in that you can't use primitive types. The original code (with int[] ) compiled fine, but did not work as intended, because of the behaviour of the variadic method asList : it just makes a one-element list, with the int array as its only member.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/180979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ] }
180,985
Why does tempuri.org exist? Why does each XML Webservice require its own namespace, unique from any other on the web?
Webservices require unique namespaces so they don't confuse each others schemas and whatever with each other. A URL (domain, subdomain, subsubdomain, etc) is a clever identifier as it's "guaranteed" to be unique, and in most circumstances you've already got one.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/180985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ] }
180,986
What is the difference between the search() and match() functions in the Python re module? I've read the Python 2 documentation ( Python 3 documentation ), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.
re.match is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using ^ in the pattern. As the re.match documentation says: If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match. Note: If you want to locate a match anywhere in string, use search() instead. re.search searches the entire string, as the documentation says : Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. So if you need to match at the beginning of the string, or to match the entire string use match . It is faster. Otherwise use search . The documentation has a specific section for match vs. search that also covers multiline strings: Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default). Note that match may differ from search even when using a regular expression beginning with '^' : '^' matches only at the start of the string, or in MULTILINE mode also immediately following a newline. The “ match ” operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional pos argument regardless of whether a newline precedes it. Now, enough talk. Time to see some example code: # example code:string_with_newlines = """somethingsomeotherthing"""import reprint re.match('some', string_with_newlines) # matchesprint re.match('someother', string_with_newlines) # won't matchprint re.match('^someother', string_with_newlines, re.MULTILINE) # also won't matchprint re.search('someother', string_with_newlines) # finds somethingprint re.search('^someother', string_with_newlines, re.MULTILINE) # also finds somethingm = re.compile('thing$', re.MULTILINE)print m.match(string_with_newlines) # no matchprint m.match(string_with_newlines, pos=4) # matchesprint m.search(string_with_newlines, re.MULTILINE) # also matches
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/180986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ] }
181,015
I am just checking out F#, so apologies if this is a silly question, but in the VS2008 F# CTP 1.9.6.2 'Tutorial' project, both // and /// are used for commenting code. Is there a functional difference between the two slash vs three slash commenting, or is it convention (as it appears in the tutorial code) to comment a function with /// and use // for everything else?
Using three slashes (///) is a C# convention for XML Documentation Comments that is adopted by F# as well.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ] }
181,036
I'm trying to get this simple PowerShell script working, but I think something is fundamentally wrong. ;-) ls | ForEach { "C:\Working\tools\custom-tool.exe" $_ } I basically want to get files in a directory, and pass them one by one as arguments to the custom tool.
ls | %{C:\Working\tools\custom-tool.exe $_} As each object comes down the pipeline the tool will be run against it. Putting quotes around the command string causes it to be... a string! The local variable "$_" it then likely doesn't know what to do with so pukes with an error.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18437/" ] }
181,038
I installed Ruby and Ruby on Rails yesterday on Vista 32bit using the directions on this site: http://rubyonrails.org/down So I downloaded the installer, then Gems, then I downloaded rails with Gems. Now I can't use the Gem or Ruby commands in the command line... so I assume there's something wrong with the environment variables, but I hav eno idea how to set them up in Vista or what to put. Can anyone help me with this?
To set up the environment variables, do this Fire up the start menu Right-Click on Computer and select Properties Click Advanced system settings in the left-hand bar, and confirm the UAC prompt Select the Advanced tab (it's 3rd) Click Environment Variables... (at the bottom) In the top box ( User variables for XXX ) either find the entry for PATH , or click new to create the entry. If there is already a PATH use semi-colons to seperate each directory listed in it Put c:\ruby\bin (change if you installed ruby somewhere else) in. Click OK a lot of times to close all the windows we opened. Restart your command prompt. gem and ruby and irb should now all work. Whoever said that GUI tools are slower than command line tools. pshaw!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713/" ] }
181,046
I am trying to learn some of the basic and advanced features of visual studio, Anyone find sites that have this type of information ? I see this: https://stackoverflow.com/questions/86355/best-way-to-learn-visual-studio-power-features But it seems more related to tips and advanced features. All three versions ( 2003, 2005, 2008 )
To set up the environment variables, do this Fire up the start menu Right-Click on Computer and select Properties Click Advanced system settings in the left-hand bar, and confirm the UAC prompt Select the Advanced tab (it's 3rd) Click Environment Variables... (at the bottom) In the top box ( User variables for XXX ) either find the entry for PATH , or click new to create the entry. If there is already a PATH use semi-colons to seperate each directory listed in it Put c:\ruby\bin (change if you installed ruby somewhere else) in. Click OK a lot of times to close all the windows we opened. Restart your command prompt. gem and ruby and irb should now all work. Whoever said that GUI tools are slower than command line tools. pshaw!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
181,050
With very large amounts of ram these days I was wondering, it is possible to allocate a single chunk of memory that is larger than 4GB? Or would I need to allocate a bunch of smaller chunks and handle switching between them? Why???I'm working on processing some openstreetmap xml data and these files are huge. I'm currently streaming them in since I can't load them all in one chunk but I just got curious about the upper limits on malloc or new.
Short answer: Not likely In order for this to work, you absolutely would have to use a 64-bit processor.Secondly, it would depend on the Operating System support for allocating more than 4G of RAM to a single process. In theory, it would be possible, but you would have to read the documentation for the memory allocator. You would also be more susceptible to memory fragmentation issues. There is good information on Windows memory management .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ] }
181,082
I have followed all the instructions here: http://www.tonyspencer.com/2003/10/22/curl-with-php-and-apache-on-windows/ to install & config apacheget the PHP5 packagesand get the CURL packages. I run the apache and run a PHP script. no problem.but when I run the php script with curl, it fails. It returns: **Call to undefined function curl_version() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\testing.php on line 5** In which line 5 is a called to curl_init() I output the php -i to see whether the right path to extension is called. It is correctly set: extension_dir => C:\PHP\ext => C:\PHP\extcURL support => enabledcURL Information => libcurl/7.16.0 OpenSSL/0.9.8g zlib/1.2.3 I even tried to run curl_version() but still, same kind of error comes up. It looks like the PHP can't find the CURL extension, but the php.ini (and also php -i) shows that it is set. any idea? :) P.S> System I m running on:Windows XPApache 2.2PHP 5.2.6CURL Win32 Generic Binaries: Win32 2000/XP metalink 7.19.0 binary SSL enabled Daniel Stenberg 249 KB I didn't get this: Win32 2000/XP 7.19.0 libcurl SSL enabled Günter Knauf 1.55 MBShould I get this one instead? The reason I need to use CURL is that it is the requirement from my project. So, I can only stick with that.XAMPP... how does it work in Windows? Is there any site that you can recommend? Thanks. I have tried a lot of things on installing cURL and check everything, but still, I'm stilling circling around the problem and have no idea what's going on. The Apache server uses the right PHP.ini. and the PHP.ini has the correct extension_dir and extension=php_curl.dllI have no idea why it doesn't work. even I follow every step for setting it up. :(
You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser. Write down the PHP ini directory path you see in the variables list now!You will probably notice that it's different from your PHP-CLI ini file. Enable the extension You're done :-)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196874/" ] }
181,090
I have a tree of active record objects, something like: class Part < ActiveRecord::Base has_many :sub_parts, :class_name => "Part" def complicated_calculation if sub_parts.size > 0 return self.sub_parts.inject(0){ |sum, current| sum + current.complicated_calculation } else sleep(1) return rand(10000) end endend It is too costly to recalculate the complicated_calculation each time. So, I need a way to cache the value. However, if any part is changed, it needs to invalidate its cache and the cache of its parent, and grandparent, etc. As a rough draft, I created a column to hold the cached calculation in the "parts" table, but this smells a little rotten. It seems like there should be a cleaner way to cache the calculated values without stuffing them along side the "real" columns.
I suggest using association callbacks. class Part < ActiveRecord::Base has_many :sub_parts, :class_name => "Part", :after_add => :count_sub_parts, :after_remove => :count_sub_parts private def count_sub_parts update_attribute(:sub_part_count, calculate_sub_part_count) end def calculate_sub_part_count # perform the actual calculation here endend Nice and easy =)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23899/" ] }
181,091
I have an array of hashes, and I want the unique values out of it. Calling Array.uniq doesn't give me what I expect. a = [{:a => 1},{:a => 2}, {:a => 1}]a.uniq # => [{:a => 1}, {:a => 2}, {:a => 1}] Where I expected: [{:a => 1}, {:a => 2}] In searching around on the net, I didn't come up with a solution that I was happy with. Folks recommended redefining Hash.eql? and Hash.hash , since that is what Array.uniq is querying. Edit:Where I ran into this in the real world, the hashes were slightly more complex. They were the result of parsed JSON that had multiple fields, some of which the values were hashes as well. I had an array of those results that I wanted to filter out the unique values. I don't like the redefine Hash.eql? and Hash.hash solution, because I would either have to redefine Hash globally, or redefine it for each entry in my array. Changing the definition of Hash for each entry would be cumbersome, especially since there may be nested hashes inside of each entry. Changing Hash globally has some potential, especially if it were done temporarily. I'd want to build another class or helper function that wrapped saving off the old definitions, and restoring them, but I think this adds more complexity than is really needed. Using inject seems like a good alternative to redefining Hash .
I can get what I want by calling inject a = [{:a => 1},{:a => 2}, {:a => 1}]a.inject([]) { |result,h| result << h unless result.include?(h); result } This will return: [{:a=>1}, {:a=>2}]
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12086/" ] }
181,095
I would like to extract from a general HTML page, all the text (displayed or not). I would like to remove any HTML tags Any javascript Any CSS styles Is there a regular expression (one or more) that will achieve that?
You can't really parse HTML with regular expressions. It's too complex. RE's won't handle <![CDATA[ sections correctly at all. Further, some kinds of common HTML things like &lt;text> will work in a browser as proper text, but might baffle a naive RE. You'll be happier and more successful with a proper HTML parser. Python folks often use something Beautiful Soup to parse HTML and strip out tags and scripts. Also, browsers, by design, tolerate malformed HTML. So you will often find yourself trying to parse HTML which is clearly improper, but happens to work okay in a browser. You might be able to parse bad HTML with RE's. All it requires is patience and hard work. But it's often simpler to use someone else's parser.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363/" ] }
181,097
I wanted to do something like this: <asp:Label ID="lblMyLabel" onclick="lblMyLabel_Click" runat="server">My Label</asp:Label> I know that in Javascript I can do: <span onclick="foo();">My Label</span> So I'm wondering why I can't do that with a Label object.
You can use Attributes to add onclick client side callback. I didn't know you can do this on span tags, but if it works you can add 'onclick' by lblMyLabel.Attributes.Add("onclick", "foo();"); But foo(); would need to be a client side javascript function. System.Web.UI.WebControls.Label does NOT have OnClick server event. You could look into using AJAX if you want server callback with example above. You could also use LinkButton like other say. You can make it not look like a link by using CSS, if it is just that underline you are concerned about. ASPX: <asp:LinkButton ID="LinkButton1" runat="server" CssClass="imjusttext" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton> CSS: a.imjusttext{ color: #000000; text-decoration: none; }a.imjusttext:hover { text-decoration: none; }
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/181097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ] }
181,132
On my homepage I got: <ul id="login"> <li> <a id="loginswitch" href="./login-page">log-in</a> | </li> <li> <a id="signupswitch" href="./signup-page">sign-up</a> </li></ul> Via MooTools, I get these anchor elements by id so that once they're clicked, a flashy div will popup below them that contains the login or signup form (with methods to stop the propagation of events of course)and upon filling-up the fields the AJAX call kicks in - that's supposed to create a session and reload the page so that the user would have a visual that he is now logged in and user-level-controls appears etc.. The ajax call is initiated by the MooTools AJAX class and evalScripts option is set to true. The AJAX page returns the script code: <script type="text/javascript">window.location = self.location;</script> This system works perfectly - now I'm wondering why if I change the anchors' href values to href="#" my scripts won't work anymore? Does it have anything to do with the window? Did it change its property when I clicked a link or so even when the event's propagation was stopped??
window.location = self.location; This JavaScript is executing . When it executes, the browser is being told to replace the value of window.location with a new value. Not all browsers will react the same way here. Some will probably work as you expect, but others will get smart about it and compare the two values. The browser knows what page it's on, and it knows that you're just asking for it to go to the same page. Browser Cache The browser even has a copy of your current page in cache . It can talk to the server and ask whether the page it has in cache is still valid. If the cache is valid, it may decide not to force a reload of the page. Behind the scenes, this happens with HTTP headers. Browsers and servers can communicate over HTTP in many ways. In this case, your browser sends a quick request to the server saying something like this: GET /stackoverflow.com/posts/196643/index.htmlHTTP/1.1Host: www.stackoverflow.comUser-Agent: Mozilla/5.0If-Modified-Since: Sun, 12 Oct 2008 20:41:31 GMT This is called a conditional GET request . By saying If-Modified-Since , your browser is saying, "Give me that file, but only if it has been modified since the last time I saw it." Long story short, you haven't explicitly told the browser to reload the page. Here's how you can: location.reload( true ); The "true" is an optional parameter , for forcing a reload . The browser won't even look at the cache. It will just do as you say.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24744/" ] }
181,159
I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. I'm using php, and at the moment this little snippet is responsible for generating the UID: $id = tempnam (".", "");unlink($id);$id = substr($id, 2); This code is hideous: it creates a temporary file on the FS and deletes it, retaining only the relevant unique part of the generated string. Is there any better way to do this, most preferably without any external dependencies? Thanks much!
string uniqid ([ string $prefix [, bool $more_entropy ]] ) Gets a prefixed unique identifier based on the current time in microseconds. USAGE: $id = uniqid(rand(), true);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ] }
181,188
In VB.NET I often Catch…When : Try …Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES" …End Try Is there a C# equivalent to Catch…When ? I don't want to resort to using an if statement inside a catch if possible.
This functionality was announced for C# 6. It is now possible to write try { … }catch (MyException e) when (myfilter(e)){ …} You can download the preview of Visual Studio 2015 now to check this out, or wait for the official release.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ] }
181,214
Implementing a file upload under html is fairly simple, but I just noticed that there is an 'accept' attribute that can be added to the <input type="file" ...> tag. Is this attribute useful as a way of limiting file uploads to images, etc? What is the best way to use it? Alternatively, is there a way to limit file types, preferably in the file dialog, for an html file input tag?
The accept attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current input . While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types. Usage Note: These examples were written based on the current specification and may not actually work in all (or any) browsers. The specification may also change in the future, which could break these examples. h1 { font-size: 1em; margin:1em 0; }h1 ~ h1 { border-top: 1px solid #ccc; padding-top: 1em; } <h1>Match all image files (image/*)</h1><p><label>image/* <input type="file" accept="image/*"></label></p><h1>Match all video files (video/*)</h1><p><label>video/* <input type="file" accept="video/*"></label></p><h1>Match all audio files (audio/*)</h1><p><label>audio/* <input type="file" accept="audio/*"></label></p><h1>Match all image files (image/*) and files with the extension ".someext"</h1><p><label>.someext,image/* <input type="file" accept=".someext,image/*"></label></p><h1>Match all image files (image/*) and video files (video/*)</h1><p><label>image/*,video/* <input type="file" accept="image/*,video/*"></label></p> From the HTML Specification ( source ) The accept attribute may be specified to provide user agents with a hint of what file types will be accepted. If specified, the attribute must consist of a set of comma-separated tokens , each of which must be an ASCII case-insensitive match for one of the following: The string audio/* Indicates that sound files are accepted. The string video/* Indicates that video files are accepted. The string image/* Indicates that image files are accepted. A valid MIME type with no parameters Indicates that files of the specified type are accepted. A string whose first character is a U+002E FULL STOP character (.) Indicates that files with the specified file extension are accepted.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/181214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691/" ] }
181,254
If I have a style defined .style1{ width: 140px;} can I reference it from a second style? .style2{ ref: .style1;} Or is there a way via javascript/jQuery? --- Edit To clarify the problem, I am trying to apply whatever style is defined for a #x and #c to .x and .c without altering the CSS as the CSS is going to have updates that are out of my control. I used width but really the style would be something more complex with font, border and other style elements being specified. Specifying multiple class names does work when the style is being applied to a class so I'll mark existing responses as answers, but I need to take the style being applied to an id and also apply it to a class style ... if that makes any sense.
There's no way to do it with CSS -- it's an oft-requested feature, but not included in the spec yet. You also can't do it directly with JS, but there's sort of a hacky workaround: $('.style2').addClass ('style1');
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25372/" ] }
181,272
When we execute select count(*) from table_name it returns the number of rows. What does count(1) do? What does 1 signify here? Is this the same as count(*) (as it gives the same result on execution)?
The parameter to the COUNT function is an expression that is to be evaluated for each row. The COUNT function returns the number of rows for which the expression evaluates to a non-null value. ( * is a special expression that is not evaluated, it simply returns the number of rows.) There are two additional modifiers for the expression: ALL and DISTINCT. These determine whether duplicates are discarded. Since ALL is the default, your example is the same as count(ALL 1), which means that duplicates are retained. Since the expression "1" evaluates to non-null for every row, and since you are not removing duplicates, COUNT(1) should always return the same number as COUNT(*).
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/181272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11614/" ] }
181,284
I've read somewhere that functional programming is suitable to take advantage of multi-core trend in computing. I didn't really get the idea. Is it related to the lambda calculus and von neumann architecture?
Functional programming minimizes or eliminates side effects and thus is better suited to distributed programming. i.e. multicore processing. In other words, lots of pieces of the puzzle can be solved independently on separate cores simultaneously without having to worry about one operation affecting another nearly as much as you would in other programming styles.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17685/" ] }
181,309
In a nutshell, there's a global stylesheet: a { font-family: Arial; } I want to use a different font family for a particular link: <a href="..." style="font-family: Helvetica;">...</a> or <span style="font-family: Helvetica;"><a href="...">...</a></span> but nothing works. Is there an easy way to do this? P.S. I'm dynamically (via PHP) assign different fonts to different links, so creating a special class is not an option.
Unless you have a specific font named Helvetica, you should realise that on some platforms (such as Windows, via FontSubstitutes ), Helvetica is aliased to Arial. That might be the source of the problem. Try another font and see.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17216/" ] }
181,321
I've installed Oracle XE with APEX, but forgot to write down the URL to access it. How may I determine the URL?
The default is http://127.0.0.1:8080/apex If you happen to be on Windows, there will also be an entry in the Start menu (Programs > Oracle XE > Database homepage )
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ] }
181,342
What is the best way to automatically install an MSI file or installer .exe? We want to do some automated testing from our build system on the installed copy of the product. Our installer has the usual license acceptance screen, install location, etc. As FryHard pointed out there are two options in particular that seem handy: "/quiet" - no use interaction "/passive" - process bar only, unattended mode
To automate the installation of an MSI package, you can use the /I option, like this: msiexec.exe /qn /i mypackage.msi Keep in mind that you need to specify the properties the MSI package expect the user to specify through the UI, and for which it does not have a default value. You can use the Orca tool to see the list of properties and fiddle around with MSI conditions, etc. And to set values for the properties, you can just specify it in command line; e.g. to set a property ISDEBUG: msiexec.exe /qn /i mypackage.msi ISDEBUG=1 Side note : To automate uninstall, use the /X option with the package or the product code: msiexec.exe /qn /x mypackage.msi or this (where you need to change the CLSID with your product code): msiexec.exe /qn /x {B741B8A3-8DCB-44E0-B06F-2A11F56572DB}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18437/" ] }
181,348
Let me start with a specific example of what I'm trying to do. I have an array of year, month, day, hour, minute, second and millisecond components in the form [ 2008, 10, 8, 00, 16, 34, 254 ] . I'd like to instantiate a Date object using the following standard constructor: new Date(year, month, date [, hour, minute, second, millisecond ]) How can I pass my array to this constructor to get a new Date instance? [ Update : My question actually extends beyond this specific example. I'd like a general solution for built-in JavaScript classes like Date, Array, RegExp, etc. whose constructors are beyond my reach. ] I'm trying to do something like the following: var comps = [ 2008, 10, 8, 00, 16, 34, 254 ];var d = Date.prototype.constructor.apply(this, comps); I probably need a " new " in there somewhere. The above just returns the current time as if I had called " (new Date()).toString() ". I also acknowledge that I may be completely in the wrong direction with the above :) Note : No eval() and no accessing the array items one by one, please. I'm pretty sure I should be able to use the array as is. Update: Further Experiments Since no one has been able to come up with a working answer yet, I've done more playing around. Here's a new discovery. I can do this with my own class: function Foo(a, b) { this.a = a; this.b = b; this.toString = function () { return this.a + this.b; };}var foo = new Foo(1, 2);Foo.prototype.constructor.apply(foo, [4, 8]);document.write(foo); // Returns 12 -- yay! But it doesn't work with the intrinsic Date class: var d = new Date();Date.prototype.constructor.call(d, 1000);document.write(d); // Still returns current time :( Neither does it work with Number: var n = new Number(42);Number.prototype.constructor.call(n, 666);document.write(n); // Returns 42 Maybe this just isn't possible with intrinsic objects? I'm testing with Firefox BTW.
I've done more investigation of my own and came up with the conclusion that this is an impossible feat , due to how the Date class is implemented. I've inspected the SpiderMonkey source code to see how Date was implemented. I think it all boils down to the following few lines: static JSBoolDate(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval){ jsdouble *date; JSString *str; jsdouble d; /* Date called as function. */ if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) { int64 us, ms, us2ms; jsdouble msec_time; /* NSPR 2.0 docs say 'We do not support PRMJ_NowMS and PRMJ_NowS', * so compute ms from PRMJ_Now. */ us = PRMJ_Now(); JSLL_UI2L(us2ms, PRMJ_USEC_PER_MSEC); JSLL_DIV(ms, us, us2ms); JSLL_L2D(msec_time, ms); return date_format(cx, msec_time, FORMATSPEC_FULL, rval); } /* Date called as constructor. */ // ... (from here on it checks the arg count to decide how to create the date) When Date is used as a function (either as Date() or Date.prototype.constructor() , which are exactly the same thing), it defaults to returning the current time as a string in the locale format. This is regardless of any arguments that are passed in: alert(Date()); // Returns "Thu Oct 09 2008 23:15:54 ..."alert(typeof Date()); // Returns "string"alert(Date(42)); // Same thing, "Thu Oct 09 2008 23:15:54 ..."alert(Date(2008, 10, 10)); // Dittoalert(Date(null)); // Just doesn't care I don't think there's anything that can be done at the JS level to circumvent this. And this is probably the end of my pursuit in this topic. I've also noticed something interesting: /* Set the value of the Date.prototype date to NaN */ proto_date = date_constructor(cx, proto); if (!proto_date) return NULL; *proto_date = *cx->runtime->jsNaN; Date.prototype is a Date instance with the internal value of NaN and therefore, alert(Date.prototype); // Always returns "Invalid Date" // on Firefox, Opera, Safari, Chrome // but not Internet Explorer IE doesn't disappoint us. It does things a bit differently and probably sets the internal value to -1 so that Date.prototype always returns a date slightly before epoch. Update I've finally dug into ECMA-262 itself and it turns out, what I'm trying to achieve (with the Date object) is -- by definition -- not possible: 15.9.2 The Date Constructor Called as a Function When Date is called as a function rather than as a constructor, it returns a string representing the current time (UTC). NOTE The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments. 15.9.2.1 Date ( [ year [, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] ] ] ) All of the arguments are optional; any arguments supplied are accepted but are completely ignored. A string is created and returned as if by the expression (new Date()).toString() .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/181348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23501/" ] }