source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
181,356
What am I doing wrong here? string q = "john s!";string clean = Regex.Replace(q, @"([^a-zA-Z0-9]|^\s)", string.Empty);// clean == "johns". I want "john s";
just a FYI string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty); would actually be better like string clean = Regex.Replace(q, @"[^\w\s]", string.Empty);
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/181356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ] }
181,406
I have been using Ruby for a while now and I find, for bigger projects, it can take up a fair amount of memory. What are some best practices for reducing memory usage in Ruby? Please, let each answer have one "best practice" and let the community vote it up.
Don't abuse symbols. Each time you create a symbol, ruby puts an entry in it's symbol table. The symbol table is a global hash which never gets emptied. This is not technically a memory leak, but it behaves like one. Symbols don't take up much memory so you don't need to be too paranoid, but it pays to be aware of this. A general guideline: If you've actually typed the symbol in code, it's fine (you only have a finite amount of code after all), but don't call to_sym on dynamically generated or user-input strings, as this opens the door to a potentially ever-increasing number
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ] }
181,408
What is the best way to write bytes in the middle of a file using Java?
Reading and Writing in the middle of a file is as simple as using a RandomAccessFile in Java. RandomAccessFile , despite its name, is more like an InputStream and OutputStream and less like a File . It allows you to read or seek through bytes in a file and then begin writing over whichever bytes you care to stop at. Once you discover this class, it is very easy to use if you have a basic understanding of regular file i/o. A small example: public static void aMethod(){ RandomAccessFile f = new RandomAccessFile(new File("whereDidIPutTHatFile"), "rw"); long aPositionWhereIWantToGo = 99; f.seek(aPositionWhereIWantToGo); // this basically reads n bytes in the file f.write("Im in teh fil, writn bites".getBytes()); f.close();}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ] }
181,426
I'm making a Stored Procedure that basically concatenates a long string with data from many records. I want to do: set @output = @output + 'aaa' + LINEBREAK How do I specify that line break?
DECLARE @LINEBREAK AS varchar(2)SET @LINEBREAK = CHAR(13) + CHAR(10)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ] }
181,427
I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things: Define an interface for a listener type which would contain a number of method definitions Define adapter class for that interface to make things easier if I'm not interested in all the events defined in a listener Define Add, Remove and Get[] methods in the class which raises the events Define protected fire methods to do the dirty work of looping through the list of added listeners and calling the correct method This I understand (and like!) - I know I could do this exactly the same in c#, but it seems that a new (better?) system is in place for c#. After reading countless tutorials explaining the use of delegates and events in c# I still am no closer to really understanding what is going on :S In short, for the following methods how would I implement the event system in c#: void computerStarted(Computer computer);void computerStopped(Computer computer);void computerReset(Computer computer);void computerError(Computer computer, Exception error); ^ The above methods are taken from a Java application I once made which I'm trying to port over to c#. Many many thanks!
You'd create four events, and methods to raise them, along with a new EventArgs-based class to indicate the error: public class ExceptionEventArgs : EventArgs{ private readonly Exception error; public ExceptionEventArgs(Exception error) { this.error = error; } public Error { get { return error; } }}public class Computer{ public event EventHandler Started = delegate{}; public event EventHandler Stopped = delegate{}; public event EventHandler Reset = delegate{}; public event EventHandler<ExceptionEventArgs> Error = delegate{}; protected void OnStarted() { Started(this, EventArgs.Empty); } protected void OnStopped() { Stopped(this, EventArgs.Empty); } protected void OnReset() { Reset(this, EventArgs.Empty); } protected void OnError(Exception e) { Error(this, new ExceptionEventArgs(e)); }} Classes would then subscribe to the event using either a method or a an anonymous function: someComputer.Started += StartEventHandler; // A methodsomeComputer.Stopped += delegate(object o, EventArgs e){ Console.WriteLine("{0} has started", o);};someComputer.Reset += (o, e) => Console.WriteLine("{0} has been reset"); A few things to note about the above: The OnXXX methods are protected so that derived classes can raise the events. This isn't always necessary - do it as you see fit. The delegate{} piece on each event declaration is just a trick to avoid having to do a null check. It's subscribing a no-op event handler to each event The event declarations are field-like events . What's actually being created is both a variable and an event. Inside the class you see the variable; outside the class you see the event. See my events/delegates article for much more detail on events.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15075/" ] }
181,432
The class method to create an index path with one or more nodes is: + (id)indexPathWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length How do we create the "indexes" required in the first parameter? The documentation listed it as Array of indexes to make up the index path but it is expecting a (NSUinteger *). To create an index path of 1.2.3.4, is it simply an array of [1,2,3,4] ?
You are correct. You might use it like this: NSUInteger indexArr[] = {1,2,3,4};NSIndexPath *indexPath = [NSIndexPath indexPathWithIndexes:indexArr length:4];
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/181432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1987/" ] }
181,453
I would like to evaluate .NET as a development platform for a desktop application. I am looking for good examples of .NET desktop applications used in the mainstream. The only ones I know of are: Visual Studio (The copy website formis one example.) Team Explorer UI Paint.NET Reflector Gnome Do (An app launcher for Gnome; runs on Mono) I am looking for more examples; open source, freeware or a demo version in that order. Suggestions?
SharpDevelop is an open source Development IDE for .NET very much like VS.NET written in .NET (iirc it still has some pinvokes, but it is all managed code) and is quite large and feature complete. You can even get the source code for it to look at.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ] }
181,459
Is there a better way to do this? -(NSDate *)getMidnightTommorow { NSCalendarDate *now = [NSCalendarDate date]; NSCalendarDate *tomorrow = [now dateByAddingYears:0 months:0 days:1 hours:0 minutes:0 seconds:0]; return [NSCalendarDate dateWithYear:[tomorrow yearOfCommonEra] month:[tomorrow monthOfYear] day:[tomorrow dayOfMonth] hour:0 minute:0 second:0 timeZone:[tomorrow timeZone]];} Note that I always want the next midnight, even if it happens to be midnight when I make that call, however if it happens to be 23:59:59, I of course want the midnight that is coming in one second. The natural language functions seem flaky, and I'm not sure what Cocoa would do if I pass 32 in the "day" field. (If that'd work I could drop the [now dateByAddingYears:...] call)
From the documentation : Use of NSCalendarDate strongly discouraged. It is not deprecated yet, however it may be in the next major OS release after Mac OS X v10.5. For calendrical calculations, you should use suitable combinations of NSCalendar, NSDate, and NSDateComponents, as described in Calendars in Dates and Times Programming Topics for Cocoa . Following that advice: NSDate *today = [NSDate date];NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];NSDateComponents *components = [[NSDateComponents alloc] init];components.day = 1;NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];[components release];NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;components = [gregorian components:unitFlags fromDate:tomorrow];components.hour = 0;components.minute = 0;NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];[gregorian release];[components release]; (I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.) Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although dateFromComponents: may tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23033/" ] }
181,471
The new awesome Ctrl + . keyboard shortcut to show smart tags has suddenly stopped working, a week or so after I discovered it :( I am missing it badly, having had to revert back to Ctrl + Alt + F10 , which really just isn't the same. I recently installed F# CTP 1.9.6.2 Has anyone else installed this CTP and still has Ctrl + . Lost Ctrl + . without installing F# Even better, found how to get it back again? EDIT In attempting John Sheehan recommendation, I have noticed that my available mapping schemes only include Visual C# 2005 , should I not have a 2008? Also the mapped shortcut to this is OtherContextMenus.FSIConsoleContext.CancelEvaluation
From the documentation : Use of NSCalendarDate strongly discouraged. It is not deprecated yet, however it may be in the next major OS release after Mac OS X v10.5. For calendrical calculations, you should use suitable combinations of NSCalendar, NSDate, and NSDateComponents, as described in Calendars in Dates and Times Programming Topics for Cocoa . Following that advice: NSDate *today = [NSDate date];NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];NSDateComponents *components = [[NSDateComponents alloc] init];components.day = 1;NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];[components release];NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;components = [gregorian components:unitFlags fromDate:tomorrow];components.hour = 0;components.minute = 0;NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];[gregorian release];[components release]; (I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.) Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although dateFromComponents: may tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ] }
181,485
I've incorporated Apple's Reachability sample into my own project so I know whether or not I have a network connection - if I don't have a network connection, I don't bother sending out and requests. I decided to go with the status notification implementation because it seemed easier to have the reachablity updated in the background and have the current results available immediately as opposed to kicking off a synchronous request whenever I want to make a network connection. My problem is that I start getting false negatives when on an EDGE network - the phone has connectivity, but the app thinks this isn't the case. My understanding is you don't get a notification when an EDGE connection, so my assumption is that I lost and regained the connection at some point. Restarting the app is usually sufficient to see the network connection. This isn't an optimal solution, so I was wondering if anybody else came across this problem and had any thoughts on a solutions. (I don't know whether this applies to 3G as well; I'm running a first gen iPhone).
Reachability notificataions didn't seem to be reliable for me either, for detecting Wi-Fi. So I just use polling instead. Checking every 5 seconds seems to do no harm. - (void) checkReachability { BOOL connected = ([[Reachability sharedReachability] localWiFiConnectionStatus] == ReachableViaWiFiNetwork); // Do something... [self performSelector:@selector(checkReachability) withObject:nil afterDelay:5.0];}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24168/" ] }
181,530
Sometimes I break long conditions in if s onto several lines. The most obvious way to do this is: if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces. For the moment I'm using: if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something But this isn't very pretty. :-) Can you recommend an alternative way?
You don't need to use 4 spaces on your second conditional line. Maybe use: if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something Also, don't forget the whitespace is more flexible than you might think: if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4' ): do_somethingif (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something Both of those are fairly ugly though. Maybe lose the brackets (the Style Guide discourages this though)? if cond1 == 'val1' and cond2 == 'val2' and \ cond3 == 'val3' and cond4 == 'val4': do_something This at least gives you some differentiation. Or even: if cond1 == 'val1' and cond2 == 'val2' and \ cond3 == 'val3' and \ cond4 == 'val4': do_something I think I prefer: if cond1 == 'val1' and \ cond2 == 'val2' and \ cond3 == 'val3' and \ cond4 == 'val4': do_something Here's the Style Guide , which (since 2010) recommends using brackets.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/181530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ] }
181,543
There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. What am I missing? What is the problem with reduce()?
As Guido says in his The fate of reduce() in Python 3000 post: So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly. There is an excellent example of a confusing reduce in the Functional Programming HOWTO article: Quick, what's the following code doing? total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1] You can figure it out, but it takes time to disentangle the expression to figure out what's going on. Using a short nested def statements makes things a little bit better: def combine (a, b): return 0, a[1] + b[1]total = reduce(combine, items)[1] But it would be best of all if I had simply used a for loop: total = 0for a, b in items: total += b Or the sum() built-in and a generator expression: total = sum(b for a,b in items) Many uses of reduce() are clearer when written as for loops.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/181543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24530/" ] }
181,596
How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel. Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc.
Here's how I do it: private string GetExcelColumnName(int columnNumber){ string columnName = ""; while (columnNumber > 0) { int modulo = (columnNumber - 1) % 26; columnName = Convert.ToChar('A' + modulo) + columnName; columnNumber = (columnNumber - modulo) / 26; } return columnName;}
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/181596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3851/" ] }
181,597
We are in the process of nutting out the design guidelines we would like to use in our development team and got into a discussion today around how ASP.NET controls should be named. I am talking about our good friends Label, TextBox, Button etc. We came up with the following three possibilities that we voted on: (Example is a TextBox to enter/display a FirstName) Add the control type as a postfix to your controls ID: [FirstName _ TextBox] or [FirstName _ tbx] Add the control type as a prefix to your controls ID [tbxFirstName] Set the ID of the control to FirstName and name related fields (like a label for the textbox or a validator) as in option 2 [lblTextBox]. We ended up deciding to use option 2. It's not as verbose as option 1 and I like that it specifies what control it is before the name of the control. My question is whether Microsoft has released any guidelines for these prefixes and or if you have any comments about our decision.
The reason Visual Studio adds "TextBox1" when you add it to the page is because Microsoft has no way of knowing how you intend to use it. Naming it "Control1" would be too confusing because it could be any number of controls. Microsoft provides guidance in general for OO naming conventions, but not specifically for naming UI controls. Since UI controls are ultimately variables used in code, they should follow the same convention as any other variable - no hungarian notation prefix. msdn.microsoft.com/en-us/library/xzf533w0(vs.71) msdn.microsoft.com/en-us/library/ms229002(VS.80) The main reasons are... Type of control may change from textbox to listbox, then all associated code will have to be fixed (noted earlier) Your code should be more concerned with the content of the control and less with what type of control it is. When you are concerned with the type of the control, you start to depend on certain functionalities and you break encapsulation - you should be able to easily swap controls without changing much or any code. (Basic OOP principle) It is fairly easy to come up with prefixes for the standard controls, but new controls are being developed every day. You may make your own WebUserControl, or you may purchase a set of third party controls. How will you decide which prefix to use for the custom controls? Instead of focusing on the type of control, your code should be concerned with what information is contained in it. Examples txtFirstName => firstName or FirstName txtState => state or State cboState => state or State (prime example of changing control types what about lstState or rdoState - they should all have the same name because your code is not concerned about the type of control,rather the state the user selected) ctlBilling => billingAddress or BillingAddress (custom control - with hungarian notation it is not very evident what the control even is, but with a meaningful name I begin to understand the information contained in it. i.e. billingAddress.Street, billingAddress.FullAddress etc.)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202/" ] }
181,613
This is the unabashed attempt of a similar C# question. So what are your favorite F# hidden (or not) features? Most of the features I've used so far aren't exactly hidden but have been quite refreshing. Like how trivial it is to overload operators compared to say C# or VB.NET. And Async<T> has helped me shave off some real ugly code. I'm quite new to the language still so it'd be great to learn what other features are being used in the wild.
User defined numeric literals can be defined by providing a module whose name starts with NumericLiteral and which defines certain methods ( FromZero , FromOne , etc.). In particular, you can use this to provide a much more readable syntax for calling LanguagePrimitives.GenericZero and LanguagePrimitives.GenericOne : module NumericLiteralG = begin let inline FromZero() = LanguagePrimitives.GenericZero let inline FromOne() = LanguagePrimitives.GenericOneendlet inline genericFactorial n = let rec fact n = if (n = 0G) then 1G else n * (fact (n - 1G)) fact nlet flt = genericFactorial 30.let bigI = genericFactorial 30I
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ] }
181,624
I'm working on a commercial (not open source) C++ project that runs on a linux-based system. I need to do some regex within the C++ code. (I know: I now have 2 problems.) QUESTION: What libraries do people who regularly do regex from C/C++ recommend I look into? A quick search has brought the following to my attention: 1) Boost.Regex (I need to go read the Boost Software License, but this question is not about software licenses) 2) C (not C++) POSIX regex (#include <regex.h>, regcomp, regexec, etc.) 3) http://freshmeat.net/projects/cpp_regex/ (I know nothing about this one; seems to be GPL, therefore not usable on this project)
Boost.Regex is very good and is slated to become part of the C++0x standard (it's already in TR1). Personally, I find Boost.Xpressive much nicer to work with. It is a header-only library and it has some nice features such as static regexes (regexes compiled at compile time). Update: If you're using a C++11 compliant compiler (gcc 4.8 is NOT!), use std::regex unless you have good reason to use something else.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13022/" ] }
181,630
I'm wondering if anyone can recommend a good C++ tree implementation, hopefully one that is stl compatible if at all possible. For the record, I've written tree algorithms many times before, and I know it can be fun, but I want to be pragmatic and lazy if at all possible. So an actual link to a working solution is the goal here. Note: I'm looking for a generic tree, not a balanced tree or a map/set, the structure itself and the connectivity of the tree is important in this case, not only the data within.So each branch needs to be able to hold arbitrary amounts of data, and each branch should be separately iterateable.
I don't know about your requirements, but wouldn't you be better off with a graph (implementations for example in Boost Graph ) if you're interested mostly in the structure and not so much in tree-specific benefits like speed through balancing? You can 'emulate' a tree through a graph, and maybe it'll be (conceptually) closer to what you're looking for.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ] }
181,652
Let's say I have this model named Product with a field named brand . Suppose the values of brand are stored in the format this_is_a_brand . Can I define a method in the model (or anywhere else) that allows me to modify the value of brand before it is called. For example, if I call @product.brand , I want to get This is a Brand , instead of this_is_a_brand .
I would recommend using the square bracket syntax ( [] and []= ) instead of read_attribute and write_attribute . The square bracket syntax is shorter and designed to wrap the protected read/write_attribute methods . def brand original = self[:brand] transform(original)enddef brand=(b) self[:brand] = reverse_transform(b)end
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9776/" ] }
181,693
Apparently ;-) the standard containers provide some form of guarantees. What type of guarantees and what exactly are the differences between the different types of container? Working from the SGI page (about STL ) I have come up with this: Container Types:================Container: Forward Container Reverse Container Random Access Container Sequence Front Insert Sequence Back Insert Sequence Associative Container Simple Associative Container Pair Associative Container Sorted Associative Container Multiple Associative ContainerContainer Types mapped to Standard Containers=============================================std::vector: Sequence Back Sequence Forward/Reverse/Random Containerstd::deque: Sequence Front/Back Sequence Forward/Reverse/Random Containerstd::list: Sequence Front/Back Sequence Forward/Reverse Containerstd::set: Sorted/Simple/Unique Associative Container Forward Containerstd::map: Sorted/Pair/Unique Associative Container Forward Containerstd::multiset: Sorted/Simple/Multiple Associative Container Forward Containerstd::multimap: Sorted/Pair/Multiple Associative Container Forward ContainerContainer Guarantees:===================== Simp or For Rev Rand Front Back Assoc Sort Mult Cont: Cont: Cont Cont: Sequ: Sequ: Sequ: Cont: Cont: Cont:Copy Const: O(n)Fill Const: O(n)begin() O(1)end() O(1)rbegin() O(1)rend() O(1)front() O(1)push_front() O(1)pop_front() O(1)push_back() O(1)pop_back() O(1)Insert() O(ln(n))Insert: fill O(n)Insert: range O(n) O(kln(n)+n)size() O(1)swap() O(1)erase key O(ln(n))erase element O(1)erase range O(ln(n)+S)count() O(log(n)+k)find() O(ln(n))equal range O(ln(n))Lower Bound/Upper Bound O(ln(n))Equality O(n)InEquality O(n)Element Access O(1)
I found the nice resource Standard C++ Containers . Probably this is what you all looking for. VECTOR Constructors vector<T> v; Make an empty vector. O(1)vector<T> v(n); Make a vector with N elements. O(n)vector<T> v(n, value); Make a vector with N elements, initialized to value. O(n)vector<T> v(begin, end); Make a vector and copy the elements from begin to end. O(n) Accessors v[i] Return (or set) the I'th element. O(1)v.at(i) Return (or set) the I'th element, with bounds checking. O(1)v.size() Return current number of elements. O(1)v.empty() Return true if vector is empty. O(1)v.begin() Return random access iterator to start. O(1)v.end() Return random access iterator to end. O(1)v.front() Return the first element. O(1)v.back() Return the last element. O(1)v.capacity() Return maximum number of elements. O(1) Modifiers v.push_back(value) Add value to end. O(1) (amortized)v.insert(iterator, value) Insert value at the position indexed by iterator. O(n)v.pop_back() Remove value from end. O(1)v.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n)v.erase(iterator) Erase value indexed by iterator. O(n)v.erase(begin, end) Erase the elements from begin to end. O(n) For other containers, refer to the page.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/181693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14065/" ] }
181,701
Has anyone used Mono, the open source .NET implementation on a large or medium sized project? I'm wondering if it's ready for real world, production environments. Is it stable, fast, compatible, ... enough to use? Does it take a lot of effort to port projects to the Mono runtime, or is it really, really compatible enough to just take of and run already written code for Microsoft's runtime?
I've used it for a number of internal and commercial projects with great success. My warnings: Write lots of unit tests and make sure they ALL pass under Mono -- this will save you a lot of trouble. Unless you absolutely have to, do NOT use their embedding API. It's damn easy to use, but it's ungodly easy to garbage collect valid memory or leak all of your memory. Don't ever, ever, ever even come close to SVN and unless there's no choice, do not compile your own. Things change so often in SVN that it's highly likely you'll end up implementing something that doesn't work on a release version if your project is significantly large. Don't try and figure out problems on your own for long, use the IRC channel. The people there are helpful and you'll save yourself days upon days -- don't make the same mistake I did. Good luck! Edit: The reason I say not to compile your own from source (release or SVN) is that it's easy to configure it differently than release binaries and hide bugs, for instance in the garbage collection. Edit 2: Forgot to answer the second part to your question. In my case, I had no issues with porting code, but I wasn't using any MS-specific libraries (WinForms, ASP.NET, etc). If you're only using System.* stuff, you'll be fine; beyond that, you may run into issues. Mono 2.0 is quite solid, though.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26053/" ] }
181,719
How do I start a process, such as launching a URL when the user clicks a button?
As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class... using System.Diagnostics;...Process.Start("process.exe"); The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish. using System.Diagnostics;...Process process = new Process();// Configure the process using the StartInfo properties.process.StartInfo.FileName = "process.exe";process.StartInfo.Arguments = "-n";process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;process.Start();process.WaitForExit();// Waits here for the process to exit. This method allows far more control than I've mentioned.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/181719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
181,745
Often when making changes to a VS2008 ASP.net project we get a message like: BC30560: 'mymodule_ascx' is ambiguous in the namespace 'ASP'. This goes away after a recompile or sometimes just waiting 10 seconds and refreshing the page. Any way to get rid of it?
I recently came across this problem and it was only happening on one server even though all were running the same code. I thoroughly investigated the problem to make sure there were no user controls with clashing names, temp files were cleared out, etc. The only thing that solved the problems (it seems permanently) is changing the batch attribute of the compilation element to false in the web.config, as suggested in the following link: http://personalinertia.blogspot.com/2007/06/there-bug-in-compiler.html <compilation debug="true" batch="false"> I firmly believe that this is in fact a bug in the compiler as suggested on that site.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23066/" ] }
181,780
I have an app where I would like to support device rotation in certain views but other don't particularly make sense in Landscape mode, so as I swapping the views out I would like to force the rotation to be set to portrait. There is an undocumented property setter on UIDevice that does the trick but obviously generates a compiler warning and could disappear with a future revision of the SDK. [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait]; Are there any documented ways to force the orientation? Update: I thought I would provide an example as I am not looking for shouldAutorotateToInterfaceOrientation as I have already implemented that. I want my app to support landscape and portrait in View 1 but only portrait in View 2. I have already implemented shouldAutorotateToInterfaceOrientation for all views but if the user is in landscape mode in View 1 and then switches to View 2, I want to force the phone to rotate back to Portrait.
This is long after the fact, but just in case anybody comes along who isn't using a navigation controller and/or doesn't wish to use undocumented methods: UIViewController *c = [[UIViewController alloc]init];[self presentModalViewController:c animated:NO];[self dismissModalViewControllerAnimated:NO];[c release]; It is sufficient to present and dismiss a vanilla view controller. Obviously you'll still need to confirm or deny the orientation in your override of shouldAutorotateToInterfaceOrientation. But this will cause shouldAutorotate... to be called again by the system.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/181780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4496/" ] }
181,805
What's the difference between absolute path & relative path when using any web server or Tomcat?
Absolute paths start with / and refer to a location from the root of the current site (or virtual host). Relative paths do not start with / and refer to a location from the actual location of the document the reference is made. Examples, assuming root is http://foo.com/site/ Absolute path, no matter where we are on the site /foo.html will refer to http://foo.com/site/foo.html Relative path, assuming the containing link is located in http://foo.com/site/part1/bar.html ../part2/quux.html will refer to http://foo.com/site/part2/quux.html or part2/blue.html will refer to http://foo.com/site/part1/part2/blue.html
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/181805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15177/" ] }
181,842
After discovering Clojure I have spent the last few days immersed in it. What project types lend themselves to Java over Clojure, vice versa, and in combination? What are examples of programs which you would have never attempted before Clojure?
Clojure lends itself well to concurrent programming . It provides such wonderful tools for dealing with threading as Software Transactional Memory and mutable references. As a demo for the Western Mass Developer's Group, Rich Hickey made an ant colony simulation in which each ant was its own thread and all of the variables were immutable. Even with a very large number of threads things worked great. This is not only because Rich is an amazing programmer, it's also because he didn't have to worry about locking while writing his code. You can check out his presentation on the ant colony here .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ] }
181,894
I'm testing the speed of some queries in MySQL. The database is caching these queries making it difficult for me to get reliable results when testing how fast these queries are. Is there a way to disable caching for a query? System: MySQL 4 on Linux webhosting, I have access to PHPMyAdmin. Thanks
Try using the SQL_NO_CACHE (MySQL 5.7) option in your query.(MySQL 5.6 users click HERE ) eg. SELECT SQL_NO_CACHE * FROM TABLE This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/181894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
181,901
I try to add an addons system to my Windows.Net application using Reflection; but it fails when there is addon with dependencie. Addon class have to implement an interface 'IAddon' and to have an empty constructor. Main program load the addon using Reflection: Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\Addon.dll");Type t = assembly.GetType("Test.MyAddon");ConstructorInfo ctor = t.GetConstructor(new Type[] { });IAddon addon= (IAddon) ctor.Invoke(new object[] { });addon.StartAddon(); It works great when addon do not use dependencie.But if my addon reference and use an another DLL (C:\Temp\TestAddon\MyTools.dll) that is saved near the addon in disk, it fails: System.IO.FileNotFoundException: Could not load file or assembly 'MyTools.dll' or one of its dependencies. I do not wants to copy the addons DLL near my executable, how can i do to tell .Net runtime to search in "C:\Temp\TestAddon\" for any dependency? Note that adding Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\MyTools.dll"); do not change anything.
If MyTools.dll is located in the same directory as Addon.dll , all you need to do is call Assembly.LoadFrom instead of Assembly.LoadFile to make your code work. Otherwise, handling the AppDomain.AssemblyResolve event is the way to go.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/181901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26071/" ] }
181,921
When working on a big C/C++ project, do you have some specific rules regarding the #include within source or header files? For instance, we can imagine to follow one of these two excessive rules: #include are forbidden in .h files; it is up to each .c file to include all the headers it needs Each .h file should include all its dependancies, i.e. it should be able to compile alone without any error. I suppose there is trade-off in between for any project, but what is yours? Do you have more specific rules? Or any link that argues for any of the solutions?
If you include H-files exclusively into C-files, then including a H-file into a C-file might cause compilation to fail. It might fail because you may have to include 20 other H-files upfront, and even worse, you have to include them in the right order. With a real lot of H-files, this system ends up to be an administrative nightmare in the long run. All you wanted to do was including one H-file and you ended up spending two hours to find out which other H-files in which order you will need to include as well. If a H-file can only be successfully included into a C-file in case another H-file is included first, then the first H-file should include the second one and so on. That way you can simply include every H-file into every C-file you like without having to fear that this may break compilation. That way you only specify your direct dependencies, yet if these dependencies themselves also have dependencies, its up to them to specify those. On the other hand, don't include H-files into H-files if that isn't necessary. hashtable.h should only include other header files that are required to use your hashtable implementation. If the implementation itself needs hashing.h , then include it in hashtable.c , not in hashtable.h , as only the implementation needs it, not the code that only would like to use the final hashtable.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26074/" ] }
181,956
How can I prevent a user from resizing GridViewColumns withing a ListView control?
i found a solution and probably it will help someone else someday ;) you have to override the GridViewColumnHeader's ControlTemplate (default template is here ) and remove the PART_HeaderGripper from the template in order to prevent resizing of your columns. there is another solution that comes up with subclassing GridViewColumn described here . for representation purposes i prefer xaml only solutions though
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/181956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20227/" ] }
181,990
I'm setting up an online ordering system but I'm in Australia and for international customers I'd like to show prices in US dollars or Euros so they don't have to make the mental effort to convert from Australian dollars. Does anyone know if I can pull up to date exchange rates off the net somewhere in an easy-to-parse format I can access from my PHP script ? UPDATE: I have now written a PHP class which implements this. You can get the code from my website .
You can get currency conversions in a simple format from yahoo: For example, to convert from GBP to EUR: http://download.finance.yahoo.com/d/quotes.csv?s=GBPEUR=X&f=sl1d1t1ba&e=.csv
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/181990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ] }
182,044
Can anyone give me an example of what the Artifact paths setting defined for a build configuration could look like if I want to create two artifacts dist and source where I am using the sln 2008 build runner and building my projects using the default bin/Release? **/Source/Code/MyProject/bin/Release/*.* => dist**/*.* => source I get two artifact roots dist and source but under dist I get the whole directory structure (Source/Code/MyProject/bin/Release) which I don't want and under source I get the whole thing along with obj and bin/Release which I do not want. Can you give some advice on how to do this correctly? Do I need to change the target location for all the projects I am building to be able to get this thing to work?
So you'll just need: Source\Code\MyProject\bin\Release\* => distSource\**\* => source This will put all the files in release into a artifact folder called dist and everything in Source into a artifact folder called source. If you have subfolders in Release try: Source\Code\MyProject\bin\Release\**\* => dist
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ] }
182,060
I have webservice which is passed an array of ints.I'd like to do the select statement as follows but keep getting errors. Do I need to change the array to a string? [WebMethod]public MiniEvent[] getAdminEvents(int buildingID, DateTime startDate){ command.CommandText = @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (@buildingIDs) AND startDateTime <= @fromDate"; SqlParameter buildID = new SqlParameter("@buildingIDs", buildingIDs);}
You can't (unfortunately) do that. A Sql Parameter can only be a single value, so you'd have to do: WHERE buildingID IN (@buildingID1, @buildingID2, @buildingID3...) Which, of course, requires you to know how many building ids there are, or to dynamically construct the query. As a workaround*, I've done the following: WHERE buildingID IN (@buildingID)command.CommandText = command.CommandText.Replace( "@buildingID", string.Join(buildingIDs.Select(b => b.ToString()), ",")); which will replace the text of the statement with the numbers, ending up as something like: WHERE buildingID IN (1,2,3,4) Note that this is getting close to a Sql injection vulnerability, but since it's an int array is safe. Arbitrary strings are not safe, but there's no way to embed Sql statements in an integer (or datetime, boolean, etc).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ] }
182,160
I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.
You need to define a Spring Bean which implements ApplicationListener . Then, in your code, do something like this: public void onApplicationEvent(ApplicationEvent appEvent){ if (appEvent instanceof AuthenticationSuccessEvent) { AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent; UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); // .... }} Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/182160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ] }
182,177
Which Template-Engine and Ajax-Framework/-Toolkit is able to load template information from JAR-Files?
You need to define a Spring Bean which implements ApplicationListener . Then, in your code, do something like this: public void onApplicationEvent(ApplicationEvent appEvent){ if (appEvent instanceof AuthenticationSuccessEvent) { AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent; UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); // .... }} Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/182177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
182,197
I have a log file being written by another process which I want to watch for changes. Each time a change occurs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the win32file.FindNextChangeNotification function but have no idea how to ask it to watch a specific file. If anyone's done anything like this I'd be really grateful to hear how... [Edit] I should have mentioned that I was after a solution that doesn't require polling. [Edit] Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.
Did you try using Watchdog ? Python API library and shell utilities to monitor file system events. Directory monitoring made easy with A cross-platform API. A shell tool to run commands in response to directory changes. Get started quickly with a simple example in Quickstart ...
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/182197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ] }
182,229
I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?
Import your settings module too import osos.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"from mysite.polls.models import Poll, Choice should do the trick.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15616/" ] }
182,253
I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me. I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths : filepath = r"c:\ttemp\FILEPA~1.EXE"print os.path.basename(filepath)'c:\\ttemp\\FILEPA~1.EXE']print os.path.splitdrive(filepath)('', 'c:\ttemp\\FILEPA~1.EXE') WTF ? It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE". Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.
If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux) >>> import ntpath>>> filepath = r"c:\ttemp\FILEPA~1.EXE">>> print ntpath.basename(filepath)FILEPA~1.EXE>>> print ntpath.splitdrive(filepath)('c:', '\\ttemp\\FILEPA~1.EXE')
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/182253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ] }
182,262
Using Oracle, if a column value can be 'YES' or 'NO' is it possible to constrain a table so that only one row can have a 'YES' value? I would rather redesign the table structure but this is not possible. [UDPATE] Sadly, null values are not allowed in this table.
Use a function-based index: create unique index only_one_yes on mytable(case when col='YES' then 'YES' end); Oracle only indexes keys that are not completely null, and the CASE expression here ensures that all the 'NO' values are changed to nulls and so not indexed.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26108/" ] }
182,278
I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?
Here is a small trick that I use in JAVA to replicate C++ friend mechanism. Lets say I have a class Romeo and another class Juliet . They are in different packages (family) for hatred reasons. Romeo wants to cuddle Juliet and Juliet wants to only let Romeo cuddle her. In C++, Juliet would declare Romeo as a (lover) friend but there are no such things in java. Here are the classes and the trick : Ladies first : package capulet;import montague.Romeo;public class Juliet { public static void cuddle(Romeo.Love love) { Objects.requireNonNull(love); System.out.println("O Romeo, Romeo, wherefore art thou Romeo?"); }} So the method Juliet.cuddle is public but you need a Romeo.Love to call it. It uses this Romeo.Love as a "signature security" to ensure that only Romeo can call this method and checks that the love is real so that the runtime will throw a NullPointerException if it is null . Now boys : package montague;import capulet.Juliet;public class Romeo { public static final class Love { private Love() {} } private static final Love love = new Love(); public static void cuddleJuliet() { Juliet.cuddle(love); }} The class Romeo.Love is public, but its constructor is private . Therefore anyone can see it, but only Romeo can construct it. I use a static reference so the Romeo.Love that is never used is only constructed once and does not impact optimization. Therefore, Romeo can cuddle Juliet and only he can because only he can construct and access a Romeo.Love instance, which is required by Juliet to cuddle her (or else she'll slap you with a NullPointerException ).
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/182278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ] }
182,287
Why can't I pass the table name to a prepared PDO statement? $stmt = $dbh->prepare('SELECT * FROM :table WHERE 1');if ($stmt->execute(array(':table' => 'users'))) { var_dump($stmt->fetchAll());} Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do $sql = "SELECT * FROM $table WHERE 1"
Table and Column names CANNOT be replaced by parameters in PDO. In that case you will simply want to filter and sanitize the data manually. One way to do this is to pass in shorthand parameters to the function that will execute the query dynamically and then use a switch() statement to create a white list of valid values to be used for the table name or column name. That way no user input ever goes directly into the query. So for example: function buildQuery( $get_var ) { switch($get_var) { case 1: $tbl = 'users'; break; } $sql = "SELECT * FROM $tbl";} By leaving no default case or using a default case that returns an error message you ensure that only values that you want used get used.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/182287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ] }
182,316
I've often heard criticism of the lack of thread safety in the Swing libraries. Yet, I am not sure as to what I would be doing in my own code with could cause issues: In what situations does the fact Swing is not thread safe come into play ? What should I actively avoid doing ?
Never do long running tasks in response to a button, event, etc as these are on the event thread. If you block the event thread, the ENTIRE GUI will be completely unresponsive resulting in REALLY pissed off users. This is why Swing seems slow and crusty. Use Threads, Executors, and SwingWorker to run tasks NOT ON THE EDT ( event dispatch thread). Do not update or create widgets outside of the EDT. Just about the only call you can do outside of the EDT is Component.repaint(). Use SwingUtilitis.invokeLater to ensure certain code executes on the EDT. Use EDT Debug Techniques and a smart look and feel (like Substance , which checks for EDT violation) If you follow these rules, Swing can make some very attractive and RESPONSIVE GUIs An example of some REALLY awesome Swing UI work: Palantir Technologies . Note: I DO NOT work for them, just an example of awesome swing. Shame no public demo... Their blog is good too, sparse, but good
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/182316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ] }
182,325
I just had a conversation with my lead developer who disagreed that unit tests are all that necessary or important. In his view, functional tests with a high enough code coverage should be enough since any inner refactorings (interface changes, etc.) will not lead to the tests being needed to be rewritten or looked over again. I tried explaining but didn't get very far, and thought you guys could do better. ;-) So... What are some good reasons to unit test code that functional tests don't offer? What dangers are there if all you have are functional tests? Edit #1 Thanks for all the great answers. I wanted to add that by functional tests I don't mean only tests on the entire product, but rather also tests on modules within the product, just not on the low level of a unit test with mocking if necessary, etc. Note also that our functional tests are automatic, and are continuously running, but they just take longer than unit tests (which is one of the big advantages of unit tests). I like the brick vs. house example. I guess what my lead developer is saying is testing the walls of the house is enough, you don't need to test the individual bricks... :-)
Off the top of my head Unit tests are repeatable without effort. Write once, run thousands of times, no human effort required, and much faster feedback than you get from a functional test Unit tests test small units, so immediately point to the correct "sector" in which the error occurs. Functional tests point out errors, but they can be caused by plenty of modules, even in co-operation. I'd hardly call an interface change "an inner refactoring". Interface changes tend to break a lot of code, and (in my opinion) force a new test loop rather than none.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ] }
182,393
In a few large projects i have been working on lately it seems to become increasingly important to choose one or the other (XML or Annotation). As projects grow, consistency is very important for maintainability. My questions are: what are the advantages of XML-based configuration over Annotation-based configuration and what are the advantages of Annotation-based configuration over XML-based configuration?
Annotations have their use, but they are not the one silver bullet to kill XML configuration. I recommend mixing the two! For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code's dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration. However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so. I haven't used JPA annotations, so I don't know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn't care where its information came from, it should just care what it can do with its information. But if you like JPA (I don't have any expirience with it), by all means, go for it. In general:If an annotation provides functionality and acts as a comment in and of itself, and doesn't tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won't change the main functionality of the code, and hence doesn't belong in the source files.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/182393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24390/" ] }
182,408
Is there a manual for cross-compiling a C++ application from Linux to Windows? Just that. I would like some information (links, reference, examples...) to guide me to do that. I don't even know if it's possible. My objective is to compile a program in Linux and get a .exe file that I can run under Windows.
The basics are not too difficult: sudo apt-get install mingw32 cat > main.c <<EOFint main(){ printf("Hello, World!");}EOFi586-mingw32msvc-cc main.c -o hello.exe Replace apt-get with yum , or whatever your Linux distro uses. That will generate a hello.exe for Windows. Once you get your head around that, you could use autotools , and set CC=i586-mingw32msvc-cc CC=i586-mingw32msvc-cc ./configure && make Or use CMake and a toolchain file to manage the build. More difficult still is adding native cross libraries. Usually they are stored in /usr/cross/i586-mingw32msvc/{include,lib} and you would need to add those paths in separately in the configure step of the build process.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/182408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366094/" ] }
182,410
I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be. But if I try to do a redirect or simply do an 'alert' on the link array element I get: function(){return JSON.encode(this);} As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck. After following some suggestions I've run eval('(' + jsonObject + ')') but it still returns the same output. So how's this done ?
var obj = jQuery.parseJSON('{"name":"John"}');alert( obj.name === "John" ); See the jQuery API .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20603/" ] }
182,436
Are there any tools available for validating a database schema against a set of design rules, naming conventions, etc. I'm not talking about comparing one database to another (as covered by this question ). I want to be able to say "What in this database doesn't meet this set of rules". Some examples of the type of rules I'm talking about would be like: - Primary key fields should be the first in the table. - Foreign keys should have an index on that field. - Field names ending 'xxx' should be of a certain type. - Fields with a constraint limiting it it certain values it should have a default. I've written a bunch of scripts to do this in the past and was wondering if there was something generic available. Ideally I'd like something for SQL Server, but if you're aware of something for other databases it may be useful to know about them too.
var obj = jQuery.parseJSON('{"name":"John"}');alert( obj.name === "John" ); See the jQuery API .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755/" ] }
182,440
This question is a follow-up from How to indicate that a method was unsuccessful . The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code. What is best: public int DoSomething(string a){ // might throw an exception}public bool TrySomething(string a, out result){ try { result = DoSomething(a) return true; } catch (Exception) { return false; } or public int DoSomething(string a){ int result; if (TrySomething(a, out result)) { return result; } else { throw Exception(); // which exception? }}public bool TrySomething(string a, out result){ //...} I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example?
Making TrySomething just catch and swallow the exception is a really bad idea. Half the point of the TryXXX pattern is to avoid the performance hit of exceptions. If you don't need much information in the exception, you could make the DoSomething method just call TrySomething and throw an exception if it fails. If you need details in the exception, you may need something more elaborate. I haven't timed where the bulk of the performance hit of exceptions is - if it's the throwing rather than the creating, you could write a private method which had a similar signature to TrySomething, but which returned an exception or null: public int DoSomething(string input){ int ret; Exception exception = DoSomethingImpl(input, out ret); if (exception != null) { // Note that you'll lose stack trace accuracy here throw exception; } return ret;}public bool TrySomething(string input, out int ret){ Exception exception = DoSomethingImpl(input, out ret); return exception == null;}private Exception DoSomethingImpl(string input, out int ret){ ret = 0; if (input != "bad") { ret = 5; return null; } else { return new ArgumentException("Some details"); }} Time this before you commit to it though!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5789/" ] }
182,455
How do I remove a trailing comma from a string in ColdFusion?
To remove a trailing comma (if it exists): REReplace(list, ",$", "") To strip one or more trailing commas: REReplace(list, ",+$", "")
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/182455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ] }
182,475
AFAIK, Currency type in Delphi Win32 depends on the processor floating point precision. Because of this I'm having rounding problems when comparing two Currency values, returning different results depending on the machine. For now I'm using the SameValue function passing a Epsilon parameter = 0.009, because I only need 2 decimal digits precision. Is there any better way to avoid this problem?
The Currency type in Delphi is a 64-bit integer scaled by 1/10,000; in other words, its smallest increment is equivalent to 0.0001. It is not susceptible to precision issues in the same way that floating point code is. However, if you are multiplying your Currency numbers by floating-point types, or dividing your Currency values, the rounding does need to be worked out one way or the other. The FPU controls this mechanism (it's called the "control word"). The Math unit contains some procedures which control this mechanism: SetRoundMode in particular. You can see the effects in this program: {$APPTYPE CONSOLE}uses Math;var x: Currency; y: Currency;begin SetRoundMode(rmTruncate); x := 1; x := x / 6; SetRoundMode(rmNearest); y := 1; y := y / 6; Writeln(x = y); // false Writeln(x - y); // 0.0001; i.e. 0.1666 vs 0.1667end. It is possible that a third-party library you are using is setting the control word to a different value. You may want to set the control word (i.e. rounding mode) explicitly at the starting point of your important calculations. Also, if your calculations ever transfer into plain floating point and then back into Currency, all bets are off - too hard to audit. Make sure all your calculations are in Currency.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089/" ] }
182,492
I would like TortoiseSVN (1.5.3) to ignore certain folders, their contents and certain other files wherever they might appear in my directory hierarchy but I cannot get the global ignore string right. Whatever I do, it either adds to much or ignores too much What is the correct 'Global ignore pattern' to ignore.... Folders : bin obj release compile Files : *.bak *.user *.suo Update: To help clarify... yes I am using this on windows.
Currently I have the following in my Global Ignore Pattern: bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db Works really well to ignore several hidden or temp files/folders.... So for your specific requirements: Folders: bin obj release compile Files: *.bak *.user *.suo I would use: bin obj release compile *.bak *.user *.suo
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/182492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ] }
182,497
Please give me the direction of the best guidance on the Entity Framework.
Currently I have the following in my Global Ignore Pattern: bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db Works really well to ignore several hidden or temp files/folders.... So for your specific requirements: Folders: bin obj release compile Files: *.bak *.user *.suo I would use: bin obj release compile *.bak *.user *.suo
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/182497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11135/" ] }
182,510
I have to produce an RSS/Atom feed in various applications, and I want to know a good library or class which is able to produce both, and which already handles all common problems. For example, the one I used for years does not put the right format for date, so my feed is not well-handled by several aggregators. Update: Why I am looking for a library? Because the one I used for years, which I had hacked a few times, has a little problem. Maybe a specification is not being correctly followed. Why does my RSS feed duplicate some entries?
The PHP Universal Feed Generator seems to be exactly what you're after - it has a simple, OO-based way of declaring a new feed and outputting it to your desired specification. It also has built-in date format conversions as one of it's features. Features: Generates RSS 1.0, RSS 2.0 and ATOM 1.0 feeds All feeds are are validated by feed validator. Implements appropriate namespaces for different versions. Automatically converts date formats. Generates UUID for ATOM feeds. Handles CDATA encoding for required tags. Supported versions: RSS 1.0 (which officially obsoleted RSS 0.90) RSS 2.0 (which officially obsoleted RSS 0.91, 0.92, 0.93 and 0.94) ATOM 1.0
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/182510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8404/" ] }
182,542
What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits. This is ASP.NET 1.1
Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception. You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed.If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception. You can use something like: <asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/182542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
182,571
We are developing a considerably big application using Ruby on Rails framework (CRM system) and are considering to rewrite it to use ExtJS so that Rails would just do the data handling, while ExtJS would do all the browser heavylifting in a desktop-like manner. Anyone has some experience and hints about what would be the best approach? Is ExtJS mature enough to be used in relatively big (and complex) applications? And what about the Rails part - what would be the best approach here? EDIT: Just to make it clear. I would prefer to do it in such a way that all the javascript client side application code is loaded at once (at the start up of the application, optimally as one compressed js file) and then just use ajax to send data to and from Rails app. Also, it would be nice to have ERB available for dynamic generation of the Ext apliccation elements.
I currently have an extremely large, desktop style app written in ExtJS. It used to run on top of Perl's Catalyst MVC framework, but once the entire View layer was converted to an ExtJS based desktop I started migrating to Ruby on Rails models and controllers. It is equally as fast, if not faster, and easier to maintain and has a much smaller code base. Make sure that you set your active record config to not include the root name of the model in the json, so that Ext's JsonStore has no problem reading the records. There is an option on ActiveRecord BASE called include_root_in_json you have to set to false. Make sure that you properly define your Application classes in Ext and maximize code re-use and you are going to want some sort of method to clean up unused nodes in the DOM. Javascript performance can be a real pain unless you are using the latest versions of Safari or Firefox 3.1. You probably will want some sort of caching method for data on the server to be served to your application in JSON format at the time the page is loaded. This will cut down on the number of round trips via Ajax. Definitely make use of Ext's WindowManager and StoreManager objects, or roll your own from Ext.util.MixedCollection Develop your code in separate, managable files, then have a build process which combines them into a single file, and then run YUI's compressor or Dean Edwards Packer on it to compress / obfuscate the file. Serve all JS and CSS in their own single files, including the Ext supplied ones.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/182571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26123/" ] }
182,600
If you had to iterate through a loop 7 times, would you use: for (int i = 0; i < 7; i++) or: for (int i = 0; i <= 6; i++) There are two considerations: performance readability For performance I'm assuming Java or C#. Does it matter if "less than" or "less than or equal to" is used? If you have insight for a different language, please indicate which. For readability I'm assuming 0-based arrays. UPD: My mention of 0-based arrays may have confused things. I'm not talking about iterating through array elements. Just a general loop. There is a good point below about using a constant to which would explain what this magic number is. So if I had " int NUMBER_OF_THINGS = 7 " then " i <= NUMBER_OF_THINGS - 1 " would look weird, wouldn't it.
The first is more idiomatic . In particular, it indicates (in a 0-based sense) the number of iterations. When using something 1-based (e.g. JDBC, IIRC) I might be tempted to use <=. So: for (int i=0; i < count; i++) // For 0-based APIsfor (int i=1; i <= count; i++) // For 1-based APIs I would expect the performance difference to be insignificantly small in real-world code.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/182600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533/" ] }
182,630
Syntax Shorthand for the ready-event by roosteronacid Line breaks and chainability by roosteronacid Nesting filters by Nathan Long Cache a collection and execute commands on the same line by roosteronacid Contains selector by roosteronacid Defining properties at element creation by roosteronacid Access jQuery functions as you would an array by roosteronacid The noConflict function - Freeing up the $ variable by Oli Isolate the $ variable in noConflict mode by nickf No-conflict mode by roosteronacid Data Storage The data function - bind data to elements by TenebrousX HTML5 data attributes support, on steroids! by roosteronacid The jQuery metadata plug-in by Filip Dupanović Optimization Optimize performance of complex selectors by roosteronacid The context parameter by lupefiasco Save and reuse searches by Nathan Long Creating an HTML Element and keeping a reference, Checking if an element exists, Writing your own selectors by Andreas Grech Miscellaneous Check the index of an element in a collection by redsquare Live event handlers by TM Replace anonymous functions with named functions by ken Microsoft AJAX framework and jQuery bridge by Slace jQuery tutorials by egyamado Remove elements from a collection and preserve chainability by roosteronacid Declare $this at the beginning of anonymous functions by Ben FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN by Colour Blend Judicious use of third-party jQuery scripts by harriyott The each function by Jan Zich Form Extensions plug-in by Chris S Asynchronous each function by OneNerd The jQuery template plug-in: implementing complex logic using render-functions by roosteronacid
Creating an HTML Element and keeping a reference var newDiv = $("<div />");newDiv.attr("id", "myNewDiv").appendTo("body");/* Now whenever I want to append the new div I created, I can just reference it from the "newDiv" variable */ Checking if an element exists if ($("#someDiv").length){ // It exists...} Writing your own selectors $.extend($.expr[":"], { over100pixels: function (e) { return $(e).height() > 100; }});$(".box:over100pixels").click(function (){ alert("The element you clicked is over 100 pixels height");});
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/182630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20946/" ] }
182,635
I am trying to find all matches in a string that begins with | | . I have tried: if ($line =~ m/^\\\|\s\\\|/) which didn't work. Any ideas?
You are escaping the pipe one time too many, effectively escaping the backslash instead. print "YES!" if ($line =~ m/^\|\s\|/);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
182,636
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument. Example: public class MyGenericClass<T> { public void doSomething() { // Snip... // Call to a 3rd party lib T bean = (T)someObject.create(T.class); // Snip... }} Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T. My question is: does someone know a good alternative or workaround for this?
Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method : public class MyGenericClass<T> { private final Class<T> clazz; public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) { return new MyGenericClass<U>(clazz); } protected MyGenericClass(Class<T> clazz) { this.clazz = clazz; } public void doSomething() { T instance = clazz.newInstance(); }} It's ugly, but it works.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/182636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26066/" ] }
182,637
I am doing .net programming in addition to c and c++ development and want more flexibility on my home machine. I want to be able to have both Linux (probably Ubuntu) and Windows Vista on my home computer. Is there a way I can install both and on boot be prompted for which one to start? Is there a way to set Windows to default? I have seen this before in CS labs in undergrad. Also, I assume there would be no problem if I were to use Windows 32-bit along with Ubuntu 64-bit. Any advise?
The latest versions of Ubuntu include an installer called Wubi , which installs Ubuntu as a windows application (ie: it can be uninstalled from Add/Remove programs) and sets up the dual boot for you! It's great for those who want to give Linux a try without a system overhaul!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/182637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12182/" ] }
182,641
I have fname and lname in my database, and a name could be stored as JOHN DOE or john DOE or JoHN dOE, but ultimately I want to display it as John Doe fname being John and lname being Doe
seeing it is tagged PHP: either string ucfirst ( string $str ); to uppercase first letter of the first word or string ucwords ( string $str ); to uppercase the first letter of every word you might want to use those in combination with string strtolower ( string $str ); to normalize all names to lower case first.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ] }
182,742
Specifically MSSQL 2005.
Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005. select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) ); To understand how it works we have to look at the dateadd() and datediff() functions. DATEADD(datepart, number, date) DATEDIFF(datepart, startdate, enddate) If you run just the most inner call to datediff(), you get the current month number since timestamp 0. select datediff(m, 0, getdate() ); 1327 The next part adds that number of months plus 1 to the 0 timestamp, giving you the starting point of the next calendar month. select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );2010-09-01 00:00:00.000 Finally, the outer dateadd() just subtracts one second from the beginning timestamp of next month, giving you the last second of the current month. select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );2010-08-31 23:59:59.000 This old answer (below) has a bug where it doesn't work on the last day of a month that has more days than the next month. I'm leaving it here as a warning to others. Add one month to the current date, and then subtract the value returned by the DAY function applied to the current date using the functions DAY and DATEADD. dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/182742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7577/" ] }
182,750
Suppose some Windows service uses code that wants mapped network drives and no UNC paths. How can I make the drive mapping available to the service's session when the service is started? Logging in as the service user and creating a persistent mapping will not establish the mapping in the context of the actual service.
Use this at your own risk. (I have tested it on XP and Server 2008 x64 R2) For this hack you will need SysinternalsSuite by Mark Russinovich : Step one: Open an elevated cmd.exe prompt (Run as administrator) Step two: Elevate again to root using PSExec.exe:Navigate to the folder containing SysinternalsSuite and execute the following command psexec -i -s cmd.exe you are now inside of a prompt that is nt authority\system and you can prove this by typing whoami . The -i is needed because drive mappings need to interact with the user Step Three: Create the persistent mapped drive as the SYSTEM account with the following command net use z: \\servername\sharedfolder /persistent:yes It's that easy! WARNING : You can only remove this mapping the same way you created it, from the SYSTEM account. If you need to remove it, follow steps 1 and 2 but change the command on step 3 to net use z: /delete . NOTE : The newly created mapped drive will now appear for ALL users of this system but they will see it displayed as "Disconnected Network Drive (Z:)". Do not let the name fool you. It may claim to be disconnected but it will work for everyone. That's how you can tell this hack is not supported by M$.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/182750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23424/" ] }
182,875
Is there any free tool available for creating and editing PNG Images?
Paint.NET will create and edit PNGs with gusto. It's an excellent program in many respects. It's free as in beer and speech.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/182875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ] }
182,945
I've committed changes in numerous files to a SVN repository from Eclipse. I then go to website directory on the linux box where I want to update these changes from the repository to the directory there. I want to say "svn update project100" which will update the directories under "project100" with all my added and changed files, etc. HOWEVER, I don't want to necessarily update changes that I didn't make.So I thought I could say "svn status project100" but when I do this I get a totally different list of changes that will be made, none of mine are in the list, which is odd. Hence to be sure that only my changes are updated to the web directory, I am forced to navigate to every directory where I know there is a change that I made and explicitly update only those files, e.g. "svn update newfile1.php" etc. which is tedious. Can anyone shed any light on the standard working procedure here, namely how do I get an accurate list of all the changes that are about to be made before I execute the "svn update" command? I thought it was the "status" command.
Try: svn status --show-updates or (the same but shorter): svn status -u
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/182945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ] }
182,957
im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here? int value = *min_element(v2.begin(), v2.end());cout << "min value at position " << *find(v2.begin(), v2.end(), value);
min_element already gives you the iterator, no need to invoke find (additionally, it's inefficient because it's twice the work). Use distance or the - operator: cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/182957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8768/" ] }
182,976
I have parsed XML using both of the following two methods... Parsing the XmlDocument using the object model and XPath queries. XSL/T But I have never used... The Linq Xml object model that was new to .Net 3.5 Can anyone tell me the comparative efficiency between the three alternatives? I realise that the particular usage would be a factor, but I just want a rough idea. For example, is the Linq option massively slower than the others?
The absolute fastest way to query an XML document is the hardest: write a method that uses an XmlReader to process the input stream, and have it process nodes as it reads them. This is the way to combine parsing and querying into a single operation. (Simply using XPath doesn't do this; both XmlDocument and XPathDocument parse the document in their Load methods.) This is usually only a good idea if you're processing extremely large streams of XML data. All three methods you've describe perform similarly. XSLT has a lot of room to be the slowest of the lot, because it lets you combine the inefficiencies of XPath with the inefficiencies of template matching. XPath and LINQ queries both do essentially the same thing, which is linear searching through enumerable lists of XML nodes. I would expect LINQ to be marginally faster in practice because XPath is interpreted at runtime while LINQ is interpreted at compile-time. But in general, how you write your query is going to have a much greater impact on execution speed than what technology you use. The way to write fast queries against XML documents is the same whether you're using XPath or LINQ: formulate the query so that as few nodes as possible get visited during its execution. It doesn't matter which technology you use: a query that examines every node in the document is going to run a lot slower than one that examines only a small subset of them. Your ability to do that is more dependent on the structure of the XML than anything else: a document with a navigable hierarchy of elements is generally going to be a lot faster to query than one whose elements are all children of the document element. Edit: While I'm pretty sure I'm right that the absolute fastest way to query an XML is the hardest, the real fastest (and hardest) way doesn't use an XmlReader ; it uses a state machine that directly processes characters from a stream. Like parsing XML with regular expressions, this is ordinarily a terrible idea. But it does give you the option of exchanging features for speed. By deciding not to handle those pieces of XML that you don't need for your application (e.g. namespace resolution, expansion of character entities, etc.) you can build something that will seek through a stream of characters faster than an XmlReader would. I can think of applications where this is even not a bad idea, though there I can't think of many.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/182976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ] }
183,042
Is there a way to define a column (primary key) as a UUID in SQLAlchemy if using PostgreSQL (Postgres)?
The sqlalchemy postgres dialect supports UUID columns. This is easy (and the question is specifically postgres) -- I don't understand why the other answers are all so complicated. Here is an example: from sqlalchemy.dialects.postgresql import UUIDfrom flask_sqlalchemy import SQLAlchemyimport uuiddb = SQLAlchemy()class Foo(db.Model): id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) Be careful not to miss passing the callable uuid.uuid4 into the column definition, rather than calling the function itself with uuid.uuid4() . Otherwise, you will have the same scalar value for all instances of this class. More details here : A scalar, Python callable, or ColumnElement expression representing the default value for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/183042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ] }
183,091
I'm a big fan of Capistrano but I need to develop an automated deployment script for a Java-only shop. I've looked at Ant and Maven and they don't seem to be well geared towards remote administration the way Capistrano is - they seem much more focused on simply building and packaging applications. Is there a better tool out there?
I don't think there is a Capistrano-like application for Java Web Applications, but that shouldn't really keep you from using it (or alternatives like Fabric) to deploy your applications. As you've already said, Ant is more a replacement for GNU Make while Maven is primary a buildout/dependency-management application. Since Java Web Applications are thanks to the .war container less dependent on external libraries, you can (depending on your application server) make deploying an application as easy as running a simple HTTP PUT-request. But if you require additional steps, Fabric has worked very well for me so far and I assume that Capistrano also offers generic shell-command, put and get operations. So I wouldn't look for too long for an alternative if what you already have already works :-)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4061/" ] }
183,108
I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types. Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?
Virtual member functions are instantiated when a class template is instantiated, but non-virtual member functions are instantiated only if they are called. This is covered in [temp.inst] in the C++ standard (In C++11, this is §14.7.1/10. In C++14, it is §14.7.1/11, and in C++17 it is §17.7.1/9. Excerpt from C++17 below) An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, a static data member of a class template, or a substatement of a constexpr if statement (9.4.1), unless such instantiation is required Also note that it is possible to instantiate a class template even if some of the member functions are not instantiable for the given template parameters. For example: template <class T>class Xyzzy{public: void CallFoo() { t.foo(); } // Invoke T::foo() void CallBar() { t.bar(); } // Invoke T::bar()private: T t;};class FooBar{public: void foo() { ... } void bar() { ... }};class BarOnly{public: void bar() { ... }};int main(int argc, const char** argv){ Xyzzy<FooBar> foobar; // Xyzzy<FooBar> is instantiated Xyzzy<BarOnly> baronly; // Xyzzy<BarOnly> is instantiated foobar.CallFoo(); // Calls FooBar::foo() foobar.CallBar(); // Calls FooBar::bar() baronly.CallBar(); // Calls BarOnly::bar() return 0;} This is valid, even though Xyzzy::CallFoo() is not instantiable because there is no such thing as BarOnly::foo(). This feature is used often as a template metaprogramming tool. Note, however, that "instantiation" of a template does not directly correlate to how much object code gets generated. That will depend upon your compiler/linker implementation.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/183108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18721/" ] }
183,114
I have a folder that is my working copy. How do I remove all SVN functionality from this folder? There is a reason for me doing this, somehow my master folder that contains all my working copies of sites, has somehow been turned into a working copy itself, so I have a working copy within itself as such. So, is there an easy way of removing version control from a folder?
Just remove all ".svn" folders in it. That's it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/183114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ] }
183,115
I'm writing a shell script to do some web server configuration. I need to disable all currently active virtual hosts. a2dissite doesn't accept multiple arguments, so I can't do a2dissite `ls /etc/apache2/sites-enabled` Should I use find ? Is it safe to manually delete the symlinks in /etc/apache2/sites-enabled ?
Is your script Debian only? If so, you can safely delete all the symlinks in sites-enabled, that will work as long as all sites have been written correctly, in the sites-available directory. For example: find /etc/apache2/sites-enabled/ -type l -exec rm -i "{}" \; will protect you against someone who has actually written a file instead of a symlink in that directory. (remove the -i from rm for an automatic script, of course)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3757/" ] }
183,131
How do you decide if something goes in the view or the controller? Here are some specific examples: Zend_Captcha: Does the controller generate the captcha and pass it to the view or does the view generate it? Zend_Alc: Does the view decide if a segment of the view should be displayed to the user or do you have multiple views depending on available actions and the controller picks the right one for display? Zend_Session: Does the view keep track of who is viewing it based on the session data or is that parsed by the controller and presented to the view as a parameter of some kind? Are the rules or guidelines for what component (model, view, or controller) should do what written somewhere where I can view them? I didn't see that in the documentation on the Zend Framework site.
Generally speaking, this question can apply to any MVC framework. Here are the guidelines I use: Skinny controllers. If possible, have your controllers do little more than invoke business logic on your models and pass results to your views. Views do nothing but View Logic. Do anything related to interacting with the user visually, like generating captchas, hiding and showing links based on ACL. Don't calculate totals. Don't invoke logic on models. Don't do business logic. It is generally OK to read the session from your views to hide and show data/links. But don't rely on that for security: make your controllers secure too. Fat Models. Put as much business logic into your models as you can. That way, you can share them between controllers. If you find yourself in a controller iterating over elements of a model, resetting values based on certain rules, or otherwise doing complicated business logic, then you should try to find a way to get that logic into the model layer. Hope this helps.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
183,161
What's the best way to break from nested loops in Javascript? //Write the links to the page.for (var x = 0; x < Args.length; x++){ for (var Heading in Navigation.Headings) { for (var Item in Navigation.Headings[Heading]) { if (Args[x] == Navigation.Headings[Heading][Item].Name) { document.write("<a href=\"" + Navigation.Headings[Heading][Item].URL + "\">" + Navigation.Headings[Heading][Item].Name + "</a> : "); break; // <---HERE, I need to break out of two loops. } } }}
Just like Perl, loop1: for (var i in set1) {loop2: for (var j in set2) {loop3: for (var k in set3) { break loop2; // breaks out of loop3 and loop2 } } } as defined in EMCA-262 section 12.12. [MDN Docs] Unlike C, these labels can only be used for continue and break , as Javascript does not have goto .
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/183161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ] }
183,201
Oftentimes a developer will be faced with a choice between two possible ways to solve a problem -- one that is idiomatic and readable, and another that is less intuitive, but may perform better. For example, in C-based languages, there are two ways to multiply a number by 2: int SimpleMultiplyBy2(int x){ return x * 2; } and int FastMultiplyBy2(int x){ return x << 1;} The first version is simpler to pick up for both technical and non-technical readers, but the second one may perform better, since bit shifting is a simpler operation than multiplication. (For now, let's assume that the compiler's optimizer would not detect this and optimize it, though that is also a consideration). As a developer, which would be better as an initial attempt?
You missed one. First code for correctness, then for clarity (the two are often connected, of course!). Finally, and only if you have real empirical evidence that you actually need to, you can look at optimizing. Premature optimization really is evil. Optimization almost always costs you time, clarity, maintainability. You'd better be sure you're buying something worthwhile with that. Note that good algorithms almost always beat localized tuning. There is no reason you can't have code that is correct, clear, and fast. You'll be unreasonably lucky to get there starting off focusing on `fast' though.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/183201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1674/" ] }
183,214
I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function. function foo(id) { this.dom = document.getElementById(id); this.bar = 5; var self = this; this.dom.addEventListener("click", self.onclick, false);}foo.prototype = { onclick : function() { this.bar = 7; }}; Now when I create a new object (after the DOM has loaded, with a span#test) var x = new foo('test'); The 'this' inside the onclick function points to the span#test and not the foo object. How do I get a reference to my foo object inside the onclick function?
(extracted some explanation that was hidden in comments in other answer) The problem lies in the following line: this.dom.addEventListener("click", self.onclick, false); Here, you pass a function object to be used as callback. When the event trigger, the function is called but now it has no association with any object (this). The problem can be solved by wrapping the function (with it's object reference) in a closure as follows: this.dom.addEventListener( "click", function(event) {self.onclick(event)}, false); Since the variable self was assigned this when the closure was created, the closure function will remember the value of the self variable when it's called at a later time. An alternative way to solve this is to make an utility function (and avoid using variables for binding this ): function bind(scope, fn) { return function () { fn.apply(scope, arguments); };} The updated code would then look like: this.dom.addEventListener("click", bind(this, this.onclick), false); Function.prototype.bind is part of ECMAScript 5 and provides the same functionality. So you can do: this.dom.addEventListener("click", this.onclick.bind(this), false); For browsers which do not support ES5 yet, MDN provides the following shim : if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; }
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/183214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18146/" ] }
183,254
I'm making my way into web development and have seen the word postback thrown around. Coming from a non-web based background, what does a new web developer have to know about postbacks? (i.e. what are they and when do they arise?) Any more information you'd like to share to help a newbie in the web world be aware of postbacks would be most greatly appreciated.
The following is aimed at beginners to ASP.Net... When does it happen? A postback originates from the client browser. Usually one of the controls on the page will be manipulated by the user (a button clicked or dropdown changed, etc), and this control will initiate a postback. The state of this control, plus all other controls on the page,(known as the View State) is Posted Back to the web server. What happens? Most commonly the postback causes the web server to create an instance of the code behind class of the page that initiated the postback. This page object is then executed within the normal page lifecycle with a slight difference (see below). If you do not redirect the user specifically to another page somewhere during the page lifecycle, the final result of the postback will be the same page displayed to the user again, and then another postback could happen, and so on. Why does it happen? The web application is running on the web server. In order to process the user’s response, cause the application state to change, or move to a different page, you need to get some code to execute on the web server. The only way to achieve this is to collect up all the information that the user is currently working on and send it all back to the server. Some things for a beginner to note are... The state of the controls on the posting back page are available within the context. This will allow you to manipulate the page controls or redirect to another page based on the information there. Controls on a web form have events, and therefore event handlers, just like any other controls. The initialisation part of the page lifecycle will execute before the event handler of the control that caused the post back. Therefore the code in the page’s Init and Load event handler will execute before the code in the event handler for the button that the user clicked. The value of the “Page.IsPostBack” property will be set to “true” when the page is executing after a postback, and “false” otherwise. Technologies like Ajax and MVC have changed the way postbacks work.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/183254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ] }
183,292
Is it possible to specify a Java classpath that includes a JAR file contained within another JAR file?
If you're trying to create a single jar that contains your application and its required libraries, there are two ways (that I know of) to do that. The first is One-Jar , which uses a special classloader to allow the nesting of jars. The second is UberJar , (or Shade ), which explodes the included libraries and puts all the classes in the top-level jar. I should also mention that UberJar and Shade are plugins for Maven1 and Maven2 respectively. As mentioned below, you can also use the assembly plugin (which in reality is much more powerful, but much harder to properly configure).
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/183292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7648/" ] }
183,316
How do I go about the [HandleError] filter in asp.net MVC Preview 5? I set the customErrors in my Web.config file <customErrors mode="On" defaultRedirect="Error.aspx"> <error statusCode="403" redirect="NoAccess.htm"/> <error statusCode="404" redirect="FileNotFound.htm"/></customErrors> and put [HandleError] above my Controller Class like this: [HandleError]public class DSWebsiteController: Controller{ [snip] public ActionResult CrashTest() { throw new Exception("Oh Noes!"); }} Then I let my controllers inherit from this class and call CrashTest() on them.Visual studio halts at the error and after pressing f5 to continue, I get rerouted to Error.aspx?aspxerrorpath=/sxi.mvc/CrashTest (where sxi is the name of the used controller.Off course the path cannot be found and I get "Server Error in '/' Application." 404. This site was ported from preview 3 to 5.Everything runs (wasn't that much work to port) except the error handling.When I create a complete new project the error handling seems to work. Ideas? --Note-- Since this question has over 3K views now, I thought it would be beneficial to put in what I'm currently (ASP.NET MVC 1.0) using.In the mvc contrib project there is a brilliant attribute called "RescueAttribute"You should probably check it out too ;)
[HandleError] When you provide only the HandleError attribute to your class (or to your action method for that matter), then when an unhandled exception occurs MVC will look for a corresponding View named "Error" first in the Controller's View folder. If it can't find it there then it will proceed to look in the Shared View folder (which should have an Error.aspx file in it by default) [HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")][HandleError(ExceptionType = typeof(NullReferenceException), View = "LameErrorHandling")] You can also stack up additional attributes with specific information about the type of exception you are looking for. At that point, you can direct the Error to a specific view other than the default "Error" view. For more information, take a look at Scott Guthrie's blog post about it.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/183316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ] }
183,353
Passing an undimensioned array to the VB6's Ubound function will cause an error, so I want to check if it has been dimensioned yet before attempting to check its upper bound. How do I do this?
Note: the code has been updated, the original version can be found in the revision history (not that it is useful to find it). The updated code does not depend on the undocumented GetMem4 function and correctly handles arrays of all types. Note for VBA users: This code is for VB6 which never got an x64 update. If you intend to use this code for VBA, see https://stackoverflow.com/a/32539884/11683 for the VBA version. You will only need to take the CopyMemory declaration and the pArrPtr function, leaving the rest. I use this: Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _(ByRef Destination As Any, ByRef Source As Any, ByVal length As Long)Private Const VT_BYREF As Long = &H4000&' When declared in this way, the passed array is wrapped in a Variant/ByRef. It is not copied.' Returns *SAFEARRAY, not **SAFEARRAYPublic Function pArrPtr(ByRef arr As Variant) As Long 'VarType lies to you, hiding important differences. Manual VarType here. Dim vt As Integer CopyMemory ByVal VarPtr(vt), ByVal VarPtr(arr), Len(vt) If (vt And vbArray) <> vbArray Then Err.Raise 5, , "Variant must contain an array" End If 'see https://msdn.microsoft.com/en-us/library/windows/desktop/ms221627%28v=vs.85%29.aspx If (vt And VT_BYREF) = VT_BYREF Then 'By-ref variant array. Contains **pparray at offset 8 CopyMemory ByVal VarPtr(pArrPtr), ByVal VarPtr(arr) + 8, Len(pArrPtr) 'pArrPtr = arr->pparray; CopyMemory ByVal VarPtr(pArrPtr), ByVal pArrPtr, Len(pArrPtr) 'pArrPtr = *pArrPtr; Else 'Non-by-ref variant array. Contains *parray at offset 8 CopyMemory ByVal VarPtr(pArrPtr), ByVal VarPtr(arr) + 8, Len(pArrPtr) 'pArrPtr = arr->parray; End IfEnd FunctionPublic Function ArrayExists(ByRef arr As Variant) As Boolean ArrayExists = pArrPtr(arr) <> 0End Function Usage: ? ArrayExists(someArray) Your code seems to do the same (testing for SAFEARRAY** being NULL), but in a way which I would consider a compiler bug :)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ] }
183,367
Is it possible to unsubscribe an anonymous method from an event? If I subscribe to an event like this: void MyMethod(){ Console.WriteLine("I did it!");}MyEvent += MyMethod; I can un-subscribe like this: MyEvent -= MyMethod; But if I subscribe using an anonymous method: MyEvent += delegate(){Console.WriteLine("I did it!");}; is it possible to unsubscribe this anonymous method? If so, how?
Action myDelegate = delegate(){Console.WriteLine("I did it!");};MyEvent += myDelegate;// .... laterMyEvent -= myDelegate; Just keep a reference to the delegate around.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/183367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2610/" ] }
183,369
I'm looking for a XPath library to query over XML documents in FF, IE, Opera and Safari... and couldn't find one. Have you seen any?
Google has just released Wicked Good XPath - A rewrite of Cybozu Lab's famous JavaScript-XPath. Link: https://github.com/google/wicked-good-xpath The rewritten version is 40% smaller and about 30% faster than the original implementation.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26183/" ] }
183,377
Does Mono .NET support and compile C++ / CLI? If not, do you know if they have any plans of supporting it?
We don't have a compiler for C++/CLI, it would be a very large undertaking for a very small userbase. Consider also that the C++/CLI spec is inherently flawed and non-portable, so being able to compile it wouldn't help much in the general case. You can compile using the MS .NET compiler and run in mono with these restrictions: run with mono on any system if the C++/CLI app is pure managed (but then, why use such an ugly language and not C#?) run with mono on windows in the other cases (C++/CLI apps are in general non-portable and include native code, so they can run only on windows and are uninteresting for the major objective of mono which is to run managed programs on Linux) Note that MS itself will eventually drop C++/CLI, so don't invest too much on it and switch to C#.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/183377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
183,391
I have a project where I am taking some particularly ugly "live" HTML and forcing it into a formal XML DOM with the HTML Agility Pack. What I would like to be able to do is then query over this with Linq to XML so that I can scrape out the bits I need. I'm using the method described here to parse the HtmlDocument into an XDocument, but when trying to query over this I'm not sure how to handle namespaces. In one particular document the original HTML was actually poorly formatted XHTML with the following tag: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> When trying to query from this document it seems that the namespace attribute is preventing me from doing something like: var x = xDoc.Descendants("div");// returns null Apparently for those "div" tags only the LocalName is "div", but the proper tag name is the namespace plus "div". I have tried to do some research on the issue of XML namespaces and it seems that I can bypass the namespace by querying this way: var x = (from x in xDoc.Descendants() where x.Name.LocalName == "div" select x);// works However, this seems like a rather hacky solution and does not properly address the namespace issue. As I understand it a proper XML document can contain multiple namespaces and therefore the proper way to handle it should be to parse out the namespaces I'm querying under. Has anyone else ever had to do this? Am I just making it way to complicated? I know that I could avoid all this by just sticking with HtmlDocument and querying with XPath, but I would rather stick to what I know (Linq) if possible and I would also prefer to know that I am not setting myself up for further namespace-related issues down the road. What is the proper way to deal with namespaces in this situation?
Using LocalName should be okay. I wouldn't consider it a hack at all if you don't care what namespace it's in. If you know the namespace you want and you want to specify it, you can: var ns = "{http://www.w3.org/1999/xhtml}";var x = xDoc.Root.Descendants(ns + "div"); ( MSDN reference ) You can also get a list of all the namespaces used in the document: var namespaces = (from x in xDoc.Root.DescendantsAndSelf() select x.Name.Namespace).Distinct(); I suppose you could use that to do this but it's not really any less of a hack: var x = namespaces.SelectMany(ns=>xDoc.Root.Descendants(ns+"div"));
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24608/" ] }
183,406
How can I add a line break to text when it is being set as an attribute i.e.: <TextBlock Text="Stuff on line1 \n Stuff on line2" /> Breaking it out into the exploded format isn't an option for my particular situation. What I need is some way to emulate the following: <TextBlock> <TextBlock.Text> Stuff on line1 <LineBreak/> Stuff on line2 </TextBlock.Text><TextBlock/>
<TextBlock Text="Stuff on line1&#x0a;Stuff on line 2"/> You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" vbCrLf , then you can use &#x0d;&#x0a; By the way, note the syntax: It's the ampersand, a pound, the letter x , then the hex value of the character you want, and then finally a semi-colon. ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/183406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93/" ] }
183,462
I'm currently working with Groovy and Grails. While Groovy is pretty straight-forward since it's basically Java, I can't say I grok Grails. I read that Groovy is to Grails as Ruby is to Ruby on Rails, but what does that mean?
To address your confusion with the metaphor (though it has been answered in other words under your question): Groovy is to Grails as Ruby is to Ruby on Rails, but what does that mean? Grails was a web framework built on/with the Groovy programming language to do the same thing for Groovy that Rails (a web framework for Ruby) does for Ruby. What does it mean to be "on rails"? The answer to this comes down to the essence of these web frameworks. These web frameworks (Grails & Rails) are built on the premise of "convention over configuration", which means that using common conventions to develop web applications can lead to higher productivity and more maintainable applications (this is a gross generalization). And by defining a convention and sticking to that you will find that your applications are easy to generate and quick to get up and running. This is what it means to me to be "on rails", just like a train. When a new train route is developed there is no worry about reinventing the way the train will get from one place to another, it's been solved by a single convention for decades: rails. Just as the tracks on a train route constrain its path from two locations, convention-based web frameworks use conventions to the flexibility of application developers so that they can concentrate on what the essential business problem of their application. One key benefit of a convention for a web framework is that the web framework can now make assumptions on how certain layers of the application hook together. In Rails, one can usually assume that if one's database table has a plural name, the ActiveRecord class mapped to that table will have the corresponding singular name. Consequently, Rails code generators can consume the data-mapping information to generate data access code such as dynamic finders, migrations, lazy-loaded association traversals, etc. This data access code in a configuration-based framework is laborious to code by hand.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/183462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6833/" ] }
183,480
Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this?Thanks! def unique_filename(file_name):counter = 1file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1return file_name I really do require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.
One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated. To get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O_CREAT and os.O_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple): def unique_file(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while 1: try: fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW) return os.fdopen(fd), file_name except OSError: pass file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 [Edit] Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface): def unique_file(file_name): dirname, filename = os.path.split(file_name) prefix, suffix = os.path.splitext(filename) fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname) return os.fdopen(fd), filename>>> f, filename=unique_file('/home/some_dir/foo.txt')>>> print filename/home/some_dir/foo_z8f_2Z.txt The only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some_dir/foo.txt) first.You may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/183480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26196/" ] }
183,485
I need to convert the punycode NIATO-OTABD to nñiñatoñ . I found a text converter in JavaScript the other day, but the punycode conversion doesn't work if there's a dash in the middle. Any suggestion to fix the "dash" issue?
I took the time to create the punycode below. It it based on the C code in RFC 3492. To use it with domain names you have to remove/add xn-- from/to the input/output to/from decode/encode. The utf16-class is necessary to convert from JavaScripts internal character representation to unicode and back. There are also ToASCII and ToUnicode functions to make it easier to convert between puny-coded IDN and ASCII. //Javascript Punycode converter derived from example in RFC3492.//This implementation is created by [email protected] and released into public domainvar punycode = new function Punycode() { // This object converts to and from puny-code used in IDN // // punycode.ToASCII ( domain ) // // Returns a puny coded representation of "domain". // It only converts the part of the domain name that // has non ASCII characters. I.e. it dosent matter if // you call it with a domain that already is in ASCII. // // punycode.ToUnicode (domain) // // Converts a puny-coded domain name to unicode. // It only converts the puny-coded parts of the domain name. // I.e. it dosent matter if you call it on a string // that already has been converted to unicode. // // this.utf16 = { // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back. decode:function(input){ var output = [], i=0, len=input.length,value,extra; while (i < len) { value = input.charCodeAt(i++); if ((value & 0xF800) === 0xD800) { extra = input.charCodeAt(i++); if ( ((value & 0xFC00) !== 0xD800) || ((extra & 0xFC00) !== 0xDC00) ) { throw new RangeError("UTF-16(decode): Illegal UTF-16 sequence"); } value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000; } output.push(value); } return output; }, encode:function(input){ var output = [], i=0, len=input.length,value; while (i < len) { value = input[i++]; if ( (value & 0xF800) === 0xD800 ) { throw new RangeError("UTF-16(encode): Illegal UTF-16 value"); } if (value > 0xFFFF) { value -= 0x10000; output.push(String.fromCharCode(((value >>>10) & 0x3FF) | 0xD800)); value = 0xDC00 | (value & 0x3FF); } output.push(String.fromCharCode(value)); } return output.join(""); } } //Default parameters var initial_n = 0x80; var initial_bias = 72; var delimiter = "\x2D"; var base = 36; var damp = 700; var tmin=1; var tmax=26; var skew=38; var maxint = 0x7FFFFFFF; // decode_digit(cp) returns the numeric value of a basic code // point (for use in representing integers) in the range 0 to // base-1, or base if cp is does not represent a value. function decode_digit(cp) { return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base; } // encode_digit(d,flag) returns the basic code point whose value // (when used for representing integers) is d, which needs to be in // the range 0 to base-1. The lowercase form is used unless flag is // nonzero, in which case the uppercase form is used. The behavior // is undefined if flag is nonzero and digit d has no uppercase form. function encode_digit(d, flag) { return d + 22 + 75 * (d < 26) - ((flag != 0) << 5); // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 } //** Bias adaptation function ** function adapt(delta, numpoints, firsttime ) { var k; delta = firsttime ? Math.floor(delta / damp) : (delta >> 1); delta += Math.floor(delta / numpoints); for (k = 0; delta > (((base - tmin) * tmax) >> 1); k += base) { delta = Math.floor(delta / ( base - tmin )); } return Math.floor(k + (base - tmin + 1) * delta / (delta + skew)); } // encode_basic(bcp,flag) forces a basic code point to lowercase if flag is zero, // uppercase if flag is nonzero, and returns the resulting code point. // The code point is unchanged if it is caseless. // The behavior is undefined if bcp is not a basic code point. function encode_basic(bcp, flag) { bcp -= (bcp - 97 < 26) << 5; return bcp + ((!flag && (bcp - 65 < 26)) << 5); } // Main decode this.decode=function(input,preserveCase) { // Dont use utf16 var output=[]; var case_flags=[]; var input_length = input.length; var n, out, i, bias, basic, j, ic, oldi, w, k, digit, t, len; // Initialize the state: n = initial_n; i = 0; bias = initial_bias; // Handle the basic code points: Let basic be the number of input code // points before the last delimiter, or 0 if there is none, then // copy the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) basic = 0; for (j = 0; j < basic; ++j) { if(preserveCase) case_flags[output.length] = ( input.charCodeAt(j) -65 < 26); if ( input.charCodeAt(j) >= 0x80) { throw new RangeError("Illegal input >= 0x80"); } output.push( input.charCodeAt(j) ); } // Main decoding loop: Start just after the last delimiter if any // basic code points were copied; start at the beginning otherwise. for (ic = basic > 0 ? basic + 1 : 0; ic < input_length; ) { // ic is the index of the next character to be consumed, // Decode a generalized variable-length integer into delta, // which gets added to i. The overflow checking is easier // if we increase i as we go, then subtract off its starting // value at the end to obtain delta. for (oldi = i, w = 1, k = base; ; k += base) { if (ic >= input_length) { throw RangeError ("punycode_bad_input(1)"); } digit = decode_digit(input.charCodeAt(ic++)); if (digit >= base) { throw RangeError("punycode_bad_input(2)"); } if (digit > Math.floor((maxint - i) / w)) { throw RangeError ("punycode_overflow(1)"); } i += digit * w; t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias; if (digit < t) { break; } if (w > Math.floor(maxint / (base - t))) { throw RangeError("punycode_overflow(2)"); } w *= (base - t); } out = output.length + 1; bias = adapt(i - oldi, out, oldi === 0); // i was supposed to wrap around from out to 0, // incrementing n each time, so we'll fix that now: if ( Math.floor(i / out) > maxint - n) { throw RangeError("punycode_overflow(3)"); } n += Math.floor( i / out ) ; i %= out; // Insert n at position i of the output: // Case of last character determines uppercase flag: if (preserveCase) { case_flags.splice(i, 0, input.charCodeAt(ic -1) -65 < 26);} output.splice(i, 0, n); i++; } if (preserveCase) { for (i = 0, len = output.length; i < len; i++) { if (case_flags[i]) { output[i] = (String.fromCharCode(output[i]).toUpperCase()).charCodeAt(0); } } } return this.utf16.encode(output); }; //** Main encode function ** this.encode = function (input,preserveCase) { //** Bias adaptation function ** var n, delta, h, b, bias, j, m, q, k, t, ijv, case_flags; if (preserveCase) { // Preserve case, step1 of 2: Get a list of the unaltered string case_flags = this.utf16.decode(input); } // Converts the input in UTF-16 to Unicode input = this.utf16.decode(input.toLowerCase()); var input_length = input.length; // Cache the length if (preserveCase) { // Preserve case, step2 of 2: Modify the list to true/false for (j=0; j < input_length; j++) { case_flags[j] = input[j] != case_flags[j]; } } var output=[]; // Initialize the state: n = initial_n; delta = 0; bias = initial_bias; // Handle the basic code points: for (j = 0; j < input_length; ++j) { if ( input[j] < 0x80) { output.push( String.fromCharCode( case_flags ? encode_basic(input[j], case_flags[j]) : input[j] ) ); } } h = b = output.length; // h is the number of code points that have been handled, b is the // number of basic code points if (b > 0) output.push(delimiter); // Main encoding loop: // while (h < input_length) { // All non-basic code points < n have been // handled already. Find the next larger one: for (m = maxint, j = 0; j < input_length; ++j) { ijv = input[j]; if (ijv >= n && ijv < m) m = ijv; } // Increase delta enough to advance the decoder's // <n,i> state to <m,0>, but guard against overflow: if (m - n > Math.floor((maxint - delta) / (h + 1))) { throw RangeError("punycode_overflow (1)"); } delta += (m - n) * (h + 1); n = m; for (j = 0; j < input_length; ++j) { ijv = input[j]; if (ijv < n ) { if (++delta > maxint) return Error("punycode_overflow(2)"); } if (ijv == n) { // Represent delta as a generalized variable-length integer: for (q = delta, k = base; ; k += base) { t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias; if (q < t) break; output.push( String.fromCharCode(encode_digit(t + (q - t) % (base - t), 0)) ); q = Math.floor( (q - t) / (base - t) ); } output.push( String.fromCharCode(encode_digit(q, preserveCase && case_flags[j] ? 1:0 ))); bias = adapt(delta, h + 1, h == b); delta = 0; ++h; } } ++delta, ++n; } return output.join(""); } this.ToASCII = function ( domain ) { var domain_array = domain.split("."); var out = []; for (var i=0; i < domain_array.length; ++i) { var s = domain_array[i]; out.push( s.match(/[^A-Za-z0-9-]/) ? "xn--" + punycode.encode(s) : s ); } return out.join("."); } this.ToUnicode = function ( domain ) { var domain_array = domain.split("."); var out = []; for (var i=0; i < domain_array.length; ++i) { var s = domain_array[i]; out.push( s.match(/^xn--/) ? punycode.decode(s.slice(4)) : s ); } return out.join("."); }}();// Example of usage:domain.oninput = function() { var input = domain.value var ascii = punycode.ToASCII(input) var display = punycode.ToUnicode(ascii) domain_ascii.value = ascii domain_display.value = display} <p>Try with your own data</p><label> <div>Input domain</div> <div><input id="domain" type="text"></div></label><div>Ascii: <output id="domain_ascii"></div><div>Display: <output id="domain_display"></div> Licence: From RFC3492: Disclaimer and license Regarding this entire document or any portion of it (including the pseudocode and C code), the author makes no guarantees and is not responsible for any damage resulting from its use. The author grants irrevocable permission to anyone to use, modify, and distribute it in any way that does not diminish the rights of anyone else to use, modify, and distribute it, provided that redistributed derivative works do not contain misleading author or version information. Derivative works need not be licensed under similar terms. I put my work in this punycode and utf16 in the public domain. It would be nice to get an email telling me in what project you use it. The scope of the code Each TLD has rules for which code points are allowed. The scope of the code below is to encode and decode a string between punycode and the internal encoding used by javascript regardes of those rules.Depending on your use case, you may need to filter the string.For example, 0xFE0F: Variation Selector-16, an invisible code point that specifies that the previous character should be displayed with emoji presentation.If you search for "allowed code points in IDN" you should find several projects that can help you filter the string.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/183485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23520/" ] }
183,488
We are doing some performance tests on our website and we are getting the following error a lot: *** 'C:\inetpub\foo.plex' log message at: 2008/10/07 13:19:58DBD::ODBC::st execute failed: [Microsoft][SQL Native Client]String data, right truncation (SQL-22001) at C:\inetpub\foo.plex line 25. Line 25 is the following: SELECT DISTINCT top 20 ZIP_CODE, CITY, STATE FROM Zipcodes WHERE (ZIP_CODE like ?) OR (CITY like ?) ORDER BY ZIP_CODE And lastly, this is perl code. Any ideas? EDIT : the issue here was that I was searching in the zip file with the string "74523%" which is too long. I ended up just not adding the % if they give five digits.
Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODE s column width or the parameter supplied for CITY is larger (in length) than CITY s column width. It would be interesting to know the values supplied for the two ? placeholders.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/183488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ] }
183,496
I've recently come across this piece of JavaScript code: if (",>=,<=,<>,".indexOf("," + sCompOp + ",") != -1) I was intrigued, because to write this test I would have done: if (/(>=|<=|<>)/.test(sCompOp)) Is this just a stylistic difference, or does the author of the other code know something about optimization that I don't? Or perhaps there is a different good reason to do this, or to not use regexes...? It seems to me that using String.indexOf() for this is a little more difficult to read (but then, I'm quite comfortable with regular expressions), but are there instances where it might be "better" than writing an equivalent regex? By "better" that might be quicker or more efficient, (although obviously that depends on the browser's JavaScript engine), or some other reason I'm not aware of. Can anyone enlighten me?
I ran some tests. The first method is slightly faster, but not by enough to make any real difference even under heavy use... except when sCompOp could potentially be a very long string. Because the first method searches a fixed-length string, its execution time is very stable no matter how long sCompOp gets, while the second method will potentially iterate through the entire length of sCompOp . Also, the second method will potentially match invalid strings - "blah blah blah <= blah blah" satisfies the test... Given that you're likely doing the work of parsing out the operator elsewhere, i doubt either edge case would be a problem. But even if this were not the case, a small modification to the expression would resolve both issues: /^(>=|<=|<>)$/ Testing code: function Time(fn, iter){ var start = new Date(); for (var i=0; i<iter; ++i) fn(); var end = new Date(); console.log(fn.toString().replace(/[\r|\n]/g, ' '), "\n : " + (end-start));}function IndexMethod(op){ return (",>=,<=,<>,".indexOf("," + op + ",") != -1);}function RegexMethod(op){ return /(>=|<=|<>)/.test(op);}function timeTests(){ var loopCount = 50000; Time(function(){IndexMethod(">=");}, loopCount); Time(function(){IndexMethod("<=");}, loopCount); Time(function(){IndexMethod("<>");}, loopCount); Time(function(){IndexMethod("!!");}, loopCount); Time(function(){IndexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount); Time(function(){IndexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount); Time(function(){RegexMethod(">=");}, loopCount); Time(function(){RegexMethod("<=");}, loopCount); Time(function(){RegexMethod("<>");}, loopCount); Time(function(){RegexMethod("!!");}, loopCount); Time(function(){RegexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount); Time(function(){RegexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);}timeTests(); Tested in IE6, FF3, Chrome 0.2.149.30
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12559/" ] }
183,499
One of the things that always bugs me about using Readers and Streams in Java is that the close() method can throw an exception. Since it's a good idea to put the close method in a finally block, that necessitates a bit of an awkward situation. I usually use this construction: FileReader fr = new FileReader("SomeFile.txt");try { try { fr.read(); } finally { fr.close(); }} catch(Exception e) { // Do exception handling} But I've also seen this construction: FileReader fr = new FileReader("SomeFile.txt");try { fr.read() } catch (Exception e) { // Do exception handling} finally { try { fr.close(); } catch (Exception e) { // Do exception handling }} I prefer the first construction because there's only one catch block and it just seems more elegant. Is there a reason to actually prefer the second or an alternate construction? UPDATE: Would it make a difference if I pointed out that both read and close only throw IOExceptions? So it seems likely to me that, if read fails, close will fail for the same reason.
I'm afraid there's a big problem with the first example, which is that if an exception happens on or after the read, the finally block executes. So far so good. But what if the fr.close() then causes another exception to be thrown? This will "trump" the first exception (a bit like putting return in a finally block) and you will lose all information about what actually caused the problem to begin with. Your finally block should use: IOUtil.closeSilently(fr); where this utility method just does: public static void closeSilently(Closeable c) { try { c.close(); } catch (Exception e) {} }
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23669/" ] }
183,532
I would like to ask for some simple examples showing the uses of <div> and <span> . I've seen them both used to mark a section of a page with an id or class , but I'm interested in knowing if there are times when one is preferred over the other.
div is a block element span is an inline element . This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc. For example: <div>This a large main division, with <span>a small bit</span> of spanned text!</div> Note that it is illegal to place a block-level element within an inline element, so: <div>Some <span>text that <div>I want</div> to mark</span> up</div> ...is illegal. EDIT: As of HTML5, some block elements can be placed inside of some inline elements. See the MDN reference here for a pretty clear listing. The above is still illegal, as <span> only accepts phrasing content, and <div> is flow content. You asked for some concrete examples, so is one taken from my bowling website, BowlSK : <div id="header"> <div id="userbar"> Hi there, <span class="username">Chris Marasti-Georg</span> | <a href="/edit-profile.html">Profile</a> | <a href="https://www.bowlsk.com/_ah/logout?...">Sign out</a> </div> <h1><a href="/">Bowl<span class="sk">SK</span></a></h1></div> Ok, what's going on? At the top of my page, I have a logical section, the "header". Since this is a section, I use a div (with an appropriate id). Within that, I have a couple of sections: the user bar and the actual page title. The title uses the appropriate tag, h1 . The userbar, being a section, is wrapped in a div . Within that, the username is wrapped in a span , so that I can change the style. As you can see, I have also wrapped a span around 2 letters in the title - this allows me to change their color in my stylesheet. Also note that HTML5 includes a broad new set of elements that define common page structures, such as article, section, nav, etc. Section 4.4 of the HTML 5 working draft lists them and gives hints as to their usage. HTML5 is still a working spec, so nothing is "final" yet, but it is highly doubtful that any of these elements are going anywhere. There is a javascript hack that you will need to use if you want to style these elements in some older version of IE - You need to create one of each element using document.createElement before any of those elements are specified in your source. There are a bunch of libraries that will take care of this for you - a quick Google search turned up html5shiv .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/183532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3676/" ] }
183,589
I'm currently in the process of writing my first Windows Forms application. I've read a few C# books now so I've got a relatively good understanding of what language features C# has to deal with exceptions. They're all quite theoretical however so what I haven't got yet is a feel for how to translate the basic concepts into a good exception-handling model in my application. Would anyone like to share any pearls of wisdom on the subject? Post any common mistakes you've seen newbies like myself make, and any general advice on handling exceptions in a way that will my application more stable and robust. The main things I'm currently trying to work out are: When should I re-throw an exception? Should I try to have a central error-handling mechanism of some kind? Do handling exceptions which might be thrown have a performance hit compared with pre-emptively testing things like whether a file on disk exists? Should all executable code be enclosed in try-catch-finally blocks? Are there any times when an empty catch block might be acceptable? All advice gratefully received!
There is an excellent code CodeProject article here . Here are a couple of highlights: Plan for the worst* Check it early Don't trust external data The only reliable devices are: the video, the mouse and keyboard. Writes can fail, too Code Safely Don't throw new Exception() Don't put important exception information on the Message field Put a single catch (Exception ex) per thread Generic Exceptions caught should be published Log Exception.ToString(); never log only Exception.Message! Don't catch (Exception) more than once per thread Don't ever swallow exceptions Cleanup code should be put in finally blocks Use "using" everywhere Don't return special values on error conditions Don't use exceptions to indicate absence of a resource Don't use exception handling as means of returning information from a method Use exceptions for errors that should not be ignored Don't clear the stack trace when re-throwing an exception Avoid changing exceptions without adding semantic value Exceptions should be marked [Serializable] When in doubt, don't Assert, throw an Exception Each exception class should have at least the three original constructors Be careful when using the AppDomain.UnhandledException event Don't reinvent the wheel Don't use Unstructured Error Handling (VB.Net)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/183589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4019/" ] }
183,602
Why does Visual studio take so long to delete a file from the solution tree? The app freezes and sits there for what feels like an eternity. If I delete the file from the file system first, then delete it in the solution it happens instantly. Is there an option I can set somewhere to avoid this?
I've found that when there is a lot in my Recycle Bin (1000s of files), it takes longer to delete a file in Windows Explorer as well as Visual Studio.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12459/" ] }
183,606
In the Google C++ Style Guide , the section on Operator Overloading recommends against overloading any operators ("except in rare, special circumstances"). Specifically, it recommends: In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container. I'm a little fuzzy on what such a functor would look like, but my main question is, why would you want to write your own functors for this? Wouldn't defining operator< , and using the standard std::less<T> function, be simpler? Is there any advantage to using one over the other?
Except for the more fundamental types, the less-than operation isn't always trivial, and even equality may vary from situation to situation. Imagine the situation of an airline that wants to assign all passengers a boarding number. This number reflects the boarding order (of course). Now, what determines who comes before who? You might just take the order in which the customers registered – in that case, the less-than operation would compare the check-in times. You might also consider the price customers paid for their tickets – less-than would now compare ticket prices. … and so on. All in all, it's just not meaningful to define an operator < on the Passenger class although it may be required to have passengers in a sorted container. I think that's what Google warns against.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ] }
183,638
I have this code that performs an ajax call and loads the results into two duplicate divs every time a dropdown is changed. I want the results to be faded into the div, to give a more obvious indication that something has changed, as its so seamless its sometimes hard to notice the change! print("$('.ajaxdropdown').change(function(){ $.ajax({ type: "GET", url: "/includes/html/gsm-tariff.php", data: "c_name="+escape($(this).val()), success: function(html){ $("#charges-gsm").html(html); //i want to fade result into these 2 divs... $("#charges-gsm-faq").html(html); $("#charges-gsm-prices").html(html); } }); });"); I've tried appending the fadein method and a few other things, but no joy.
You'll have to hide() it before you can use fadeIn() . UPDATE: Here's how you'd do this by chaining: $("#charges-gsm-faq").hide().html(html).fadeIn();$("#charges-gsm-prices").hide().html(html).fadeIn();
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/183638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ] }
183,642
select distinct constraint_type from user_constraints;C-CPRU Seems P means primary key and R means foreign key, correct? What are U and C?
Code Description Acts On Level---------------------------------------------C Check on a table ColumnO Read Only on a view ObjectP Primary Key ObjectR Referential (Foreign Key) ColumnU Unique Key ColumnV Check Option on a view Object
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/183642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ] }
183,685
Does anyone know if there is a good equivalent to Java's Set collection in C#? I know that you can somewhat mimic a set using a Dictionary or a HashTable by populating but ignoring the values, but that's not a very elegant way.
If you're using .NET 3.5, you can use HashSet<T> . It's true that .NET doesn't cater for sets as well as Java does though. The Wintellect PowerCollections may help too.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/183685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ] }
183,686
Whenever I restore a backup of my database in SQL Server I am presented with the following error: Msg 3101, Level 16, State 1, Line 1Exclusive access could not be obtained because the database is in use.Msg 3013, Level 16, State 1, Line 1RESTORE DATABASE is terminating abnormally. Usually to get around this I just restart the server. This was fine when we were developing on our local instance on our development machines. But we have a few programmers that need to access the database, and the logistics of having everyone script their changes and drop them into Subversion was becoming a nightmare. Regardless our simple solution was to put it on a shared server in the office and backup the server occasionally in case someone screwed up the data. Well, I screwed up the data and needed to restore. Unfortunately, I have another co-worker in the office who is working on another project and is using the same database server for development. To be nice I'd like to restore without restarting the SQL Server and possibly disrupting his work. Is there a way to script in T-SQL to be able to take exclusive access or to drop all connections?
You can force the database offline and drop connections with: EXEC sp_dboption N'yourDatabase', N'offline', N'true' Or you can ALTER DATABASE [yourDatabase] SET OFFLINE WITHROLLBACK AFTER 60 SECONDS Rollback specifies if anything is executing. After that period they will be rolled back. So it provides some protection. Sorry I wasn't thinking/reading right. You could bing back online and backup. There was also a post on Stack Overflow on a T-SQL snippet for dropping all connections rather than binging offline first: Hidden Features of SQL Server
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/183686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648/" ] }
183,702
Something like var life= { users : { guys : function(){ this.SOMETHING.mameAndDestroy(this.girls); }, girls : function(){ this.SOMETHING.kiss(this.boys); }, }, mameAndDestroy : function(group){ }, kiss : function(group){ }}; this.SOMETHING is what I imagine the format is, but it might not be. What will step back up to the parent of an object?
JavaScript does not offer this functionality natively. And I doubt you could even create this type of functionality. For example: var Bobby = {name: "Bobby"};var Dad = {name: "Dad", children: [ Bobby ]};var Mom = {name: "Mom", children: [ Bobby ]}; Who does Bobby belong to?
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/183702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1825034/" ] }
183,742
Let's look at an example - books. A book can have 1..n authors. An author can have 1..m books. What is a good way to represent all of the authors of a book? I came up with an idea to create a Books table and an Authors table. The Authors table has a primary AuthorID key the author's name. The Books table has a primary Book ID and metadata about the book (title, publication date, so on). However, there needs to be a way to link the books to authors and authors to books. And this is where the problem is. Let's say we have three books by Bob. However, on one book, he wrote it as Bob, PhD. Another he wrote as Dr. Bob, and a third he wrote as Dr. Robert. I want to be able to identify the fact that these authors are, in reality, the same person but credited under different names. I also want to distinguish Bob from another Bob who wrote different books. Now let's also add in another part to an application, a Person table that keeps track of interesting people. And let's say that Bob is an interesting person. I want to not only say that the author of all three books is Bob, but that this interesting Bob is the same Bob as the author Bob. So what strategies exist for such potentially complicated mapping, while ensuring that the book authors are identified by the name on the cover?
Add another table called BookAuthors with columns for BookID, AuthorID, and NameUsed. A NULL value for NameUsed would mean to pull it from the Author's table instead. This is called an Intersection table.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/183742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }