source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
31,201 | I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this? | I just found this recently. Use OuterClassName.this . class Outer { void foo() { new Thread() { public void run() { Outer.this.bar(); } }.start(); } void bar() { System.out.println("BAR!"); }} Updated If you just want the object itself (instead of invoking members), then Outer.this is the way to go. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/31201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
]
} |
31,221 | I have a method that where I want to redirect the user back to a login page located at the root of my web application. I'm using the following code: Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString()); This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString()); but this code is on a master page, and can be executed from any folder level. How do I get around this issue? | I think you need to drop the "~/" and replace it with just "/", I believe / is the root STOP RIGHT THERE! :-) unless you want to hardcode your web app so that it can only be installed at the root of a web site. "~/" is the correct thing to use, but the reason that your original code didn't work as expected is that ResolveUrl (which is used internally by Redirect ) tries to first work out if the path you are passing it is an absolute URL (e.g. "** http://server/ **foo/bar.htm" as opposed to "foo/bar.htm") - but unfortunately it does this by simply looking for a colon character ':' in the URL you give it. But in this case it finds a colon in the URL you give in the ReturnPath query string value, which fools it - therefore your '~/' doesn't get resolved. The fix is that you should be URL-encoding the ReturnPath value which escapes the problematic ':' along with any other special characters. Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString())); Additionally, I recommend that you (or anyone) never use Uri.ToString - because it gives a human-readable, more "friendly" version of the URL - not a necessarily correct one (it unescapes things). Instead use Uri.AbsoluteUri - like so: Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.AbsoluteUri)); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226/"
]
} |
31,249 | Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code. How do I do this? I assume I need to find the resource somewhere. myTreeViewControl.ItemTemplate = ?? | If the template is defined in your <Window.Resources> section directly: myTreeViewControl.ItemTemplate = this.Resources["SomeTemplate"] as DataTemplate; If it's somewhere deep within your window, like in a <Grid.Resources> section or something, I think this'll work: myTreeViewControl.ItemTemplate = this.FindResource("SomeTemplate") as DataTemplate; And if it's elsewhere in your application, I think App.FindResource("SomeTemplate") will work. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
]
} |
31,320 | What is the best way to profile a controller action in Ruby on Rails. Currently I am using the brute-force method of throwing in puts Time.now calls between what I think will be a bottleneck. But that feels really, really dirty. There has got to be a better way. | I picked up this technique a while back and have found it quite handy. When it's in place, you can add ?profile=true to any URL that hits a controller. Your action will run as usual, but instead of delivering the rendered page to the browser, it'll send a detailed, nicely formatted ruby-prof page that shows where your action spent its time. First, add ruby-prof to your Gemfile, probably in the development group: group :development do gem "ruby-prof"end Then add an around filter to your ApplicationController: around_action :performance_profile if Rails.env == 'development'def performance_profile if params[:profile] && result = RubyProf.profile { yield } out = StringIO.new RubyProf::GraphHtmlPrinter.new(result).print out, :min_percent => 0 self.response_body = out.string else yield endend Reading the ruby-prof output is a bit of an art, but I'll leave that as an exercise. Additional note by ScottJShea: If you want to change the measurement type place this: RubyProf.measure_mode = RubyProf::GC_TIME #example Before the if in the profile method of the application controller. You can find a list of the available measurements at the ruby-prof page . As of this writing the memory and allocations data streams seem to be corrupted ( see defect ). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/757/"
]
} |
31,340 | I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python. | Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this: http://www.artima.com/weblogs/viewpost.jsp?thread=214235 http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/ From the last link an interesting quote: Let me explain what all that means. Threads run inside the same virtual machine, and hence run on the same physical machine. Processes can run on the same physical machine or in another physical machine. If you architect your application around threads, you’ve done nothing to access multiple machines. So, you can scale to as many cores are on the single machine (which will be quite a few over time), but to really reach web scales, you’ll need to solve the multiple machine problem anyway. If you want to use multi core, pyprocessing defines an process based API to do real parallelization. The PEP also includes some interesting benchmarks. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242853/"
]
} |
31,394 | I see many similar questions, however I want to find the Username of the currently logged in user using Java. Its probably something like: System.getProperty(current.user); But, I'm not quite sure. | You're actually really close. This is what you're looking for: System.getProperty("user.name") | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
} |
31,408 | I have been using Castle MonoRail for the last two years, but in a new job I am going to be the one to bring in ASP.NET MVC with me. I understand the basics of views, actions and the like. I just need a good sample for someone with MVC experience. Any good links besides Scott's Northwind traders sample? | CodeCampServer - Built with ASP.NET MVC, pretty light and small project. No cruft at all. @lomaxx - Just FYI, most of what Troy Goode wrote is now part of ASP.NET MVC as of Preview 4 . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
]
} |
31,424 | When creating a criteria in NHibernate I can use Restriction.In() or Restriction.InG() What is the difference between them? | InG is the generic equivalent of In (for collections) The signatures of the methods are as follows (only the ICollection In overload is shown): In(string propertyName, ICollection values) vs. InG<T>(string propertyName, ICollection<T> values) Looking at NHibernate's source code (trunk) it seems that they both copy the collection to an object array and use that going forward, so I don't think there is a performance difference between them. I personally just use the In one most of the time - its easier to read. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
31,446 | What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in the first place so they would essentially act as 'read only'? The reason why I want to do this is becuase I want to modify the data within the bean - with in my application only, but not ever have it persisted to the database. In my program, I eventually have to call flush() on the EntityManager, which would persist all changes from attached entities to the underyling database, but I want to exclude specific objects. | (may be too late to answer, but can be useful for others) I'm developing my first system with JPA right now. Unfortunately I'm faced with this problem when this system is almost complete. Simply put. Use Hibernate, or wait for JPA 2.0. In Hibernate, you can use 'session.evict(object)' to remove one object from session. In JPA 2.0, in draft right now , there is the 'EntityManager.detach(object)' method to detach one object from persistence context. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506/"
]
} |
31,462 | Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String? | I'm currently using this: String content = null;URLConnection connection = null;try { connection = new URL("http://www.google.com").openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); scanner.close();}catch ( Exception ex ) { ex.printStackTrace();}System.out.println(content); But not sure if there's a better way. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
]
} |
31,465 | When you get a badge or aren't logged in to stack overflow there's a groovy little notification bar at the top of the page that lets you know there's something going on. I know the SOflow team use JQuery, but I was wondering if anyone knew of an implementation of the same style of notification system in asp.net AJAX. On a side note, what's the "official" name for this style of notification bar? | I'm currently using this: String content = null;URLConnection connection = null;try { connection = new URL("http://www.google.com").openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); scanner.close();}catch ( Exception ex ) { ex.printStackTrace();}System.out.println(content); But not sure if there's a better way. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
31,480 | How stable is WPF not in terms of stability of a WPF program, but in terms of the 'stability' of the API itself. Let me explain: Microsoft is notorious for changing its whole methodology around with new technology. Like with the move from silverlight 1 to silverlight 2. With WPF, I know that MS changed a bunch of stuff with the release of the .NET service pack. I don't know how much they changed things around. So the bottom line is, in your opinion are they going to revamp the system again with the next release or do you think that it is stable enough now that they won't change the bulk of the system. I hate to have to unlearn stuff with every release. I hope that the question wasn't too long winded. | MS do have a history of "fire and movement" with regards to introducing new technology into their development stack, but they also have a strong history of maintaining support for the older stuff, and backwards-compatibility. WPF seems to be getting stuff added to it with each new release of the framework but the things you learn aren't being superceded or invalidated. The only breaking change I've seen in my own WPF applications with a new release of the framework was one recently in 3.5 SP1, and that was because we were unknowingly relying on a bug to get a certain behaviour from our code. We adjusted the XAML to be more correct and it started working fine. So yeah, I think WPF is pretty "stable" as a client-side development technology. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2976/"
]
} |
31,497 | What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required. | As stated in "Learning C# 3.0: Master the fundamentals of C# 3.0" General Scenario: When a head of state dies, the President of the United States typically does not have time to attend the funeralpersonally. Instead, he dispatches a delegate. Often this delegate isthe Vice President, but sometimes the VP is unavailable and thePresident must send someone else, such as the Secretary of State oreven the First Lady. He does not want to “hardwire” his delegatedauthority to a single person; he might delegate this responsibility toanyone who is able to execute the correct international protocol. The President defines in advance what responsibility will be delegated(attend the funeral), what parameters will be passed (condolences,kind words), and what value he hopes to get back (good will). He thenassigns a particular person to that delegated responsibility at“runtime” as the course of his presidency progresses. In programming Scenario: You are often faced with situations where you need to execute a particular action, but you don’t know inadvance which method, or even which object, you’ll want to call uponto execute it. For Example: A button might not know which object or objects need to be notified. Rather than wiring the button to a particularobject, you will connect the button to a delegate and then resolvethat delegate to a particular method when the program executes. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635/"
]
} |
31,498 | I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T) . When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1: T createDefault(){ if(typeof(T).IsValueType) { return default(T); } else { return Activator.CreateInstance<T>(); }} Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is: T createDefault(){ if(typeof(T).IsValueType || typeof(T).FullName == "System.String") { return default(T); } else { return Activator.CreateInstance<T>(); }} But this feels like a kludge. Is there a nicer way to handle the string case? | Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code: if (typeof(T) == typeof(String)) return (T)(object)String.Empty; | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/31498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67/"
]
} |
31,500 | If I have a query like: Select EmployeeId From Employee Where EmployeeTypeId IN (1,2,3) and I have an index on the EmployeeTypeId field, does SQL server still use that index? | Yeah, that's right. If your Employee table has 10,000 records, and only 5 records have EmployeeTypeId in (1,2,3), then it will most likely use the index to fetch the records. However, if it finds that 9,000 records have the EmployeeTypeId in (1,2,3), then it would most likely just do a table scan to get the corresponding EmployeeId s, as it's faster just to run through the whole table than to go to each branch of the index tree and look at the records individually. SQL Server does a lot of stuff to try and optimize how the queries run. However, sometimes it doesn't get the right answer. If you know that SQL Server isn't using the index, by looking at the execution plan in query analyzer, you can tell the query engine to use a specific index with the following change to your query. SELECT EmployeeId FROM Employee WITH (Index(Index_EmployeeTypeId )) WHERE EmployeeTypeId IN (1,2,3) Assuming the index you have on the EmployeeTypeId field is named Index_EmployeeTypeId . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
31,535 | I'm trying to fetch some HTML from various blogs and have noticed that different providers use the same tag in different ways. For example, here are two major providers that use the meta name generator tag differently: Blogger: <meta content='blogger' name='generator'/> (content first, name later and, yes, single quotes!) WordPress: <meta name="generator" content="WordPress.com" /> (name first, content later) Is there a way to extract the value of content for all cases (single/double quotes, first/last in the row)? P.S. Although I'm using Java, the answer would probably help more people if it where for regular expressions generally. | The answer is: don't use regular expressions . Seriously. Use a SGML parser, or an XML parser if you happen to know it's valid XML (probably almost never true). You will absolutely screw up and waste tons of time trying to get it right. Just use what's already available. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
]
} |
31,551 | Using SqlServer, and trying to update rows from within the same table. I want to use a table alias for readability.This is the way I am doing it at the moment: UPDATE ra SET ra.ItemValue = rb.ItemValueFROM dbo.Rates ra, dbo.Rates rbWHERE ra.ResourceID = rb.ResourceIDAND ra.PriceSched = 't8'AND rb.PriceSched = 't9' Are there easier / better ways? | UPDATE ra SET ra.ItemValue = rb.ItemValue FROM dbo.Rates ra INNER JOIN dbo.Rates rb ON ra.ResourceID = rb.ResourceIDWHERE ra.PriceSched = 't8' AND rb.PriceSched = 't9'; This might help in improving performance. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2027/"
]
} |
31,572 | I'm working on a .net solution that is run completely inside a single network. When users make a change to the system, I want to launch an announcement and have everyone else hear it and act accordingly. Is there a way that we can broadcast out messages like this (like UDP will let you do) while keeping guaranteed delivery (like TCP)? This is on a small network (30ish clients), if that would make a difference. | Almost all games have a need for the fast-reacting properties (and to a lesser extent, the connectionless properties) of UDP and the reliability of TCP. What they do is they build their own reliable protocol on top of UDP. This gives them the ability to just burst packets to whereever and optionally make them reliable, as well. The reliable packet system is usually a simple retry-until-acknowledged system simpler than TCP but there are protocols which go way beyond what TCP can offer. Your situation sounds very simple. You'll probably be able to make the cleanest solution yourself - just make every client send back an "I heard you" response and have the server keep trying until it gets it (or gives up). If you want something more, most custom protocol libraries are in C++, so I am not sure how much use they'll be to you. However, my knowledge here is a few years old - perhaps some protocols have been ported over by now. Hmm... RakNet and enet are two C/C++ libraries that come to mind. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259/"
]
} |
31,581 | I'm writing an app that will need to make use of Timer s, but potentially very many of them. How scalable is the System.Threading.Timer class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked into a single thread (or very small threadpool) that processes all the callbacks on behalf of a Timer , or does each Timer have its own thread? I guess another way to rephrase the question is: How is System.Threading.Timer implemented? | I say this in response to a lot of questions: Don't forget that the (managed) source code to the framework is available. You can use this tool to get it all: http://www.codeplex.com/NetMassDownloader Unfortunately, in this specific case, a lot of the implementation is in native code, so you don't get to look at it... They definitely use pool threads rather than a thread-per-timer, though. The standard way to implement a big collection of timers (which is how the kernel does it internally, and I would suspect is indirectly how your big collection of Timers ends up) is to maintain the list sorted by time-until-expiry - so the system only ever has to worry about checking the next timer which is going to expire, not the whole list. Roughly, this gives O(log n) for starting a timer and O(1) for processing running timers. Edit: Just been looking in Jeff Richter's book. He says (of Threading.Timer) that it uses a single thread for all Timer objects, this thread knows when the next timer (i.e. as above) is due and calls ThreadPool.QueueUserWorkItem for the callbacks as appropriate. This has the effect that if you don't finish servicing one callback on a timer before the next is due, that your callback will reenter on another pool thread. So in summary I doubt you'll see a big problem with having lots of timers, but you might suffer thread pool exhaustion if large numbers of them are firing at the same timer and/or their callbacks are slow-running. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
]
} |
31,584 | For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the Builder pattern in Effective Java that is kinda the same). Basically, all setter methods return the object itself so then you can use code like this: myClass .setInt(1) .setString("test") .setBoolean(true); Setters simply return this in the end: public MyClass setInt(int anInt) { // [snip] return this;} What is your opinion? What are the pros and cons? Does this have any impact on performance? Also referred to as the named parameter idiom in c++. | @pek Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return this . If you're interested in this topic, there is a bunch of links and a simple example on Alex Miller's Java 7 page . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
]
} |
31,627 | I've been programming for 10+ years now for the same employer and only source code control we've ever used is VSS. (Sorry - That's what they had when I started). There's only ever been a few of us; two right now and we usually work alone, so VSS has worked ok for us. So, I have two questions: 1) Should we switch to something else like subversion, git, TFS, etc what exactly and why (please)? 2) Am I beyond all hope and destined to eternal damnation because VSS has corrupted me (as Jeff says) ? Wow - thanks for all the great responses! It sounds like I should clearify a few things. We are a MS shop (Gold parntner) and we mostly do VB, ASP.NET, SQL Server, sharepoint & Biztalk work. I have CS degree so I've done x86 assembly C, C++ on DEC Unix and Slackware Linux in a "time out of mind" ... My concern with VSS is that now I'm working over a VPN a lot more and VSS's performance sux and I'm afraid that our 10+ y/o version 5 VSS database is going to get hoosed...There's the LAN service that's supposed to speed things up, but Ive never used it and I'm not sure it helps with corruption - has anyone used the VSS LAN service? (new with VSS 2005) | I'd probably go with Subversion, if I were you. I'm a total Git fanatic at this point, but Subversion certainly has some advantages: simplicity abundance of interoperable tools active and supportive community portable Has really nice Windows shell integration integrates with visual studio (I think - but surely through a third party) Git has many, many other advantages, but the above tend to be the ones people care about when asking general questions like the above. Edit : the company I now work for is using VisualSVN server, which is free. It makes setting up a Subversion repository on a Windows server stupid simple, and on the client we're using TortoiseSVN (for shell integration) and AnkhSVN for Visual Studio support. It's quite good, and should be fairly easy for even VSS users to pick up. Latter-day Edit : So....nearly eight years later, I would never recommend Subversion to anyone for any reason. I don't really recant, per se , because I think my advice was valid at the time. However, in 2016, Subversion retains almost none of the advantages it used to have over Git. The tooling for Git is superior to (and much more diverse) what it once was, and in particular, there's GitHub and other good Git hosting providers (BitBucket, Beanstalk, Visual Studio Online, just off the top of my head). Visual Studio now has Git support out-of-the-box, and it's actually pretty good. There are even PowerShell modules to give a more native Windows experience to denizens of the console. Git is even easier to set up and use than Subversion and doesn't require a server component. Git has become as ubiquitous as any single tool can be, and you really would only be cheating yourself to not use it (unless you just really want to use something not-Git). Don't misunderstand - this isn't me hating on Subversion, but rather me recognizing that it's a tool from another time, rather like a straight razor for shaving. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1433/"
]
} |
31,672 | I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code. I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google & two introductory level books. The code is rife with "performance enhancing improvements". Does anyone have any guides or practical advice for de -optimizing FORTRAN into CS 101 levels? Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase? | You kind of have to get a "feel" for what programmers had to do back in the day. The vast majority of the code I work with is older than I am and ran on machines that were "new" when my parents were in high school. Common FORTRAN-isms I deal with, that hurt readability are: Common blocks Implicit variables Two or three DO loops with shared CONTINUE statements GOTO's in place of DO loops Arithmetic IF statements Computed GOTO's Equivalence REAL/INTEGER/other in some common block Strategies for solving these involve: Get Spag / plusFORT , worth the money, it solves a lot of them automatically and Bug Free(tm) Move to Fortran 90 if at all possible, if not move to free-format Fortran 77 Add IMPLICIT NONE to each subroutine and then fix every compile error, time consuming but ultimately necessary, some programs can do this for you automatically (or you can script it) Moving all COMMON blocks to MODULEs, low hanging fruit, worth it Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks Convert computed GOTOs to SELECT CASE blocks Convert all DO loops to the newer F90 syntax myloop: do ii = 1, nloops ! do somethingenddo myloop Convert equivalenced common block members to either ALLOCATABLE memory allocated in a module, or to their true character routines if it is Hollerith being stored in a REAL If you had more specific questions as to how to accomplish some readability tasks, I can give advice. I have a code base of a few hundred thousand lines of Fortran which was written over the span of 40 years that I am in some way responsible for, so I've probably run across any "problems" you may have found. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390/"
]
} |
31,673 | Wifi support on Vista is fine, but Native Wifi on XP is half baked. NDIS 802.11 Wireless LAN Miniport Drivers only gets you part of the way there (e.g. network scanning). From what I've read (and tried), the 802.11 NDIS drivers on XP will not allow you to configure a wireless connection. You have to use the Native Wifi API in order to do this. (Please, correct me if I'm wrong here.) Applications like InSSIDer have helped me to understand the APIs, but InSSIDer is just a scanner and is not designed to configure Wifi networks. So, the question is: where can I find some code examples (C# or C++) that deal with the configuration of Wifi networks on XP -- e.g. profile creation and connection management? I should note that this is a XP Embedded application on a closed system where we can't use the built-in Wireless Zero Configuration (WZC). We have to build all Wifi management functionality into our .NET application. Yes, I've Googled myself blue. It seems that someone should have a solution to this problem, but I can't find it. That's why I'm asking here. Thanks. | You kind of have to get a "feel" for what programmers had to do back in the day. The vast majority of the code I work with is older than I am and ran on machines that were "new" when my parents were in high school. Common FORTRAN-isms I deal with, that hurt readability are: Common blocks Implicit variables Two or three DO loops with shared CONTINUE statements GOTO's in place of DO loops Arithmetic IF statements Computed GOTO's Equivalence REAL/INTEGER/other in some common block Strategies for solving these involve: Get Spag / plusFORT , worth the money, it solves a lot of them automatically and Bug Free(tm) Move to Fortran 90 if at all possible, if not move to free-format Fortran 77 Add IMPLICIT NONE to each subroutine and then fix every compile error, time consuming but ultimately necessary, some programs can do this for you automatically (or you can script it) Moving all COMMON blocks to MODULEs, low hanging fruit, worth it Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks Convert computed GOTOs to SELECT CASE blocks Convert all DO loops to the newer F90 syntax myloop: do ii = 1, nloops ! do somethingenddo myloop Convert equivalenced common block members to either ALLOCATABLE memory allocated in a module, or to their true character routines if it is Hollerith being stored in a REAL If you had more specific questions as to how to accomplish some readability tasks, I can give advice. I have a code base of a few hundred thousand lines of Fortran which was written over the span of 40 years that I am in some way responsible for, so I've probably run across any "problems" you may have found. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2514/"
]
} |
31,693 | I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that .NET has better implementations etc. etc. So, what are the main differences between C++, C#, Java in generics? Pros/cons of each? | I'll add my voice to the noise and take a stab at making things clear: C# Generics allow you to declare something like this. List<Person> foo = new List<Person>(); and then the compiler will prevent you from putting things that aren't Person into the list. Behind the scenes the C# compiler is just putting List<Person> into the .NET dll file, but at runtime the JIT compiler goes and builds a new set of code, as if you had written a special list class just for containing people - something like ListOfPerson . The benefit of this is that it makes it really fast. There's no casting or any other stuff, and because the dll contains the information that this is a List of Person , other code that looks at it later on using reflection can tell that it contains Person objects (so you get intellisense and so on). The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new List<something> , so you have to manually convert things back to plain old List to interoperate with them. This is not that big of a problem, because C# 2.0 binary code is not backwards compatible. The only time this will ever happen is if you're upgrading some old C# 1.0/1.1 code to C# 2.0 Java Generics allow you to declare something like this. ArrayList<Person> foo = new ArrayList<Person>(); On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't Person into the list. The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special ListOfPerson - it just uses the plain old ArrayList which has always been in Java. When you get things out of the array, the usual Person p = (Person)foo.get(1); casting-dance still has to be done. The compiler is saving you the key-presses, but the speed hit/casting is still incurred just like it always was. When people mention "Type Erasure" this is what they're talking about. The compiler inserts the casts for you, and then 'erases' the fact that it's meant to be a list of Person not just Object The benefit of this approach is that old code which doesn't understand generics doesn't have to care. It's still dealing with the same old ArrayList as it always has. This is more important in the java world because they wanted to support compiling code using Java 5 with generics, and having it run on old 1.4 or previous JVM's, which microsoft deliberately decided not to bother with. The downside is the speed hit I mentioned previously, and also because there is no ListOfPerson pseudo-class or anything like that going into the .class files, code that looks at it later on (with reflection, or if you pull it out of another collection where it's been converted into Object or so on) can't tell in any way that it's meant to be a list containing only Person and not just any other array list. C++ Templates allow you to declare something like this std::list<Person>* foo = new std::list<Person>(); It looks like C# and Java generics, and it will do what you think it should do, but behind the scenes different things are happening. It has the most in common with C# generics in that it builds special pseudo-classes rather than just throwing the type information away like java does, but it's a whole different kettle of fish. Both C# and Java produce output which is designed for virtual machines. If you write some code which has a Person class in it, in both cases some information about a Person class will go into the .dll or .class file, and the JVM/CLR will do stuff with this. C++ produces raw x86 binary code. Everything is not an object, and there's no underlying virtual machine which needs to know about a Person class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything. Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you. The most obvious example is adding things: In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example: string addNames<T>( T first, T second ) { return first.Name() + second.Name(); } That code won't compile in C# or Java, because it doesn't know that the type T actually provides a method called Name(). You have to tell it - in C# like this: interface IHasName{ string Name(); };string addNames<T>( T first, T second ) where T : IHasName { .... } And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different ( <T extends IHasName> ), but it suffers from the same problems. The 'classic' case for this problem is trying to write a function which does this string addNames<T>( T first, T second ) { return first + second; } You can't actually write this code because there are no ways to declare an interface with the + method in it. You fail. C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a .Name() function, it will compile. If they don't, it won't. Simple. So, there you have it :-) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/31693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
]
} |
31,701 | I have a mapping application that needs to draw a path, and then display icons on top of the path. I can't find a way to control the order of virtual earth layers, other than the order in which they are added. Does anyone know how to change the z index of Virtual Earth shape layers, or force a layer to the front? | I'll add my voice to the noise and take a stab at making things clear: C# Generics allow you to declare something like this. List<Person> foo = new List<Person>(); and then the compiler will prevent you from putting things that aren't Person into the list. Behind the scenes the C# compiler is just putting List<Person> into the .NET dll file, but at runtime the JIT compiler goes and builds a new set of code, as if you had written a special list class just for containing people - something like ListOfPerson . The benefit of this is that it makes it really fast. There's no casting or any other stuff, and because the dll contains the information that this is a List of Person , other code that looks at it later on using reflection can tell that it contains Person objects (so you get intellisense and so on). The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new List<something> , so you have to manually convert things back to plain old List to interoperate with them. This is not that big of a problem, because C# 2.0 binary code is not backwards compatible. The only time this will ever happen is if you're upgrading some old C# 1.0/1.1 code to C# 2.0 Java Generics allow you to declare something like this. ArrayList<Person> foo = new ArrayList<Person>(); On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't Person into the list. The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special ListOfPerson - it just uses the plain old ArrayList which has always been in Java. When you get things out of the array, the usual Person p = (Person)foo.get(1); casting-dance still has to be done. The compiler is saving you the key-presses, but the speed hit/casting is still incurred just like it always was. When people mention "Type Erasure" this is what they're talking about. The compiler inserts the casts for you, and then 'erases' the fact that it's meant to be a list of Person not just Object The benefit of this approach is that old code which doesn't understand generics doesn't have to care. It's still dealing with the same old ArrayList as it always has. This is more important in the java world because they wanted to support compiling code using Java 5 with generics, and having it run on old 1.4 or previous JVM's, which microsoft deliberately decided not to bother with. The downside is the speed hit I mentioned previously, and also because there is no ListOfPerson pseudo-class or anything like that going into the .class files, code that looks at it later on (with reflection, or if you pull it out of another collection where it's been converted into Object or so on) can't tell in any way that it's meant to be a list containing only Person and not just any other array list. C++ Templates allow you to declare something like this std::list<Person>* foo = new std::list<Person>(); It looks like C# and Java generics, and it will do what you think it should do, but behind the scenes different things are happening. It has the most in common with C# generics in that it builds special pseudo-classes rather than just throwing the type information away like java does, but it's a whole different kettle of fish. Both C# and Java produce output which is designed for virtual machines. If you write some code which has a Person class in it, in both cases some information about a Person class will go into the .dll or .class file, and the JVM/CLR will do stuff with this. C++ produces raw x86 binary code. Everything is not an object, and there's no underlying virtual machine which needs to know about a Person class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything. Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you. The most obvious example is adding things: In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example: string addNames<T>( T first, T second ) { return first.Name() + second.Name(); } That code won't compile in C# or Java, because it doesn't know that the type T actually provides a method called Name(). You have to tell it - in C# like this: interface IHasName{ string Name(); };string addNames<T>( T first, T second ) where T : IHasName { .... } And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different ( <T extends IHasName> ), but it suffers from the same problems. The 'classic' case for this problem is trying to write a function which does this string addNames<T>( T first, T second ) { return first + second; } You can't actually write this code because there are no ways to declare an interface with the + method in it. You fail. C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a .Name() function, it will compile. If they don't, it won't. Simple. So, there you have it :-) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/31701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2785/"
]
} |
31,708 | I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms). Simplified code: Dictionary<Guid, Record> dict = GetAllRecords();myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");myListView.DataBind(); I thought that would work but in fact it throws a System.InvalidOperationException : ListView with id 'myListView' must have a data source that either implements ICollection or can perform data source paging if AllowPaging is true. In order to get it working I have had to resort to the following: Dictionary<Guid, Record> dict = GetAllRecords();List<Record> searchResults = new List<Record>();var matches = dict.Values.Where(rec => rec.Name == "foo");foreach (Record rec in matches) searchResults.Add(rec);myListView.DataSource = searchResults;myListView.DataBind(); Is there a small gotcha in the first example to make it work? (Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate) | Try this: var matches = dict.Values.Where(rec => rec.Name == "foo").ToList(); Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202/"
]
} |
31,722 | I'm interested in seeing a good diff algorithm, possibly in Javascript, for rendering a side-by-side diff of two HTML pages. The idea would be that the diff would show the differences of the rendered HTML. To clarify, I want to be able to see the side-by-side diffs as rendered output. So if I delete a paragraph, the side by side view would know to space things correctly. @Josh exactly. Though maybe it would show the deleted text in red or something. The idea is that if I use a WYSIWYG editor for my HTML content, I don't want to have to switch to HTML to do diffs. I want to do it with two WYSIWYG editors side by side maybe. Or at least display diffs side-by-side in an end-user friendly matter. | There's another nice trick you can use to significantly improve the look of a rendered HTML diff. Although this doesn't fully solve the initial problem, it will make a significant difference in the appearance of your rendered HTML diffs. Side-by-side rendered HTML will make it very difficult for your diff to line up vertically. Vertical alignment is crucial for comparing side-by-side diffs. In order to improve the vertical alignment of a side-by-side diff, you can insert invisible HTML elements in each version of the diff at "checkpoints" where the diff should be vertically aligned. Then you can use a bit of client-side JavaScript to add vertical spacing around checkpoint until the sides line up vertically. Explained in a little more detail: If you want to use this technique, run your diff algorithm and insert a bunch of visibility:hidden <span> s or tiny <div> s wherever your side-by-side versions should match up, according to the diff. Then run JavaScript that finds each checkpoint (and its side-by-side neighbor) and adds vertical spacing to the checkpoint that is higher-up (shallower) on the page. Now your rendered HTML diff will be vertically aligned up to that checkpoint, and you can continue repairing vertical alignment down the rest of your side-by-side page. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/598/"
]
} |
31,818 | How can I find out which Service Pack is installed on my copy of SQL Server? | From TechNet: Determining which version and edition of SQL Server Database Engine is running -- SQL Server 2000/2005SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')-- SQL Server 6.5/7.0SELECT @@VERSION | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3353/"
]
} |
31,840 | Is it still worth to add the log4j library to a Java 5 project just to loglet's say some exceptions to a file with some nice rollover settings.Or will the standard util.logging facility do the job as well? What do you think? | I'd say you're probably fine with util.logging for the needs you describe. For a good decision tree, have a look at Log4j vs java.util.logging Question One :Do you anticipate a need for any of the clever handlers that Log4j has that JUL does not have, such as the SMTPHandler, NTEventLogHandler, or any of the very convenient FileHandlers? Question Two :Do you see yourself wanting to frequently switch the format of your logging output? Will you need an easy, flexible way to do so? In other words, do you need Log4j's PatternLayout? Question Three :Do you anticipate a definite need for the ability to change complex logging configurations in your applications, after they are compiled and deployed in a production environment? Does your configuration sound something like, "Severe messages from this class get sent via e-mail to the support guy; severe messages from a subset of classes get logged to a syslog deamon on our server; warning messages from another subset of classes get logged to a file on network drive A; and then all messages from everywhere get logged to a file on network drive B"? And do you see yourself tweaking it every couple of days? If you can answer yes to any of the above questions, go with Log4j. If you answer a definite no to all of them, JUL will be more than adequate and it's conveniently already included in the SDK. That said, pretty much every project these days seems to wind up including log4j, if only because some other library uses it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3360/"
]
} |
31,867 | While I've seen rare cases where private inheritance was needed, I've never encountered a case where protected inheritance is needed. Does someone have an example? | People here seem to mistake Protected class inheritance and Protected methods. FWIW, I've never seen anyone use protected class inheritance, and if I remember correctly I think Stroustrup even considered the "protected" level to be a mistake in c++. There's precious little you cannot do if you remove that protection level and only rely on public and private. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2638/"
]
} |
31,868 | What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes? Following the two initial answers... We definitely need to use the Web Service layer as we will be making these calls from remote client applications. The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method. There is additionally a web service to upload files, painful but works all the time. Are you referring to the “Copy” service? We have been successful with this service’s CopyIntoItems method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API? I have posted our code as a suggested answer. | Example of using the WSS "Copy" Web service to upload a document to a library... public static void UploadFile2007(string destinationUrl, byte[] fileData){ // List of desination Urls, Just one in this example. string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) }; // Empty Field Information. This can be populated but not for this example. SharePoint2007CopyService.FieldInformation information = new SharePoint2007CopyService.FieldInformation(); SharePoint2007CopyService.FieldInformation[] info = { information }; // To receive the result Xml. SharePoint2007CopyService.CopyResult[] result; // Create the Copy web service instance configured from the web.config file. SharePoint2007CopyService.CopySoapClient CopyService2007 = new CopySoapClient("CopySoap"); CopyService2007.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation; CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result); if (result[0].ErrorCode != SharePoint2007CopyService.CopyErrorCode.Success) { // ... }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3362/"
]
} |
31,870 | What is the best way to include an html entity in XSLT? <xsl:template match="/a/node"> <xsl:value-of select="."/> <xsl:text> </xsl:text></xsl:template> this one returns a XsltParseError | You can use CDATA section <xsl:text disable-output-escaping="yes"><![CDATA[ ]]></xsl:text> or you can describe   in local DTD: <!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp " "> ]> or just use   instead of | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/31870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
]
} |
31,871 | Ok, I have a strange exception thrown from my code that's been bothering me for ages. System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() MSDN isn't terribly helpful on this : http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it. The code runs in a separate background thread, the method starts : public virtual void Startup() { TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port)); serverSocket.Start(); then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically: while (( socket = serverSocket.AcceptTcpClient()) !=null) //Funny exception here { connectionHandler = new ConnectionHandler(socket, mappingStrategy); pool.AddJob(connectionHandler); } } From there, the pool has it's own threads that take care of each job in it's own thread, separately. My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? Well, I do think some other thread is closing the socket, but it's certainly not from my code. What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods? | Is it possible that the serverSocket is being closed from another thread? That will cause this exception. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/31871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
]
} |
31,875 | There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow? | I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway. If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/31875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3363/"
]
} |
31,924 | I have done Java and JSP programming in the past, but I am new to Java Server Faces and want to know if there's a set of best practices for JSF development. | Some tips:Understand the JSF request lifecycle and where your various pieces of code fit in it. Especially find out why your model values will not be updated if there are validation errors. Choose a tag library and then stick with it. Take your time to determine your needs and prototype different libraries. Mixing different taglibs may cause severe harm to your mental health. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
31,930 | I've developed my own delivery extension for Reporting Services 2005, to integrate this with our SaaS marketing solution. It takes the subscription, and takes a snapshot of the report with a custom set of parameters. It then renders the report, sends an e-mail with a link and the report attached as XLS. Everything works fine, until mail delivery... Here's my code for sending e-mail: public static List<string> SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort){ List<string> failedRecipients = new List<string>(); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To); emailMessage.Priority = data.Priority; emailMessage.Subject = data.Subject; emailMessage.IsBodyHtml = false; emailMessage.Body = data.Comment; if (reportStream != null) { Attachment reportAttachment = new Attachment(reportStream, reportName); emailMessage.Attachments.Add(reportAttachment); reportStream.Dispose(); } try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpException ex) { throw ex; } catch (Exception ex) { throw ex; } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients;} Values for SmtpServerHostname is localhost, and port is 25. I veryfied that I can actually send mail, by using Telnet. And it works. Here's the error message I get from SSRS: ReportingServicesService!notification!4!08/28/2008-11:26:17:: Notification 6ab32b8d-296e-47a2-8d96-09e81222985c completed. Success: False, Status: Exception Message: Failure sending mail. Stacktrace: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153, DeliveryExtension: My Delivery, Report: Clicks Development, Attempt 1ReportingServicesService!dbpolling!4!08/28/2008-11:26:17:: NotificationPolling finished processing item 6ab32b8d-296e-47a2-8d96-09e81222985c Could this have something to do with Trust/Code Access Security? My delivery extension is granted full trust in rssrvpolicy.config: <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Name="MyDelivery_CodeGroup" Description="Code group for MyDelivery extension"> <IMembershipCondition class="UrlMembershipCondition" version="1" Url="C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer\bin\MyDeliveryExtension.dll" /> </CodeGroup> Could trust be an issue here? Another theory: SQL Server and SSRS was installed in the security context of Local System. Am I right, or is this service account restricted access to any network resource? Even its own SMTP Server? I tried changing all SQL Server Services logons to Administrator - but still without any success. I also tried logging onto the SMTP server in my code, by proviiding: NetworkCredential("Administrator", "password") and also NetworkCredential("Administrator", "password", "MyRepServer") Can anyone help here, please? | Some tips:Understand the JSF request lifecycle and where your various pieces of code fit in it. Especially find out why your model values will not be updated if there are validation errors. Choose a tag library and then stick with it. Take your time to determine your needs and prototype different libraries. Mixing different taglibs may cause severe harm to your mental health. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/31930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2972/"
]
} |
31,931 | I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'. It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way. What's the simplest way of doing this? [Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.] | var d = new Date();d.setDate(d.getDate() - 1);console.log(d); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/31931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/916/"
]
} |
32,000 | I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace. I'm using SqlConnection for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google. | using (var conn = new SqlConnection(yourConnectionString)){ var cmd = new SqlCommand("insert into Foo values (@bar)", conn); cmd.Parameters.AddWithValue("@bar", 17); conn.Open(); cmd.ExecuteNonQuery();} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
]
} |
32,001 | I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal. If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds. E.g. the timer should be able to do something like: Timer timer = new Timer(); timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X)//At some point between 0 and 5000 ms... setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y). I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again. The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: timer.stop();timer = new Timer(8000, ActionListener);timer.start(); Is there an easier way?? | According to the Timer documentation, in Java 1.5 onwards, you should prefer the ScheduledThreadPoolExecutor instead. (You may like to create this executor using Executors .newSingleThreadScheduledExecutor() for ease of use; it creates something much like a Timer .) The cool thing is, when you schedule a task (by calling schedule() ), it returns a ScheduledFuture object. You can use this to cancel the scheduled task. You're then free to submit a new task with a different triggering time. ETA: The Timer documentation linked to doesn't say anything about ScheduledThreadPoolExecutor , however the OpenJDK version had this to say: Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer / TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable ). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
]
} |
32,003 | Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like: C:\> go homeD:\profiles\user\home\> go svn-project1D:\projects\project1\svn\branch\src\> I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is cdargs or shell bookmarks but I haven't found something on windows. Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution. | What you are looking for is called DOSKEY You can use the doskey command to create macros in the command interpreter. For example: doskey mcd=mkdir "$*"$Tpushd "$*" creates a new command "mcd" that creates a new directory and then changes to that directory (I prefer "pushd" to "cd" in this case because it lets me use "popd" later to go back to where I was before) The $* will be replaced with the remainder of the command line after the macro, and the $T is used to delimit the two different commands that I want to evaluate. If I typed: mcd foo/bar at the command line, it would be equivalent to: mkdir "foo/bar"&pushd "foo/bar" The next step is to create a file that contains a set of macros which you can then import by using the /macrofile switch. I have a file (c:\tools\doskey.macros) which defines the commands that I regularly use. Each macro should be specified on a line with the same syntax as above. But you don't want to have to manually import your macros every time you launch a new command interpreter, to make it happen automatically, just open up the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun and set the value to be doskey /macrofile "c:\tools\doskey.macro". Doing this will make sure that your macros are automatically predefined every time you start a new interpreter. Extra thoughts: - If you want to do other things in AutoRun (like set environment parameters), you can delimit the commands with the ampersand. Mine looks like: set root=c:\SomeDir&doskey /macrofile "c:\tools\doskey.macros" - If you prefer that your AutoRun settings be set per-user, you can use the HKCU node instead of HKLM. - You can also use doskey to control things like the size of the command history. - I like to end all of my navigation macros with \$* so that I can chain things together - Be careful to add quotes as appropriate in your macros if you want to be able to handle paths with spaces in them. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1462/"
]
} |
32,010 | Source RegexOptions.IgnoreCase is more expensive than I would have thought (eg, should be barely measurable) Assuming that this applies to PHP, Python, Perl, Ruby etc as well as C# (which is what I assume Jeff was using), how much of a slowdown is it and will I incur a similar penalty with /[a-zA-z]/ as I will with /[a-z]/i ? | Yes, [A-Za-z] will be much faster than setting the RegexOptions.IgnoreCase , largely because of Unicode strings. But it's also much more limiting -- [A-Za-z] does not match accented international characters, it's literally the A-Za-z ASCII set and nothing more. I don't know if you saw Tim Bray's answer to my message, but it's a good one: One of the trickiest issues in internationalized search is upper and lower case. This notion of case is limited to languages written in the Latin, Greek, and Cyrillic character sets. English-speakers naturally expect search to be case-insensitive if only because they’re lazy: if Nadia Jones wants to look herself up on Google she’ll probably just type in nadia jones and expect the system to take care of it. So it’s fairly common for search systems to “normalize” words by converting them all to lower- or upper-case, both for indexing and queries. The trouble is that the mapping between cases is not always as straightforward as it is in English. For example, the German lower-case character “ß” becomes “SS” when upper-cased, and good old capital “I” when down-cased in Turkish becomes the dotless “ı” (yes, they have “i”, its upper-case version is “İ”). I have read (but not verified first-hand) that the rules for upcasing accented characters such “é” are different in France and Québec. One of the results of all this is that software such as java.String.toLowerCase() tends to run astonishingly slow as it tries to work around all these corner-cases. http://www.tbray.org/ongoing/When/200x/2003/10/11/SearchI18n | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
32,034 | After reading the Head First Design Patterns book and using a number of other design patterns, I'm trying to understand the Observer pattern. Isn't this already implemented using Events in the .NET Framework? | Yes, it is. The observer pattern is also called the publish/subscribe pattern, which is exactly what events allow you to do. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
]
} |
32,041 | Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations. It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish. | Two recommendations. First: for real logging, use a modern logging package like log4j or java's own built in logging. Don't worry about performance so much, the logging level check is on the order of nanoseconds. (it's an integer comparison). And if you have more than a single log statement, guard the whole block: (log4j, for example:) if (logger.isDebugEnabled()) { // perform expensive operations // build string to log logger.debug("....");} This gives you the added ability control logging at runtime. Having to restart and run a debug build can be very inconvenient. Second: You may find assertions are more what you need. An assertion is a statement which evaluates to a boolean result, with an optional message: assert (sky.state != FALLING) : "The sky is falling!"; Whenever the assertion results in a false, the assertion fails and an AssertionError is thrown containing your message (this is an unchecked exception, intended to exit the application). The neat thing is, these are treated special by the JVM and can toggled at runtime down to the class level, using a VM parameter (no recompile needed). If not enabled, there is zero overhead. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772/"
]
} |
32,044 | I have a tree structure in memory that I would like to render in HTML using a Django template. class Node(): name = "node name" children = [] There will be some object root that is a Node , and children is a list of Node s. root will be passed in the content of the template. I have found this one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way? | I think the canonical answer is: "Don't". What you should probably do instead is unravel the thing in your view code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert <li> and </li> from that list, creating the recursive structure with "understanding" it.) I'm also pretty sure recursively including template files is really a wrong way to do it... | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154/"
]
} |
32,085 | In XLST how would you find out the length of a node-set? | <xsl:variable name="length" select="count(nodeset)"/> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
32,100 | What is the simplest SQL query to find the second largest integer value in a specific column? There are maybe duplicate values in the column. | SELECT MAX( col ) FROM table WHERE col < ( SELECT MAX( col ) FROM table ) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/32100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
32,149 | Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as "GEORGE BURDELL" or "george burdell" and turns it into "George Burdell" . I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as "O'REILLY" and turn it into "O'Reilly" , but I know that is tougher. I am mainly focused on the English language if that simplifies things. UPDATE: I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists). I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post. | Unless I've misunderstood your question I don't think you need to roll your own, the TextInfo class can do it for you. using System.Globalization;CultureInfo.InvariantCulture.TextInfo.ToTitleCase("GeOrGE bUrdEll") Will return "George Burdell. And you can use your own culture if there's some special rules involved. Update: Michael (in a comment to this answer) pointed out that this will not work if the input is all caps since the method will assume that it is an acronym. The naive workaround for this is to .ToLower() the text before submitting it to ToTitleCase. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3203/"
]
} |
32,151 | Is there a way to export a simple HTML page to Word (.doc format, not .docx) without having Microsoft Word installed? | If you have only simple HTML pages as you said, it can be opened with Word. Otherwise, there are some libraries which can do this, but I don't have experience with them. My last idea is that if you are using ASP.NET, try to add application/msword to the header and you can save it as a Word document (it won't be a real Word doc, only an HTML renamed to doc to be able to open). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
]
} |
32,168 | A question related to Regular cast vs. static_cast vs. dynamic_cast : What cast syntax style do you prefer in C++? C-style cast syntax: (int)foo C++-style cast syntax: static_cast<int>(foo) constructor syntax: int(foo) They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?). If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax. What do you think? | It's best practice never to use C-style casts for three main reasons: as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing the new casts are intentionally visually striking. Since casts often reveal a weakness in the code, it's argued that making casts visible in the code is a good thing. this is especially true if searching for casts with an automated tool. Finding C-style casts reliably is nearly impossible. As palm3D noted: I find C++-style cast syntax too verbose. This is intentional, for the reasons given above. The constructor syntax (official name: function-style cast) is semantically the same as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate: void f(auto_ptr<int> x);f(static_cast<auto_ptr<int> >(new int(5))); // GOODf(auto_ptr<int>(new int(5)); // BAD The static_cast here will actually call the auto_ptr constructor. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2686/"
]
} |
32,175 | I'm trying to install a .NET service I wrote. As recommended by MSDN, I'm using InstallUtil. But I have missed how I can set the default service user on the command-line or even in the service itself. Now, when InstallUtil is run, it will display a dialog asking the user for the credentials for a user. I'm trying to integrate the service installation into a larger install and need the service installation to remain silent. | I think I may have found it. In the service itself, the automatically created ServiceProcessInstaller component has a property "Account" which can be set to "LocalService", "LocalSystem", "NetworkService" or "User". It was defaulting to "User" which must have displayed the prompt. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
]
} |
32,243 | The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. Even though imagesavealpha is set, something isn't quite right. What's the best way to preserve the transparency in the resampled image? $uploadTempFile = $myField[ 'tmp_name' ]list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile );$srcImage = imagecreatefrompng( $uploadTempFile ); imagesavealpha( $targetImage, true );$targetImage = imagecreatetruecolor( 128, 128 );imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight );imagepng( $targetImage, 'out.png', 9 ); | imagealphablending( $targetImage, false );imagesavealpha( $targetImage, true ); did it for me. Thanks ceejayoz. note, the target image needs the alpha settings, not the source image. Edit:full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time. $uploadTempFile = $myField[ 'tmp_name' ]list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile );$srcImage = imagecreatefrompng( $uploadTempFile ); $targetImage = imagecreatetruecolor( 128, 128 ); imagealphablending( $targetImage, false );imagesavealpha( $targetImage, true );imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight );imagepng( $targetImage, 'out.png', 9 ); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/32243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
]
} |
32,260 | Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible to do it? | Be sure to use System.Net.Mail , not the deprecated System.Web.Mail . Doing SSL with System.Web.Mail is a gross mess of hacky extensions. using System.Net;using System.Net.Mail;var fromAddress = new MailAddress("[email protected]", "From Name");var toAddress = new MailAddress("[email protected]", "To Name");const string fromPassword = "fromPassword";const string subject = "Subject";const string body = "Body";var smtp = new SmtpClient{ Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword)};using (var message = new MailMessage(fromAddress, toAddress){ Subject = subject, Body = body}){ smtp.Send(message);} Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting. If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords , select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password. If it is disabled, then you have to turn on Less secure app access , which is not recommended! So better enable the 2-Step verification. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/32260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
]
} |
32,282 | How can I test the same regex against different regular expression engines? | The most powerful free online regexp testing tool is by far http://regex101.com/ - lets you select the RE engine (PCRE, JavaScript, Python), has a debugger, colorizes the matches, explains the regexp on the fly, can create permalinks to the regex playground. Other online tools: http://www.rexv.org/ - supports PHP and Perl PCRE, Posix, Python, JavaScript, and Node.js http://refiddle.com/ - Inspired by jsfiddle, but for regular expressions. Supports JavaScript, Ruby and .NET expressions. http://regexpal.com/ - powered by the XRegExp JavaScript library http://www.rubular.com/ - Ruby-based Perl Regex Tutor - uses PCRE Windows desktop tools: The Regex Coach - free Windows application RegexBuddy recommended by most, costs US$ 39.95 Jeff Atwood [wrote about regular expressions]( post:). Other tools recommended by SO users include: http://www.txt2re.com/ Online free tool to generate regular expressions for multiple language (@ palmsey another thread) The Added Bytes Regular Expressions Cheat Sheet (@ GateKiller another thread) http://regexhero.net/ - The Online .NET Regular Expression Tester. Not free. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820/"
]
} |
32,332 | This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ std::fstream classes don't take a std::string in their constructor or open methods. Everyone loves code examples so: #include <iostream>#include <fstream>#include <string>int main(){ std::string filename = "testfile"; std::ifstream fin; fin.open(filename.c_str()); // Works just fine. fin.close(); //fin.open(filename); // Error: no such method. //fin.close();} This gets me all the time when working with files. Surely the C++ library would use std::string wherever possible? | By taking a C string the C++03 std::fstream class reduced dependency on the std::string class. In C++11, however, the std::fstream class does allow passing a std::string for its constructor parameter. Now, you may wonder why isn't there a transparent conversion from a std:string to a C string, so a class that expects a C string could still take a std::string just like a class that expects a std::string can take a C string. The reason is that this would cause a conversion cycle, which in turn may lead to problems. For example, suppose std::string would be convertible to a C string so that you could use std::string s with fstream s. Suppose also that C string are convertible to std::string s as is the state in the current standard. Now, consider the following: void f(std::string str1, std::string str2);void f(char* cstr1, char* cstr2);void g(){ char* cstr = "abc"; std::string str = "def"; f(cstr, str); // ERROR: ambiguous} Because you can convert either way between a std::string and a C string the call to f() could resolve to either of the two f() alternatives, and is thus ambiguous. The solution is to break the conversion cycle by making one conversion direction explicit, which is what the STL chose to do with c_str() . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
]
} |
32,343 | Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3s. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had and spin up an encoding thread on each core. So, when I run the program on a quad core CPU, the program figures out it's a quad core CPU, figures out there are four cores to work with, then spawns four threads for the encoding, each of which is running on its own separate CPU. How would I do this? And would this be any different if the cores were spread out across multiple physical CPUs? As in, if I had a machine with two quad core CPUs on it, are there any special considerations or are the eight cores across the two dies considered equal in Windows? | Don't bother doing that. Instead use the Thread Pool . The thread pool is a mechanism (actually a class) of the framework that you can query for a new thread. When you ask for a new thread it will either give you a new one or enqueue the work until a thread get freed. In that way the framework is in charge on deciding wether it should create more threads or not depending on the number of present CPUs. Edit: In addition, as it has been already mentioned, the OS is in charge of distributing the threads among the different CPUs. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
]
} |
32,369 | One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy. Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site. Question : Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before. Any help is appreciated. | I'm not sure if it'll work in all browsers but you should try setting autocomplete="off" on the form. <form id="loginForm" action="login.cgi" method="post" autocomplete="off"> The easiest and simplest way to disable Form and Password storage prompts and prevent form data from being cached in session history is to use the autocomplete form element attribute with value "off". From https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion Some minor research shows that this works in IE to but I'll leave no guarantees ;) @Joseph : If it's a strict requirement to pass XHTML validation with the actual markup (don't know why it would be though) you could theoretically add this attribute with javascript afterwards but then users with js disabled (probably a neglectable amount of your userbase or zero if your site requires js) will still have their passwords saved. Example with jQuery: $('#loginForm').attr('autocomplete', 'off'); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/32369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3262/"
]
} |
32,397 | On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine. | My understanding is that it is approximately the following from another Jeff Atwood post t = (time of entry post) - (Dec 8, 2005)x = upvotes - downvotesy = {1 if x > 0, 0 if x = 0, -1 if x < 0)z = {1 if x < 1, otherwise x}log(z) + (y * t)/45000 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942/"
]
} |
32,404 | I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d? | Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions). This is a basic skeleton for a simple service: import win32serviceutilimport win32serviceimport win32eventimport servicemanagerimport socketclass AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): passif __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) Your code would go in the main() method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop method | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/32404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
} |
32,414 | We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a ctrl F5 refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time. Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome. As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change? | As far as I know a common solution is to add a ?<version> to the script's src link. For instance: <script type="text/javascript" src="myfile.js?1500"></script> I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags? You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance. It would look something like this: <script type="text/javascript" src="myfile.js?$$REVISION$$"></script> Of course, there are always better solutions like this one . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/32414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2176/"
]
} |
32,433 | This query works great: var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select op) .SingleOrDefault(); I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but select op, pg).SingleOrDefault(); doesn't work. How can I select everything from both tables so that they appear in my new pageObject type? | You can use anonymous types for this, i.e.: var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select new { pg, op }).SingleOrDefault(); This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:- var pageObject = (from op in db.ObjectPermissions join pg in db.Pages on op.ObjectPermissionName equals page.PageName where pg.PageID == page.PageID select new { PermissionName = pg, ObjectPermission = op }).SingleOrDefault(); This will enable you to say:- if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit(); For example :-) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/32433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
]
} |
32,458 | I have a coworker who writes unit tests for objects which fill their fields with random data. His reason is that it gives a wider range of testing, since it will test a lot of different values, whereas a normal test only uses a single static value. I've given him a number of different reasons against this, the main ones being: random values means the test isn't truly repeatable (which also means that if the test can randomly fail, it can do so on the build server and break the build) if it's a random value and the test fails, we need to a) fix the object and b) force ourselves to test for that value every time, so we know it works, but since it's random we don't know what the value was Another coworker added: If I am testing an exception, random values will not ensure that the test ends up in the expected state random data is used for flushing out a system and load testing, not for unit tests Can anyone else add additional reasons I can give him to get him to stop doing this? (Or alternately, is this an acceptable method of writing unit tests, and I and my other coworker are wrong?) | There's a compromise. Your coworker is actually onto something, but I think he's doing it wrong. I'm not sure that totally random testing is very useful, but it's certainly not invalid. A program (or unit) specification is a hypothesis that there exists some program that meets it. The program itself is then evidence of that hypothesis. What unit testing ought to be is an attempt to provide counter-evidence to refute that the program works according to the spec. Now, you can write the unit tests by hand, but it really is a mechanical task. It can be automated. All you have to do is write the spec, and a machine can generate lots and lots of unit tests that try to break your code. I don't know what language you're using, but see here: Java http://functionaljava.org/ Scala (or Java) http://github.com/rickynils/scalacheck Haskell http://www.cs.chalmers.se/~rjmh/QuickCheck/ .NET: http://blogs.msdn.com/dsyme/archive/2008/08/09/fscheck-0-2.aspx These tools will take your well-formed spec as input and automatically generate as many unit tests as you want, with automatically generated data. They use "shrinking" strategies (which you can tweak) to find the simplest possible test case to break your code and to make sure it covers the edge cases well. Happy testing! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517/"
]
} |
32,494 | I coded a Mancala game in Java for a college class this past spring, and I used the Eclipse IDE to write it. One of the great (and fairly simple) visual aids in Eclipse is if you select a particular token, say a declared variable, then the IDE will automatically highlight all other references to that token on your screen. Notepad++ , my preferred Notepad replacement, also does this. Another neat and similar feature in Eclipse was the vertical "error bar" to the right of your code (not sure what to call it). It display little red boxes for all of the syntax errors in your document, yellow boxes for warnings like "variable declared but not used", and if you select a word, boxes appear in the bar for each occurrence of the word in the document. A screenshot of these features in action: After a half hour of searching, I've determined that Visual Studio cannot do this on its own, so my question is: does anyone know of any add-ins for 2005 or 2008 that can provide either one of the aforementioned features? Being able to highlight the current line your cursor is on would be nice too. I believe the add-in ReSharper can do this, but I'd prefer to use a free add-in rather than purchase one. | In a different question on SO ( link ), someone mentioned the VS 2005 / VS 2008 add-in "RockScroll". It seems to provide the "error bar" feature I was inquiring about in my question above. RockScroll EDIT: RockScroll also does the identical token highlighting that I was looking for! Great! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/418/"
]
} |
32,505 | Most XML parsers will give up after the first error in a document. In fact, IIRC, that's actually part of the 'official' spec for parsers. I'm looking for something that will break that rule. It should take a given schema (assuming a valid schema) and an xml input and attempt to keep going after the first error and either raise an event for each error or return a list when finished, so I can use it to generate some kind of a report of the errors in the document. This requirement comes from above, so let's try to keep the purist "but it wouldn't make sense to keep going" comments to a minimum. I'm looking for something that will evaluate both whether the document is well-formed and whether or not it conforms to the schema. Ideally it would evaluate those as different classes of error. I'd prefer a .Net solution but I could use a standalone .exe as well. If you know of one that uses a different platform go ahead and post it because someone else might find it useful. Update: I expect that most of the documents where I use this will be mostly well-formed. Maybe an & included as data instead of & here and there, or an occasional mis-placed tag. I don't expect the parser to be able to recover from anything, just to make a best-effort to keep going. If a document is too out of whack it should spit out as much as it can followed by some kind of 'fatal, unable to continue' error. Otherwise the schema validation part is pretty easy. | In a different question on SO ( link ), someone mentioned the VS 2005 / VS 2008 add-in "RockScroll". It seems to provide the "error bar" feature I was inquiring about in my question above. RockScroll EDIT: RockScroll also does the identical token highlighting that I was looking for! Great! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
32,529 | I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory. How should I go about doing that? | You can probably do this by setting your own FileSystemView . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
} |
32,541 | Anybody have a good example how to deep clone a WPF object, preserving databindings? The marked answer is the first part. The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here: http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571 | The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader. ex:Write the object to xaml (let's say the object was a Grid control): string gridXaml = XamlWriter.Save(myGrid); Load it into a new object: StringReader stringReader = new StringReader(gridXaml);XmlReader xmlReader = XmlReader.Create(stringReader);Grid newGrid = (Grid)XamlReader.Load(xmlReader); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
32,607 | I'd like to rollback a change I made recently in TFS. In Subversion, this was pretty straightforward. However, it seems to be an incredible headache in TFS: Option 1: Get Prior Version Manually get prior version of each file Check out for edit Fail - the checkout (in VS2008) forces me to get the latest version Option 2: Get TFS Power Tools Download Team Foundation Power Tools Issue rollback command from cmd line Fail - it won't work if there are any other pending changes Option 3: Manually Undo Changes manually undo my changes, then commit a new changeset Question How do I rollback to a previous changeset in TFS? | Download and install Team Foundation Power Tools . Open up the Visual Studio command prompt Navigate to the directory on the file system that TFS is mapped to. If you don't do this you'll get an "Unable to determine the workspace" error when you try to roll back Make sure everything else is checked in or shelved run tfpt rollback to bring up the interface. Choose the changesets you want to rollback Check in the new versions of the files you rolled back The big disadvantage of the tool is that it will want to refresh everything in your workspace before you can merge. I got around this issue by creating a new workspace just for the rollback which mapped directly to the place in the source tree where the affected files were. If you need help to figure out which changesets to roll back, I find the code review tool in the free Team Foundation Side Kicks add-in very helpful. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1338/"
]
} |
32,633 | I can easily set breakpoints in embedded JS functions, but I don't see any way of accessing external JS scripts via Firebug unless I happen to enter them during a debug session. Is there a way to do this without having to 'explore' my way into the script? @Jason: This is a good point, but in my case I do not have easy access to the script. I am specifically talking about the client scripts which are invoked by the ASP.Net Validators that I would like to debug. I can access them during a debug session through entering the function calls, but I could not find a way to access them directly. | Place debugger; in your external script file on the line you want to break on. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2133/"
]
} |
32,637 | I am consuming the Twitter API and want to convert all URLs to hyperlinks. What is the most effective way you've come up with to do this? from string myString = "This is my tweet check it out http://tinyurl.com/blah"; to This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a> | Regular expressions are probably your friend for this kind of task: Regex r = new Regex(@"(https?://[^\s]+)");myString = r.Replace(myString, "<a href=\"$1\">$1</a>"); The regular expression for matching URLs might need a bit of work. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2347826/"
]
} |
32,640 | So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET". I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest. I'm using latest version of rhino mocks | Using MoQ it looks something like this: var request = new Mock<HttpRequestBase>();request.Expect(r => r.HttpMethod).Returns("GET");var mockHttpContext = new Mock<HttpContextBase>();mockHttpContext.Expect(c => c.Request).Returns(request.Object);var controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object); I think the Rhino Mocks syntax is similar. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
]
} |
32,649 | When making changes using SubmitChanges() , LINQ sometimes dies with a ChangeConflictException exception with the error message Row not found or changed , without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row. Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless? Additionally, does anybody know whether this exception occurs when any data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter? | Here's a way to see where the conflicts are (this is an MSDN example, so you'll need to heavily customize): try{ db.SubmitChanges(ConflictMode.ContinueOnConflict);}catch (ChangeConflictException e){ Console.WriteLine("Optimistic concurrency error."); Console.WriteLine(e.Message); Console.ReadLine(); foreach (ObjectChangeConflict occ in db.ChangeConflicts) { MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType()); Customer entityInConflict = (Customer)occ.Object; Console.WriteLine("Table name: {0}", metatable.TableName); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); foreach (MemberChangeConflict mcc in occ.MemberConflicts) { object currVal = mcc.CurrentValue; object origVal = mcc.OriginalValue; object databaseVal = mcc.DatabaseValue; MemberInfo mi = mcc.Member; Console.WriteLine("Member: {0}", mi.Name); Console.WriteLine("current value: {0}", currVal); Console.WriteLine("original value: {0}", origVal); Console.WriteLine("database value: {0}", databaseVal); } }} To make it ignore the problem and commit anyway: db.SubmitChanges(ConflictMode.ContinueOnConflict); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
]
} |
32,664 | Can anyone tell me if there is a way with generics to limit a generic type argument T to only: Int16 Int32 Int64 UInt16 UInt32 UInt64 I'm aware of the where keyword, but can't find an interface for only these types, Something like: static bool IntegerFunction<T>(T value) where T : INumeric | There's no constraint for this. It's a real issue for anyone wanting to use generics for numeric calculations. I'd go further and say we need static bool GenericFunction<T>(T value) where T : operators( +, -, /, * ) Or even static bool GenericFunction<T>(T value) where T : Add, Subtract Unfortunately you only have interfaces, base classes and the keywords struct (must be value-type), class (must be reference type) and new() (must have default constructor) You could wrap the number in something else (similar to INullable<T> ) like here on codeproject . You could apply the restriction at runtime (by reflecting for the operators or checking for types) but that does lose the advantage of having the generic in the first place. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/32664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
]
} |
32,668 | I don't edit CSS very often, and almost every time I need to go and google the CSS box model to check whether padding is inside the border and margin outside, or vice versa. (Just checked again and padding is inside). Does anyone have a good way of remembering this? A little mnemonic, a good explanation as to why the names are that way round ... | When working with CSS finally drives you mad the padded cell that they will put you in has the padding on the inside of the walls. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/32668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3189/"
]
} |
32,709 | Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing Func<T, bool> vs. Predicate<T> I would imagine there is no difference as both take a generic parameter and return bool? | They share the same signature, but they're still different types. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
]
} |
32,715 | When using the app_offline.htm feature of ASP.NET, it only allows html, but no images. Is there a way to get images to display without having to point them to a different url on another site ? | Yes, it just can't come from the site that has the app_offline.htm file. The image would have to be hosted elsewhere. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/820/"
]
} |
32,744 | For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something... The way I understand it, outgoing mail has to make three trips: Client (gmail user using Thunderbird) to a server (Gmail) First server (Gmail) to second server (Hotmail) Second server (Hotmail) to second client (hotmail user using OS X Mail) As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server. However, I don't understand how gmail server transfers the message to the hotmail server. For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again). So, the big question is: when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it? Thank you so much! ~Jason Thanks, that's been helpful so far. As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually). Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right? Thanks again (especially to dr-jan), Jason | The SMTP server at Gmail (which accepted the message from Thunderbird) will route the message to the final recipient. It does this by using DNS to find the MX (mail exchanger) record for the domain name part of the destination email address (hotmail.com in this example). The DNS server will return an IP address which the message should be sent to. The server at the destination IP address will hopefully be running SMTP (on the standard port 25) so it can receive the incoming messages. Once the message has been received by the hotmail server, it is stored until the appropriate user logs in and retrieves their messages using POP (or IMAP). Jason - to answer your follow up... Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy). That's correct - the domain name to send to is taken as everything after the '@' in the email address of the recipient. Often, RECEIVESERVER.com is an alias for something more specific, say something like incoming.RECEIVESERVER.com, (or, indeed, smtp.mail.RECEIVESERVER.com). You can use nslookup to query your local DNS servers (this works in Linux and in a Windows cmd window): nslookup> set type=mx> stackoverflow.comServer: 158.155.25.16Address: 158.155.25.16#53Non-authoritative answer:stackoverflow.com mail exchanger = 10 aspmx.l.google.com.stackoverflow.com mail exchanger = 20 alt1.aspmx.l.google.com.stackoverflow.com mail exchanger = 30 alt2.aspmx.l.google.com.stackoverflow.com mail exchanger = 40 aspmx2.googlemail.com.stackoverflow.com mail exchanger = 50 aspmx3.googlemail.com.Authoritative answers can be found from:aspmx.l.google.com internet address = 64.233.183.114aspmx.l.google.com internet address = 64.233.183.27> This shows us that email to anyone at stackoverflow.com should be sent to one of the gmail servers shown above. The Wikipedia article mentioned ( http://en.wikipedia.org/wiki/Mx_record ) discusses the priority numbers shown above (10, 20, ..., 50). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
]
} |
32,747 | How do I get today's date in C# in mm/dd/yyyy format? I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time. BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11. Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well. kronoz's answer | DateTime.Now.ToString("M/d/yyyy"); http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/32747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
]
} |
32,790 | For various reasons calling System.exit is frowned upon when writing Java Applications , so how can I notify the calling process that not everything is going according to plan? Edit: The 1 is a standin for any non-zero exit code. | The use of System.exit is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the System.exit could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option. If the java application is really meant to be run as a standalone application, there is nothing wrong with using System.exit . in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
} |
32,803 | This question comes on the heels of the question asked here . The email that comes from our web server comes from an IP address that is different than that for the Exchange server. Is this okay if the SPF and Domain keys are setup properly? | The use of System.exit is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the System.exit could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option. If the java application is really meant to be run as a standalone application, there is nothing wrong with using System.exit . in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
]
} |
32,814 | I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit? | I suspect you are running the original release (RTM) of .NET 2.0. Until early 2007 validator controls were not compatible with UpdatePanels. This was resolved with the SP1 of the .NET Framework. The source of the problem is that UpdatePanel can detect markup changes in your page, but it has no way to track scripts correctly. Validators rely heavily on scripts. During a partial postback, the scripts are either blown away, not updated, or not run when they are meant to. In early betas, MS had the UpdatePanel try to guess what scripts needed to be re-rendered or run. It didn't work very well, and they had to take it out. To get around the immediate problem, Microsoft released a patched version of the validator classes in a new DLL called Validators.DLL, and gave instructions on how to tell ASP.NET to use those classes instead of the real ones. If you Google for that DLL name, you should find more information. See also This blog post . This was a stop-gag measure and you should not use it avoid it if possible . The real solution to the problem came shortly after, in .NET 2.0 SP1. Microsoft introduced a new mechanism to register scripts in SP1, and changed the real validator classes to use that mechanism instead of the older one. Let me give you some details on the changes: Traditionally, you were supposed to register scripts via Page methods such as Page.RegisterStartupScript() and Page.RegisterClientScriptBlock(). The problem is that these methods were not designed for extensibility and UpdatePanel had no way to monitor those calls. In SP1 there is a new property object on the page called Page.ClientScripts. This object has methods to register scripts that are equivalent (and in some ways better) to the original ones. Also, UpdatePanel can monitor these calls, so that it rerenders or calls the methods when appropriate. The older RegisterStartupScript(), etc. methods have been deprecated. They still work, but not inside an UpdatePanel. There is no reason (other than politics, I suppose) to not update your installations to .NET 2.0 SP1. Service Packs carry important fixes. Good luck. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
32,824 | While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object. My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed. Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data? using System;using System.Web;public class Handler : IHttpHandler { public void ProcessRequest (HttpContext ctx) { ctx.Response.Cache.SetCacheability(HttpCacheability.Private); ctx.Response.Cache.SetETag("\"static\""); ctx.Response.ContentType = "text/plain"; ctx.Response.Write("Hello World"); } public bool IsReusable { get { return true; } }} Will return Cache-Control: privateContent-Type: text/plain; charset=utf-8Content-Length: 11 But if we change it to public it'll return Cache-Control: publicContent-Type: text/plain; charset=utf-8Content-Length: 11Etag: "static" I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using Response.AppendHeader("ETag", "static") Update : It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline. Clarification : It's a long question but the core question is this: why does ASP.NET do this, how can I get around it and should I? Update : I'm going to accept Tony's answer since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache. SetOmitVaryStar (true) otherwise the cache will add the Vary: * header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?) | I think you need to use HttpCacheability.ServerAndPrivate That should give you cache-control: private in the headers and let you set an ETag. The documentation on that needs to be a bit better. Edit: Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: * header to the output and you don't want that. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2114/"
]
} |
32,851 | I'm working on a messaging/notification system for our products. Basic requirements are: Fire and forget Persistent set of messages, possibly updating, to stay there until the sender says to remove them The libraries will be written in C#. Spring.NET just released a milestone build with lots of nice messaging abstraction, which is great - I plan on using it extensively. My basic question comes down to the question of message brokers. My architecture will look something like app -> message broker queue -> server app that listens, dispatches all messages to where they need to go, and handles the life cycle of those long-lived messages -> message broker queue or topic -> listening apps. Finally, the question: Which message broker should I use? I am biased towards ActiveMQ - We used it on our last project and loved it. I can't really think of a single strike against it, except that it's Java, and will require java to be installed on a server somewhere, and that might be a hard sell to some of the people that will be using this service. The other option I've been looking at is MSMQ. I am biased against it for some unknown reason, and it also doesn't seem to have great multicast support. Has anyone used MSMQ for something like this? Any pros or cons, stuff that might sway the vote one way or the other? One last thing, we are using .NET 2.0. | I'm kinda biased as I work on ActiveMQ but pretty much all of benefits listed for MSMQ above also apply to ActiveMQ really. Some more benefits of ActiveMQ include great support for cross language client access and multi protocol support excellent support for enterprise integration patterns a ton of advanced features like exclusive queues and message groups The main downside you mention is that the ActiveMQ broker is written in Java; but you can run it on IKVM as a .net assembly if you really want - or run it as a windows service, or compile it to a DLL/EXE via GCJ. MSMQ may or may not be written in .NET - but it doesn't really matter much how its implemented right? Irrespective of whether you choose MSMQ or ActiveMQ I'd recommend at least considering using the NMS API which as you say is integrated great into Spring.NET. There is an MSMQ implementation of this API as well as implementations for TibCo, ActiveMQ and STOMP which will support any other JMS provider via StompConnect . So by choosing NMS as your API you will avoid lockin to any proprietary technology - and you can then easily switch messaging providers at any point in time; rather than locking your code all into a proprietary API | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
]
} |
32,875 | Are there any lists of default CSS stylesheets for different browsers? (browser stylesheets in tabular form) I want to know the default font of text areas across all browsers for future reference. | Not tabular, but the source CSS may be helpful if you're looking for something specific: Firefox default HTML stylesheet WebKit default HTML stylesheet You're on your own with IE and Opera though. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118/"
]
} |
32,877 | I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway. The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all? Thanks. | A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application. <configuration> <system.diagnostics> <switches> <add name="Remote.Disable" value="1" /> </switches> </system.diagnostics></configuration> The information is debug information that the receiving service can use to help trace things back to the client. (maybe, I am guessing a little) I have proposed a follow up question to determine were the magic switch actually comes from. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
]
} |
32,899 | I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this: import unittestl = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b)if __name__ == '__main__': unittest.main() The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions? | This is called "parametrization". There are several tools that support this approach. E.g.: pytest's decorator parameterized The resulting code looks like this: from parameterized import parameterizedclass TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) Which will generate the tests: test_sequence_0_foo (__main__.TestSequence) ... oktest_sequence_1_bar (__main__.TestSequence) ... FAILtest_sequence_2_lee (__main__.TestSequence) ... ok======================================================================FAIL: test_sequence_1_bar (__main__.TestSequence)----------------------------------------------------------------------Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in <lambda> standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b)AssertionError: 'a' != 'b' For historical reasons I'll leave the original answer circa 2008): I use something like this: import unittestl = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]class TestSequense(unittest.TestCase): passdef test_generator(a, b): def test(self): self.assertEqual(a,b) return testif __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/32899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/720/"
]
} |
32,937 | In C# is there a shorthand way to write this: public static bool IsAllowed(int userID){ return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);} Like: public static bool IsAllowed(int userID){ return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);} I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible. | How about this? public static class Extensions{ public static bool In<T>(this T testValue, params T[] values) { return values.Contains(testValue); }} Usage: Personnel userId = Personnel.JohnDoe;if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe)){ // Do something} I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1302/"
]
} |
32,964 | Obviously there are security reasons to close a wireless network and it's not fun if someone is stealing your bandwidth. That would be a serious problem? To address the first concern: Does a device on the same wireless network have any special privileges or access that an other device on the internet has? Assumptions : Wireless network is connected to the internet The second seems like a community issue. If your neighbor is stealing bandwidth, you'd act just as if he were "borrowing" water or electricity. First, Talk to him about the problem and if that doesn't work, go to the authorities or lock stuff up. Am I missing something? | Bruce Schneier is famous for running an open wireless network at home ( see here ). He does it for two reasons: To be neighborly (you'd let your neighbor borrow a cup of sugar, wouldn't you? Why not a few megabits?) To keep away from the false sense of security that a firewall gives you. In other words, it forces him to make sure his hosts are secure. Personally, I would never run an open wireless network for one reason: accountability. If someone does something illegal on my network, I don't want to be held accountable. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/32964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
]
} |
32,986 | I know that if you have a loop that modifies the count of the items in the loop, using the NSEnumerator on a set is the best way to make sure your code blows up, however I would like to understand the performance tradeoffs between the NSEnumerator class and just an old school for loop | Using the new for (... in ...) syntax in Objective-C 2.0 is generally the fastest way to iterate over a collection because it can maintain a buffer on the stack and get batches of items into it. Using NSEnumerator is generally the slowest way because it often copies the collection being iterated; for immutable collections this can be cheap (equivalent to -retain ) but for mutable collections it can cause an immutable copy to be created. Doing your own iteration — for example, using -[NSArray objectAtIndex:] — will generally fall somewhere in between because while you won't have the potential copying overhead, you also won't be getting batches of objects from the underlying collection. (PS - This question should be tagged as Objective-C, not C, since NSEnumerator is a Cocoa class and the new for (... in ...) syntax is specific to Objective-C.) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/32986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3484/"
]
} |
33,034 | As many of you probably know, online banks nowadays have a security system whereby you are asked some personal questions before you even enter your password. Once you have answered them, you can choose for the bank to "remember this computer" so that in the future you can login by only entering your password. How does the "remember this computer" part work? I know it cannot be cookies, because the feature still works despite the fact that I clear all of my cookies. I thought it might be by IP address, but my friend with a dynamic IP claims it works for him, too (but maybe he's wrong). He thought it was MAC address or something, but I strongly doubt that! So, is there a concept of https-only cookies that I don't clear? Finally, the programming part of the question: how can I do something similar myself in, say, PHP? | In fact they most probably use cookies. An alternative for them would be to use " flash cookies " (officially called " Local Shared Objects "). They are similar to cookies in that they are tied to a website and have an upper size limit, but they are maintained by the flash player, so they are invisible to any browser tools. To clear them (and test this theory), you can use the instructions provided by Adobe . An other nifty (or maybe worrying, depending on your viewpoint) feature is that the LSO storage is shared by all browsers, so using LSO you can identify users even if they switched browser (as long as they are logged in as the same user). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3508/"
]
} |
33,042 | I have a very large code base that contains extensive unit tests (using CppUnit). I need to work out what percentage of the code is exercised by these tests , and (ideally) generate some sort of report that tells me on a per-library or per-file basis, how much of the code was exercised. Here's the kicker: this has to run completely unnatended (eventually inside a continuous integration build), and has to be cross platform (well, WIN32 and *nix at least). Can anyone suggest a tool, or set of tools that can help me do this? I can't change away from CppUnit (nor would I want to - it kicks ass), but otherwise I'm eager to hear any recommendations you might have. Cheers, | Which tool should I use? This article describes another developers frustrations searching for C++ code coverage tools. The author's final solution was Bullseye Coverage . Bullseye Coverage features: Cross Platform Support (win32, unix, and embedded), (supports linux gcc compilers and MSVC6) Easy to use (up and running in a few hours). Provides "best" metrics : Function Coverage and Condition/Decision Coverage. Uses source code instrumentation. As for hooking into your continuous integration, it depends on which CI solution you use, but you can likely hook the instrumentation / coverage measurement steps into the make file you use for automated testing. Testing Linux vs Windows? So long as all your tests run correctly in both environments, you should be fine measuring coverage on one or the other. (Though Bullseye appears to support both platforms ). But why aren't you doing continuous integration builds in both environments?? If you deliver to clients in both environments then you need to be testing in both. For that reason, it sounds like you might need to have two continuous build servers set up, one for a linux build and one for a windows build. Perhaps this can be easily accomplished with some virtualization software like vmware or virtualbox . You may not need to run code coverage metrics on both OSs, but you should definitely be running your unit tests on both. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
]
} |
33,048 | Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec? | You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don't want to have to handle observer behavior in my message expectations. In your example, there isn't a really good way to spec "set_status" on the model without knowledge of what the observer is going to do to it. Therefore, I like to use the "No Peeping Toms" plugin. Given your code above and using the No Peeping Toms plugin, I would spec the model like this: describe Person do it "should set status correctly" do @p = Person.new(:status => "foo") @p.set_status("bar") @p.save @p.status.should eql("bar") endend You can spec your model code without having to worry that there is an observer out there that is going to come in and clobber your value. You'd spec that separately in the person_observer_spec like this: describe PersonObserver do it "should clobber the status field" do @p = mock_model(Person, :status => "foo") @obs = PersonObserver.instance @p.should_receive(:set_status).with("aha!") @obs.after_save endend If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this: describe Person do it "should register a status change with the person observer turned on" do Person.with_observers(:person_observer) do lambda { @p = Person.new; @p.save }.should change(@p, :status).to("aha!) end endend 99% of the time, I'd rather spec test with the observers turned off. It's just easier that way. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2569/"
]
} |
33,055 | I'm new to SVN and I'd like to know what methods are available for backing up repositories in a Windows environment? | You could use something like (Linux): svnadmin dump repositorypath | gzip > backupname.svn.gz Since Windows does not support GZip it is just: svnadmin dump repositorypath > backupname.svn | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/33055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
]
} |
33,079 | I have a couple of pet projects where I'm the sole designer/programmer and I spend too much time changing the user interface to make it easier to use by real users and avoiding bright yellow and green that is so common on "programmer" designs. Do you have tips to choose a color scheme when you do not have a graphics designer around? How do you avoid creating the typical "programmer" interface? | kuler has a lot of user submitted colour schemes edit: just remembered... also try colorlovers | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
]
} |
33,080 | In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window. I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV. My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me? Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar). | Try this simple, specific function: function resizeElementHeight(element) { var height = 0; var body = window.document.body; if (window.innerHeight) { height = window.innerHeight; } else if (body.parentElement.clientHeight) { height = body.parentElement.clientHeight; } else if (body && body.clientHeight) { height = body.clientHeight; } element.style.height = ((height - element.offsetTop) + "px");} It does not depend on the current distance from the top of the body being specified (in case your 300px changes). EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226/"
]
} |
33,199 | Would it be possible to print Hello twice using single condition ? if "condition" printf ("Hello");else printf("World"); | if ( printf("Hello") == 0 ) printf ("Hello");else printf ("World"); :-) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2454/"
]
} |
33,207 | What frameworks exist to unit test Objective-C code? I would like a framework that integrates nicely with Apple Xcode. | Xcode includes XCTest, which is similar to OCUnit , an Objective-C unit testing framework, and has full support for running XCTest-based unit tests as part of your project's build process. Xcode's unit testing support is described in the Xcode Overview: Using Unit Tests . Back in the Xcode 2 days, I wrote a series of weblog posts about how to perform some common tasks with Xcode unit testing: Unit testing Cocoa frameworks Debugging Cocoa framework unit tests Unit testing Cocoa applications Debugging Cocoa application unit tests Despite using OCUnit rather than XCTest, the concepts are largely the same. Finally, I also wrote a few posts on how to write tests for Cocoa user interfaces; the way Cocoa is structured makes it relatively straightforward, because you don't have to spin an event loop or anything like that in most cases. Trust, but verify. Unit testing Cocoa user interfaces: Target-Action Unit testing Cocoa user interfaces: Cocoa Bindings This makes it possible to do test-driven development for not just your model-level code but also your controller-level and even view-level code. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/33207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2339/"
]
} |
33,223 | I know Microsoft has made efforts in the direction of semantic and cross-browser compliant XHTML and CSS, but it still seems like a PitA to pull off elegant markup. I've downloaded and tweaked the CSS Friendly Adapters and all that. But I still find myself frustrated with bloated and unattractive code. Is elegant, semantic CSS with ASP.Net still a pipe dream? Or is it finally possible, I just need more practice? | The easiest way to generate elegant HTML and CSS is to use MVC framework, where you have much more control over HTML generation than with Web Forms. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2640/"
]
} |
33,242 | Is there a method (other than trial and error) I can use to find unused image files? How about CSS declarations for ID's and Classes that don't even exist in the site? It seems like there might be a way to write a script that scans the site, profile it, and see which images and styles are never loaded. | You don't have to pay any web service or search for an addon, you already have this in Google Chrome under F12 (Inspector)->Audits->Remove unused CSS rules Screenshot: Update: 30 Jun, 2017 Now Chrome 59 provides CSS and JS code coverage . See https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
]
} |
33,262 | I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5) Solution Thanks to Matt McMinn , I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException .) public static org.w3c.dom.Document loadXMLFrom(String xml) throws org.xml.sax.SAXException, java.io.IOException { return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes()));}public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is) throws org.xml.sax.SAXException, java.io.IOException { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException ex) { } org.w3c.dom.Document doc = builder.parse(is); is.close(); return doc;} | This works for me in Java 1.5 - I stripped out specific exceptions for readability. import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.DocumentBuilder;import org.w3c.dom.Document;import java.io.ByteArrayInputStream;public Document loadXMLFromString(String xml) throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(xml.getBytes()));} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
]
} |
33,263 | I'm using the ASP.NET Login Controls and Forms Authentication for membership/credentials for an ASP.NET web application. I've got two roles: Users Administrators I want pages to be viewable by four different groups: Everyone (Default, Help) Anonymous (CreateUser, Login, PasswordRecovery) Users (ChangePassword, DataEntry) Administrators (Report) Expanding on the example in the ASP.NET HOW DO I Video Series: Membership and Roles , I've put those page files into such folders: And I used the ASP.NET Web Site Administration Tool to set up access rules for each folder. It works but seems kludgy to me and it creates issues when Login.aspx is not at the root and with the ReturnUrl parameter of Login.aspx. Is there a better way to do this? Is there perhaps a simple way I can set permissions at the page level rather than at the folder level? | This works for me in Java 1.5 - I stripped out specific exceptions for readability. import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.DocumentBuilder;import org.w3c.dom.Document;import java.io.ByteArrayInputStream;public Document loadXMLFromString(String xml) throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(xml.getBytes()));} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
]
} |
33,265 | There are two weird operators in C#: the true operator the false operator If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool. Let's say I have a following class: public class MyType { public readonly int Value; public MyType(int value) { Value = value; } public static bool operator true (MyType mt) { return mt.Value > 0; } public static bool operator false (MyType mt) { return mt.Value < 0; } } So I can write the following code: MyType mTrue = new MyType(100); MyType mFalse = new MyType(-100); MyType mDontKnow = new MyType(0); if (mTrue) { // Do something. } while (mFalse) { // Do something else. } do { // Another code comes here. } while (mDontKnow) However for all the examples above only the true operator is executed. So what's the false operator in C# good for? Note: More examples can be found here , here and here . | You can use it to override the && and || operators. The && and || operators can't be overridden, but if you override | , & , true and false in exactly the right way the compiler will call | and & when you write || and && . For example, look at this code (from http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading - where I found out about this trick; archived version by @BiggsTRC): public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs){ return new AndExpression(lhs, rhs);}public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs){ return new OrExpression(lhs, rhs);}public static bool operator false(AbstractCriterion criteria){ return false;}public static bool operator true(AbstractCriterion criteria){ return false;} This is obviously a side effect and not the way it's intended to be used, but it is useful. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.