source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
6,628 | What is the difference, if any, between these methods of indexing into a PHP array: $array[$index]$array["$index"]$array["{$index}"] I'm interested in both the performance and functional differences. Update: (In response to @Jeremy) I'm not sure that's right. I ran this code: $array = array(100, 200, 300); print_r($array); $idx = 0; $array[$idx] = 123; print_r($array); $array["$idx"] = 456; print_r($array); $array["{$idx}"] = 789; print_r($array); And got this output: Array( [0] => 100 [1] => 200 [2] => 300)Array( [0] => 123 [1] => 200 [2] => 300)Array( [0] => 456 [1] => 200 [2] => 300)Array( [0] => 789 [1] => 200 [2] => 300) | see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit. Performance wise, $index should be faster than "$index" and "{$index}" (which are the same). Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically. In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103/"
]
} |
6,639 | How should I load files into my Java application? | The short answer Use one of these two methods: Class.getResource(String) Class.getResourceAsStream(String) For example: InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg"); -- The long answer Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it: File file = new File("C:\\Users\\Joe\\image.jpg"); This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable. Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone). Instead, use the getResource() methods in the Class class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/816/"
]
} |
6,642 | I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a favicon.ico file in the root of the website. I found this nice little guide: How to Add a Favicon . However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use). Is there a third method that works across all the most popular browsers? | This is what I always use: <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> The second one is for IE. The first one is for other browsers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
]
} |
6,658 | At work we are currently still using JUnit 3 to run our tests. We have been considering switching over to JUnit 4 for new tests being written but I have been keeping an eye on TestNG for a while now. What experiences have you all had with either JUnit 4 or TestNG, and which seems to work better for very large numbers of tests? Having flexibility in writing tests is also important to us since our functional tests cover a wide aspect and need to be written in a variety of ways to get results. Old tests will not be re-written as they do their job just fine. What I would like to see in new tests though is flexibility in the way the test can be written, natural assertions, grouping, and easily distributed test executions. | I've used both, but I have to agree with Justin Standard that you shouldn't really consider rewriting your existing tests to any new format. Regardless of the decision, it is pretty trivial to run both. TestNG strives to be much more configurable than JUnit, but in the end they both work equally well. TestNG has a neat feature where you can mark tests as a particular group, and then easily run all tests of a specific group, or exclude tests of a particular group. Thus you can mark tests that run slowly as in the "slow" group and then ignore them when you want quick results. A suggestion from their documentation is to mark some subset as "checkin" tests which should be run whenever you check new files in. I never saw such a feature in JUnit, but then again, if you don't have it, you don't REALLY miss it. For all its claims of high configuration, I did run into a corner case the a couple weeks ago where I couldn't do what I wanted to do... I wish I could remember what it is, but I wanted to bring it up so you know that it's not perfect. The biggest advantage TestNG has is annotations... which JUnit added in version 4 anyways. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/782/"
]
} |
6,661 | I'm aware of things like onchange , onmousedown and onmouseup but is there a good reference somewhere that lists all of them complete with possibly a list of the elements that they cover? | W3Schools seems to have a good Javascript events reference: HTML DOM Events | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
6,666 | I am working on a new project. Is there any benefit with going with a WCF web service over a regular old fashion web service? Visual Studio offers templates for both. What are the differences? Pros and cons? | What is a "regular old fashioned web service?" An ASMX service, or are you using WSE as well? ASMX services are not naturally interoperable, don't support WS-* specs, and ASMX is a technology that is aging very quickly. WSE (Web Service Enhancements) services DO add support for WS-* and can be made to be interoperable, but WCF is meant to replace WSE, so you should take the time to learn it. I would say that unless your application is a quick an dirty one-off, you will gain immense flexibility and end up with a better design if you choose WCF. WCF does have a learning curve beyond a [WebMethod] attribute, but the learning curve is over-exaggerated in my opinion, and it is exponentially more powerful and future proof than legacy ASMX services. Unless your time line simply cannot tolerate the learning curve, you would be doing yourself a huge favor learning WCF instead of just sticking with ASP.NET Web Services. Applications will only continue to become more and more distributed and interconnected, and WCF is the future of distributed computing on the Microsoft platform. Here is a comparison between the two. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/831/"
]
} |
6,703 | Since I started studying object-oriented programming, I frequently read articles/blogs saying functions are better, or not all problems should be modeled as objects. From your personal programming adventures, when do you think a problem is better solved by OOP? | There is no hard and fast rule. A problem is better solved with OOP when you are better at solving problems and thinking in an OO mentality. Object Orientation is just another tool which has come along through trying to make computing a better tool for solving problems. However, it can allow for better code reuse, and can also lead to neater code. But quite often these highly praised qualities are, in-relity, of little real value. Applying OO techniques to an existing functional application could really cause a lot of problems. The skill lies in learning many different techniques and applying the most appropriate to the problem at hand. OO is often quoted as a Nirvana-like solution to the software development, however there are many times when it is not appropriate to be applied to the issue at hand. It can, quite often, lead to over-engineering of a problem to reach the perfect solution, when often it is really not necessary. In essence, OOP is not really Object Oriented Programming, but mapping Object Oriented Thinking to a programming language capable of supporting OO Techniques. OO techniques can be supported by languages which are not inherently OO, and there are techniques you can use within functional languages to take advantage of the benefits. As an example, I have been developing OO software for about 20 years now, so I tend to think in OO terms when solving problems, irrespective of the language I am writing in. Currently I am implementing polymorphism using Perl 5.6, which does not natively support it. I have chosen to do this as it will make maintenance and extension of the code a simple configuration task, rather than a development issue. Not sure if this is clear. There are people who are hard in the OO court, and there are people who are hard in the Functional court. And then there are people who have tried both and try to take the best from each. Neither is perfect, but both have some very good traits that you can utilise no matter what the language. If you are trying to learn OOP, don't just concentrate on OOP, but try to utilise Object Oriented Analysis and general OO principles to the whole spectrum of the problem solution. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/718/"
]
} |
6,729 | I probably spend far too much time trying to make my visual interfaces look good, and while I'm pretty adept at finding the right match between usability and style one area I am hopeless at is making nice looking icons. How do you people overcome this (I'm sure common) problem? I'm thinking of things like images on buttons and perhaps most important of all, the actual application icon. Do you rely on third party designers, in or out of house? Or do you know of some hidden website that offers lots of icons for us to use? I've tried Google but I seem to find either expensive packages that are very specific, millions of Star Trek icons or icons that look abysmal at 16x16 which is my preferred size on in-application buttons. Any help/advice appreciated. | Good icons are hard to design. I have tried to design my own, and have used in-house graphics designers as well. However, building a good icon set takes a lot of work, even for the graphic designer. I believe your best solution is to buy/find a set of icons for use in your projects. The silk icon set is a good, free set and can be found at FamFamFam . There are over 1000 icons in this set, and it is very popular. If you are looking for something "different", you can purchase icon sets for a couple hundred bucks. Considering the cost of having a designer create them for you, or doing them yourself, the cost of these sets is cheap! Here's a few icon designers I've come across of the web: Icon Factory Icon Experience Icon Buffet | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770/"
]
} |
6,785 | Suppose I have a stringbuilder in C# that does this: StringBuilder sb = new StringBuilder();string cat = "cat";sb.Append("the ").Append(cat).(" in the hat");string s = sb.ToString(); would that be as efficient or any more efficient as having: string cat = "cat";string s = String.Format("The {0} in the hat", cat); If so, why? EDIT After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at injecting one string into another. In both cases above I want to inject one or more strings into the middle of a predefined template string. Sorry for the confusion | NOTE: This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions. String.Format uses a StringBuilder internally: public static string Format(IFormatProvider provider, string format, params object[] args){ if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null) ? "format" : "args"); } StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8)); builder.AppendFormat(provider, format, args); return builder.ToString();} The above code is a snippet from mscorlib, so the question becomes "is StringBuilder.Append() faster than StringBuilder.AppendFormat() "? Without benchmarking I'd probably say that the code sample above would run more quickly using .Append() . But it's a guess, try benchmarking and/or profiling the two to get a proper comparison. This chap, Jerry Dixon, did some benchmarking: http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm Updated: Sadly the link above has since died. However there's still a copy on the Way Back Machine: http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm At the end of the day it depends whether your string formatting is going to be called repetitively, i.e. you're doing some serious text processing over 100's of megabytes of text, or whether it's being called when a user clicks a button now and again. Unless you're doing some huge batch processing job I'd stick with String.Format, it aids code readability. If you suspect a perf bottleneck then stick a profiler on your code and see where it really is. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/6785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
6,816 | I was hoping someone could help me out with a problem I'm having using the java search function in Eclipse on a particular project. When using the java search on one particular project, I get an error message saying Class file name must end with .class (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt? I have already tried Project -> Clean ... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail. The only reference I've been able to find on Google for the problem is at http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx , but unfortunately his solution (closing, deleting class files, restarting) did not work for me. If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers. Version: 3.4.0Build id: I20080617-2000 Also just found this thread - http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck. Caused by: java.lang.IllegalArgumentException: Class file name must end with .classat org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182)at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109)at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177)at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94)at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223)at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506)at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551)at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142)at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129)at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594)at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522)at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45)at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225)at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160)at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77)at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39)at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709)at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800)at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650)at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92)at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) Thanks McDowell, closing and opening the project seems to have fixed it (at least for now). | Two more general-purpose mechanisms for fixing some of Eclipse's idiosyncrasies: Close and open the project Delete the project (but not from disk!) and reimport it as an existing project Failing that, bugs.eclipse.org might provide the answer. If the workspace is caching something broken, you may be able to delete it by poking around in workspace/.metadata/.plugins . Most of that stuff is fairly transient (though backup and watch for deleted preferences). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
6,847 | When writing code do you consciously program defensively to ensure high program quality and to avoid the possibility of your code being exploited maliciously, e.g. through buffer overflow exploits or code injection ? What's the "minimum" level of quality you'll always apply to your code ? | In my line of work, our code has to be top quality. So, we focus on two main things: Testing Code reviews Those bring home the money. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
]
} |
6,859 | As a long time World of Warcraft player, and a passionate developer I have decided that I would like to combine the two and set about developing some addins. Not only to improve my gameplay experience but as a great opportunity to learn something new. Does anyone have any advice on how to go about starting out? Is there an IDE one can use? How does one go about testing? Are there any ready made libraries available? Or would I get a better learning experience by ignoring the libraries and building from scratch? How do I oneshot Hogger? Would love to hear your advice, experiences and views. | This article explains how to start pretty well. Your first bookmark is possibly the US Interface Forum, especially the Stickies for that: http://us.battle.net/wow/en/forum/1011693/ Then, grab some simple addons to learn how XML and LUA interacts. The WoWWiki HOWTO List is a good point here as well. One important thing to keep in mind: World of Warcraft is available in many languages. If you have a EU Account, you got an excellent testing bed by simply downloading the language Packs for Spanish, German and French. If you're an US Guy, check if you can get the Latin America version. That way, you can test it against another language version. Once you made 1 or 2 really small and simple addons just to learn how to use it, have a look at the various frameworks. WowAce is a popular one, but there are others. Just keep one thing in mind: Making an Addon is work. Maintaining one is even more work. With each new Patch, there may be breaking changes, and the next Addon will surely cause a big Exodus of Addons, just like Patch 2.0.1 did. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770/"
]
} |
6,890 | I have some code for starting a thread on the .NET CF 2.0: ThreadStart tStart = new ThreadStart(MyMethod);Thread t = new Thread(tStart);t.Start(); If I call this inside a loop the items completely out of order. How do introduce a wait after t.Start() , so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads? | How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to Kevin Kenny's answer, you should call Join outside the loop. This means you will need a collection to hold references to the threads you started: // Start all of the threads.List<Thread> startedThreads = new List<Thread>();foreach (...) { Thread thread = new Thread(new ThreadStart(MyMethod)); thread.Start(); startedThreads.Add(thread);}// Wait for all of the threads to finish.foreach (Thread thread in startedThreads) { thread.Join();} In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish. If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
]
} |
6,891 | I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not: try{ ... // some code}catch (Exception ex){ ... // Do something throw new CustomException(ex);} Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again. How does this differ in Performance from the following two: try{ ... // some code}catch (Exception ex){ .. // Do something throw ex;} or try{ ... // some code}catch (Exception ex){ .. // Do something throw;} Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches? | @Brad Tutterow The exception is not being lost in the first case, it is being passed in to the constructor. I will agree with you on the rest though, the second approach is a very bad idea because of the loss of stack trace. When I worked with .NET, I ran into many cases where other programmers did just that, and it frustrated me to no end when I needed to see the true cause of an exception, only to find it being rethrown from a huge try block where I now have no idea where the problem originated. I also second Brad's comment that you shouldn't worry about the performance. This kind of micro optimization is a HORRIBLE idea. Unless you are talking about throwing an exception in every iteration of a for loop that is running for a long time, you will more than likely not run into performance issues by the way of your exception usage. Always optimize performance when you have metrics that indicate you NEED to optimize performance, and then hit the spots that are proven to be the culprit. It is much better to have readable code with easy debugging capabilities (IE not hiding the stack trace) rather than make something run a nanosecond faster. A final note about wrapping exceptions into a custom exception... this can be a very useful construct, especially when dealing with UIs. You can wrap every known and reasonable exceptional case into some base custom exception (or one that extends from said base exception), and then the UI can just catch this base exception. When caught, the exception will need to provide means of displaying information to the user, say a ReadableMessage property, or something along those lines. Thus, any time the UI misses an exception, it is because of a bug you need to fix, and anytime it catches an exception, it is a known error condition that can and should be handled properly by the UI. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
]
} |
6,899 | To illustrate, assume that I have two tables as follows: VehicleID Name1 Chuck2 LarryLocationID VehicleID City1 1 New York2 1 Seattle3 1 Vancouver4 2 Los Angeles5 2 Houston I want to write a query to return the following results: VehicleID Name Locations1 Chuck New York, Seattle, Vancouver2 Larry Los Angeles, Houston I know that this can be done using server side cursors, ie: DECLARE @VehicleID intDECLARE @VehicleName varchar(100)DECLARE @LocationCity varchar(100)DECLARE @Locations varchar(4000)DECLARE @Results TABLE( VehicleID int Name varchar(100) Locations varchar(4000))DECLARE VehiclesCursor CURSOR FORSELECT [VehicleID], [Name]FROM [Vehicles]OPEN VehiclesCursorFETCH NEXT FROM VehiclesCursor INTO @VehicleID, @VehicleNameWHILE @@FETCH_STATUS = 0BEGIN SET @Locations = '' DECLARE LocationsCursor CURSOR FOR SELECT [City] FROM [Locations] WHERE [VehicleID] = @VehicleID OPEN LocationsCursor FETCH NEXT FROM LocationsCursor INTO @LocationCity WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = @Locations + @LocationCity FETCH NEXT FROM LocationsCursor INTO @LocationCity END CLOSE LocationsCursor DEALLOCATE LocationsCursor INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @LocationsEND CLOSE VehiclesCursorDEALLOCATE VehiclesCursorSELECT * FROM @Results However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this: SELECT VehicleID , Name , JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS LocationsFROM Vehicles Is this possible? Or something similar? | If you're using SQL Server 2005, you could use the FOR XML PATH command. SELECT [VehicleID] , [Name] , (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX)) FROM [Location] WHERE (VehicleID = Vehicle.VehicleID) FOR XML PATH ('')), 1, 2, '')) AS LocationsFROM [Vehicle] It's a lot easier than using a cursor, and seems to work fairly well. Update For anyone still using this method with newer versions of SQL Server, there is another way of doing it which is a bit easier and more performant using the STRING_AGG method that has been available since SQL Server 2017. SELECT [VehicleID] ,[Name] ,(SELECT STRING_AGG([City], ', ') FROM [Location] WHERE VehicleID = V.VehicleID) AS LocationsFROM [Vehicle] V This also allows a different separator to be specified as the second parameter, providing a little more flexibility over the former method. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/6899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799/"
]
} |
6,915 | Is there a way to implement a singleton object in C++ that is: Lazily constructed in a thread safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once). Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables). (I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..) Excellent, it seems that I have a couple of good answers now (shame I can't mark 2 or 3 as being the answer ). There appears to be two broad solutions: Use static initialisation (as opposed to dynamic initialisation) of a POD static variable, and implementing my own mutex with that using the builtin atomic instructions. This was the type of solution I was hinting at in my question, and I believe I knew already. Use some other library function like pthread_once or boost::call_once . These I certainly didn't know about - and am very grateful for the answers posted. | Basically, you're asking for synchronized creation of a singleton, without using any synchronization (previously-constructed variables). In general, no, this is not possible. You need something available for synchronization. As for your other question, yes, static variables which can be statically initialized (i.e. no runtime code necessary) are guaranteed to be initialized before other code is executed. This makes it possible to use a statically-initialized mutex to synchronize creation of the singleton. From the 2003 revision of the C++ standard: Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit. If you know that you will be using this singleton during the initialization of other static objects, I think you'll find that synchronization is a non-issue. To the best of my knowledge, all major compilers initialize static objects in a single thread, so thread-safety during static initialization. You can declare your singleton pointer to be NULL, and then check to see if it's been initialized before you use it. However, this assumes that you know that you'll use this singleton during static initialization. This is also not guaranteed by the standard, so if you want to be completely safe, use a statically-initialized mutex. Edit: Chris's suggestion to use an atomic compare-and-swap would certainly work. If portability is not an issue (and creating additional temporary singletons is not a problem), then it is a slightly lower overhead solution. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
]
} |
6,926 | I want to get started doing some game development using Microsoft's XNA. Part of that is Shader development, but I have no idea how to get started. I know that nVidia's FX Composer is a great tool to develop shaders, but I did not find much useful and updated content on how to actually get started. What tutorials would you recommend? | Development of shaders in XNA (which obviously uses DirectX) requires knowledge of HLSL or shader assembly. I'd recommend getting familiar with the former before diving into the latter. Before writing any shaders, it's a good idea to get solid understanding of the shader pipeline, and attempt to get your mind around what is possible when using programmable shaders. When you're familiar with the life of a pixel (from source data all the way through to the screen) then understanding examples of shaders becomes a lot easier. Next make an attempt to write your own HLSL which does what the Fixed T&L pipeline used to do, just to get you hands dirty. This is the equivalent of a "hello world" program in vertex/pixel shader world. When you're able to do that and you understand what you've written you're ready to go onto the more fun stuff. As a next step you might want to simulate basic sepcular lighting in one of your shaders from a single light source. You can then adapt this down the track to use multiple lights. Play with colours, and movement of lights. This will help get familiar with the use of shader constants as well. When you have a couple of basic shaders together, you should attempt to make it so that your game/engine uses multiple/different shaders on different objects. Start adding some other bits like basic bump or normal maps . When you get to this stage, the world is your oyster. You can start diving into some funky effectcs, and even consider using the GPU for more than it was originally intended. For those who are a little more advanced, there are a couple of good books that are available for free online which have some great information from Nvidia here and here . Don't forget that there's an excellent series of books called ShaderX which covers some awesome shader stuff. There's 1 , 2 , 3 , 4 , 5 and 6 already in print, and 7 is coming soon. Good luck. If you get some shaders going, I'd love to see them :) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
} |
6,937 | Ultramon is a great program for dual monitors (stretching screen across monitors), but I was wondering if there is any way do to something in Visual Studio like have one tab of code open on one monitor and a second tab of code open on the second monitor with only one instance of Visual Studio running? Or are there any other suggestions on getting most bang for buck on dual monitors and Visual Studio? | Personally, I have my windows set up so that one my main monitor, I have the main visual studio monitor, so therefore my code window, maximized, with only the toolbox docked, on the left. This means the code window takes up as much space as possible, while keeping the left hand edge of the code close to the middle of the screen, where my eyes naturally look. My main monitor is a wide screen, so I find that gives me more than enough room for my code. My secondary monitor has a second window, which contains the tool windows that I use. So I have solution explorer, error list, task list (//todo: comments), output window, find results etc. all taking up as much space as they like on my secondary monitor. When debugging, the solution explorer moves the main monitor, and the watch, autos and locals windows take its place. I find this gives me a very large area to write code, and really helps usage of all of those additional windows, by giving them more real estate than they'd usually have. Update: In response to everyone talking about using the second monitor for documentation or running the app, I wholeheartedly agree, and forgot to mention how I do that. I use PowerMenu alot to acheive this. Basically I can right-click on any window and set Always On Top. So while i'm debugging, i want to see my output window, but then if I have to refer to some documentation, I just flick to Mozilla (on the second monitor), set it on top, and go back to visual studio. I find this lets me manage the tool windows without having to either shuffle them around a lot, or take up valuable space in the code window. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396/"
]
} |
7,031 | I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in? For Example - You have Home , Products , About Us , and Contact . I want to have buttons for Dealer , Distributor , and maybe other information if the user is logged in. So I will have Home , Products , About Us , Contacts , Dealer (if dealer login), Distributor (if distributor login), and so forth. Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show. | Regarding security, you cannot trust what comes from the client : The visitor can see all your code (HTML and Javascript, not PHP) and try stuff The visitor may not even use a browser; it's trivially easy to send a request with a script This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it. If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876/"
]
} |
7,034 | I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around. Note: I'm not looking for a charting library. | I've just put together what you may be looking for: http://www.graphdracula.net It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this: var g = new Graph();g.addEdge("strawberry", "cherry");g.addEdge("cherry", "apple");g.addEdge("id34", "cherry"); I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask! You may want to have a look at other projects, too! Below are two meta-comparisons: SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones. DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph": Here's a list of similar projects (some have been already mentioned here): Pure JavaScript Libraries vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks. Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below ) with help from several universities and other organizations. The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree . Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010. D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery . Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here , human interaction example here , and JS Embed API . sigma.js Lightweight but powerful library for drawing graphs jsPlumb jQuery plug-in for creating interactive connected graphs Springy - a force-directed graph layout algorithm JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines. RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that. JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io . Commercial libraries GoJS Interactive graph drawing and layout library yFiles for HTML Commercial graph drawing and layout library KeyLines Commercial JS network visualization toolkit ZoomCharts Commercial multi-purpose visualization library Syncfusion JavaScript Diagram Commercial diagram library for drawing and visualization. Abandoned libraries Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js) Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013. arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist. jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012. jsdot Client side graph drawing application. Abandoned in 2011 . Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3. Moo Wheel Interactive JS representation for connections and relations (2008) JSViz 2007-era graph visualization script dagre Graph layout for JavaScript Non-Javascript Libraries Graphviz Sophisticated graph visualization language Graphviz has been compiled to Javascript using Emscripten here with an online interactive demo here Flare Beautiful and powerful Flash based graph drawing NodeBox Python Graph Visualization Processing.js Javascript port of the Processing library by John Resig | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/7034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
]
} |
7,035 | I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output. So far the only input required is a password for sudo - and gksudo handles that fine.But I haven't found an easy way to show a message box yet. Is there some kind of 'gkmessage' command available? I'd prefer something present in a default Ubuntu install, but I don't mind installing a new package if necessary. | I believe Zenity will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an Ubuntu package . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/7035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
]
} |
7,074 | What are the differences between these two and which one should I use? string s = "Hello world!";String s = "Hello world!"; | string is an alias in C# for System.String . So technically, there is no difference. It's like int vs. System.Int32 . As far as guidelines, it's generally recommended to use string any time you're referring to an object. e.g. string place = "world"; Likewise, I think it's generally recommended to use String if you need to refer specifically to the class. e.g. string greet = String.Format("Hello {0}!", place); This is the style that Microsoft tends to use in their examples . It appears that the guidance in this area may have changed, as StyleCop now enforces the use of the C# specific aliases. | {
"score": 14,
"source": [
"https://Stackoverflow.com/questions/7074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
]
} |
7,084 | I've worked on a number of different embedded systems. They have all used typedef s (or #defines ) for types such as UINT32 . This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc. But on some systems you know that the compiler and processor won't change for the life of the project. So what should influence your decision to create and enforce project-specific types? EDITI think I managed to lose the gist of my question, and maybe it's really two. With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler. For everything else the types have less importance. You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to UINT16 , UCHAR .Using types such as UCHAR can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type. i++; can become ADD REG,1AND REG, 0xFF which is unecessary. So I think my question should have been :- given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience. | I use type abstraction very rarely. Here are my arguments, sorted in increasing order of subjectivity: Local variables are different from struct members and arrays in the sense that you want them to fit in a register. On a 32b/64b target, a local int16_t can make code slower compared to a local int since the compiler will have to add operations to /force/ overflow according to the semantics of int16_t . While C99 defines an intfast_t typedef, AFAIK a plain int will fit in a register just as well, and it sure is a shorter name. Organizations which like these typedefs almost invariably end up with several of them ( INT32, int32_t, INT32_T , ad infinitum). Organizations using built-in types are thus better off, in a way, having just one set of names. I wish people used the typedefs from stdint.h or windows.h or anything existing; and when a target doesn't have that .h file, how hard is it to add one? The typedefs can theoretically aid portability, but I, for one, never gained a thing from them. Is there a useful system you can port from a 32b target to a 16b one? Is there a 16b system that isn't trivial to port to a 32b target? Moreover, if most vars are ints, you'll actually gain something from the 32 bits on the new target, but if they are int16_t , you won't. And the places which are hard to port tend to require manual inspection anyway; before you try a port, you don't know where they are. Now, if someone thinks it's so easy to port things if you have typedefs all over the place - when time comes to port, which happens to few systems, write a script converting all names in the code base. This should work according to the "no manual inspection required" logic, and it postpones the effort to the point in time where it actually gives benefit. Now if portability may be a theoretical benefit of the typedefs, readability sure goes down the drain. Just look at stdint.h: {int,uint}{max,fast,least}{8,16,32,64}_t . Lots of types. A program has lots of variables; is it really that easy to understand which need to be int_fast16_t and which need to be uint_least32_t ? How many times are we silently converting between them, making them entirely pointless? (I particularly like BOOL/Bool/eBool/boolean/bool/int conversions. Every program written by an orderly organization mandating typedefs is littered with that). Of course in C++ we could make the type system more strict, by wrapping numbers in template class instantiations with overloaded operators and stuff. This means that you'll now get error messages of the form "class Number<int,Least,32> has no operator+ overload for argument of type class Number<unsigned long long,Fast,64>, candidates are..." I don't call this "readability", either. Your chances of implementing these wrapper classes correctly are microscopic, and most of the time you'll wait for the innumerable template instantiations to compile. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/888/"
]
} |
7,089 | How can I create rounded corners using CSS? | Since CSS3 was introduced, the best way to add rounded corners using CSS is by using the border-radius property. You can read the spec on the property, or get some useful implementation information on MDN : If you are using a browser that doesn't implement border-radius (Chrome pre-v4, Firefox pre-v4, IE8, Opera pre-v10.5, Safari pre-v5), then the links below detail a whole bunch of different approaches. Find one that suits your site and coding style, and go with it. CSS Design: Creating Custom Corners& Borders CSS Rounded Corners 'Roundup' 25 Rounded Corners Techniques with CSS | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/7089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
]
} |
7,095 | In other words, is this Singleton implementation thread safe: public class Singleton{ private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return instance; } }} | Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below. public class Singleton{ private static Singleton instance; // Added a static mutex for synchronising use of instance. private static System.Threading.Mutex mutex; private Singleton() { } static Singleton() { instance = new Singleton(); mutex = new System.Threading.Mutex(); } public static Singleton Acquire() { mutex.WaitOne(); return instance; } // Each call to Acquire() requires a call to Release() public static void Release() { mutex.ReleaseMutex(); }} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/7095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
]
} |
7,118 | Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and Safari . In Firefox, you can use Firebug's logging feature and command Line functions . However, this doesn't help me when I move to other browsers. | For Safari you need to enable the "Develop" menu via Preferences (in Safari 3.1; see the entry in Apple's Safari development FAQ ) or via $ defaults write com.apple.Safari IncludeDebugMenu 1 at the terminal in Mac OS X. Then from the Develop menu choose Show Web Inspector and click on the Console link. Your script can write to the console using window.console.log. For Internet Explorer, Visual Studio is really the best script debugger but the Microsoft Script Debugger is okay if you don't have Visual Studio. This post on the IE team blog walks you through installing it and connecting to Internet Explorer. Internet Explorer 8 looks like it will have a very fancy script debugger, so if you're feeling really adventurous you could install the Internet Explorer 8 beta and give that a whirl. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
]
} |
7,244 | What I want to do is something like this: I have enums with combined flagged values. public static class EnumExtension{ public static bool IsSet<T>( this T input, T matchTo ) where T:enum //the constraint I want that doesn't exist in C#3 { return (input & matchTo) != 0; }} So then I could do: MyEnum tester = MyEnum.FlagA | MyEnum.FlagBif( tester.IsSet( MyEnum.FlagA ) ) //act on flag a Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this. Does anyone know a workaround? | EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody. (As requested on my blog post about enum constraints . I've included the basic facts below for the sake of a standalone answer.) The best solution is to wait for me to include it in UnconstrainedMelody 1 . This is a library which takes C# code with "fake" constraints such as where T : struct, IEnumConstraint and turns it into where T : struct, System.Enum via a postbuild step. It shouldn't be too hard to write IsSet ... although catering for both Int64 -based and UInt64 -based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of UInt64 .) What would you want the behaviour to be if you called tester.IsSet(MyFlags.A | MyFlags.C) ? Should it check that all the specified flags are set? That would be my expectation. I'll try to do this on the way home tonight... I'm hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit. EDIT: I'm not sure about IsSet as a name, by the way. Options: Includes Contains HasFlag (or HasFlags) IsSet (it's certainly an option) Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway... 1 or submit it as a patch, of course... | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/7244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
]
} |
7,245 | What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space? Let's say the screen looks like this ('#' represents filled area): ..................................########...................................###.................########...............#####...............#####............... A probable solution is: ..................................########...++++++++++++........++++++++++++###.....++++++++++++########++++++++++++...#####++++++++++++...#####++++++++++++... Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution? Shog9 wrote: Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)? Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any? | @lassevk I found the referenced article, from DDJ: The Maximal Rectangle Problem | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
]
} |
7,252 | We have a junior programmer that simply doesn't write enough tests. I have to nag him every two hours, "have you written tests?" We've tried: Showing that the design becomes simpler Showing it prevents defects Making it an ego thing saying only bad programmers don't This weekend 2 team members had to come to work because his code had a NULL reference and he didn't test it My work requires top quality stable code, and usually everyone 'gets it' and there's no need to push tests through. We know we can make him write tests, but we all know the useful tests are those written when you're into it. Do you know of more motivations? | This is one of the hardest things to do. Getting your people to get it . Sometimes one of the best ways to help junior level programmers 'get it' and learn the right techniques from the seniors is to do a bit of pair programming. Try this: on an upcoming project, pair the junior guy up with yourself or another senior programmer. They should work together, taking turns "driving" (being the one typing at they keyboard) and "coaching" (looking over the shoulder of the driver and pointing out suggestions, mistakes, etc as they go). It may seem like a waste of resources, but you will find: That these guys together can produce code plenty fast and of higher quality. If your junior guy learns enough to "get it" with a senior guy directing him along the right path (eg. "Ok, now before we continue, lets write at test for this function.") It will be well worth the resources you commit to it. Maybe also have someone in your group give the Unit Testing 101 presentation by Kate Rhodes, I think its a great way to get people excited about testing, if delivered well. Another thing you can do is have your Jr. Devs practice the Bowling Game Kata which will help them learn Test Driven Development. It is in java, but could easily be adapted to any language. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/7252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573/"
]
} |
7,260 | How do I setup Public-Key Authentication for SSH? | If you have SSH installed, you should be able to run.. ssh-keygen Then go through the steps, you'll have two files, id_rsa and id_rsa.pub (the first is your private key, the second is your public key - the one you copy to remote machines) Then, connect to the remote machine you want to login to, to the file ~/.ssh/authorized_keys add the contents of your that id_rsa.pub file. Oh, and chmod 600 all the id_rsa* files (both locally and remote), so no other users can read them: chmod 600 ~/.ssh/id_rsa* Similarly, ensure the remote ~/.ssh/authorized_keys file is chmod 600 also: chmod 600 ~/.ssh/authorized_keys Then, when you do ssh remote.machine , it should ask you for the key's password, not the remote machine. To make it nicer to use, you can use ssh-agent to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the ssh-agent command) `ssh-agent` On some distros, ssh-agent is started automatically. If you run echo $SSH_AUTH_SOCK and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command. Then to add your key, you do ssh-add ~/.ssh/id_rsa and enter your passphrase. It's stored until you remove it (using the ssh-add -D command, which removes all keys from the agent) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/7260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
]
} |
7,284 | What does the expression "Turing Complete" mean? Can you give a simple explanation, without going into too many theoretical details? | Here's the briefest explanation: A Turing Complete system means a system in which a program can be written that will find an answer (although with no guarantees regarding runtime or memory). So, if somebody says "my new thing is Turing Complete" that means in principle (although often not in practice) it could be used to solve any computation problem. Sometimes it's a joke... a guy wrote a Turing Machine simulator in vi, so it's possible to say that vi is the only computational engine ever needed in the world. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/7284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198/"
]
} |
7,364 | Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :) I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF? On the front-end | If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework: <?phprequire_once 'Zend/Pdf.php';$pdf = Zend_Pdf::load('blank.pdf');$page = $pdf->pages[0];$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);$page->setFont($font, 12);$page->drawText('Hello world!', 72, 720);$pdf->save('zend.pdf'); If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page. A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/7364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
]
} |
7,477 | I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address. Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed. Here's a screenshot of it currently. Any ideas? @Chris A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space. I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no. I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot). It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it. Though if someone comes up with another way to approach the problem I'm open to that too. I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed. resizeIt = function() { var str = $('iso_address').value; var cols = $('iso_address').cols; var linecount = 0; $A(str.split("\n")).each(function(l) { linecount += 1 + Math.floor(l.length / cols); // Take into account long lines }) $('iso_address').rows = linecount;}; | Facebook does it, when you write on people's walls, but only resizes vertically. Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice. None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'. Some JavaScript code to do it, using Prototype (because that's what I'm familiar with): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <script src="http://www.google.com/jsapi"></script> <script language="javascript"> google.load('prototype', '1.6.0.2'); </script> </head> <body> <textarea id="text-area" rows="1" cols="50"></textarea> <script type="text/javascript" language="javascript"> resizeIt = function() { var str = $('text-area').value; var cols = $('text-area').cols; var linecount = 0; $A(str.split("\n")).each( function(l) { linecount += Math.ceil( l.length / cols ); // Take into account long lines }) $('text-area').rows = linecount + 1; }; // You could attach to keyUp, etc. if keydown doesn't work Event.observe('text-area', 'keydown', resizeIt ); resizeIt(); //Initial on load </script> </body></html> PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/7477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
]
} |
7,492 | In the past, I used Microsoft Web Application Stress Tool and Pylot to stress test web applications. I'd written a simple home page, login script, and site walkthrough (in an ecommerce site adding a few items to a cart and checkout). Just hitting the homepage hard with a handful of developers would almost always locate a major problem. More scalability problems would surface at the second stage, and even more - after the launch. The URL of the tools I used were Microsoft Homer (aka Microsoft Web Application Stress Tool ) and Pylot . The reports generated by these tools never made much sense to me, and I would spend many hours trying to figure out what kind of concurrent load the site would be able to support. It was always worth it because the stupidest bugs and bottlenecks would always come up (for instance, web server misconfigurations). What have you done, what tools have you used, and what success have you had with your approach? The part that is most interesting to me is coming up with some kind of a meaningful formula for calculating the number of concurrent users an app can support from the numbers reported by the stress test application. | Here's another vote for JMeter . JMeter is an open-source load testing tool, written in Java. It's capable of testing a number of different server types (for example, web, web services, database, just about anything that uses requests basically). It does however have a steep learning curve once you start getting to complicated tests, but it's well worth it. You can get up and running very quickly, and depending on what sort of stress-testing you want to do, that might be fine. Pros: Open-Source/Free tool from the Apache project (helps with buy-in) Easy to get started with, and easy to use once you grasp the core concepts. (Ie, how to create a request, how to create an assertion, how to work with variables etc). Very scalable. I've run tests with 11 machines generating load on the server to the tune of almost a million hits/hour. It was much easier to setup than I was expecting. Has an active community and good resources to help you get up and running. Read the tutorials first and play with it for a while. Cons: The UI is written in Swing. (ugh!) JMeter works by parsing the response text returned by the server. So if you're looking to validate any sort of javascript behaviours, you're out of luck. Learning curve is steep for non-programmers. If you're familiar with regular expressions, you're already ahead of the game. There are large numbers of ( insert expletive ) idiots in the support forum asking stupid questions that could be easily solved if they'd give the documentation even a cursory glance. ('How do I use JMeter to stress-test my Windows GUI' shows up quite frequently). Reporting 'out of the box' leaves much to be desired, particularly for larger tests. In the test I mentioned above, I ended up having to write a quick console app to do some of the 'xml-logfile' to 'html' conversions. That was a few years ago though, so it's probable that this would no longer be required. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/7492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
]
} |
7,503 | I know almost nothing about linq. I'm doing this: var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero select app; Which gets me all the running processes which match that criteria. But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this var matchedApp = (from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero select app).First(); which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way? UPDATE I'm actually trying to find the first matching item, and call SetForegroundWindow on it I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas? var unused = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess | @FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want: var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle != IntPtr.Zero);if (app == null) return;SetForegroundWindow(app.MainWindowHandle); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
]
} |
7,525 | So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an std::string to a class and assigning it a value from another std::string : std::string hello = "Hello, world.\n";/* exampleString = "Hello, world.\n" would work fine. */exampleString = hello; crashes on my system with a stack dump. So basically I need to stop and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able. Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with valgrind , and while not knowing completely what I'm doing, it did report that the std::string 's destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well. (In before rm -rf ProjectDir , do again in C# :D) EDIT:I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were. | These are relatively cheap mechanisms for possibly solving the problem: Keep an eye on my heap corruption question - I'm updating with the answers as they shake out. The first was balancing new[] and delete[] , but you're already doing that. Give valgrind more of a go; it's an excellent tool, and I only wish it was available under Windows. I only slows your program down by about half, which is pretty good compared to the Windows equivalents. Think about using the Google Performance Tools as a replacement malloc/new. Have you cleaned out all your object files and started over? Perhaps your make file is... "suboptimal" You're not assert() ing enough in your code. How do I know that without having seen it? Like flossing, no-one assert() s enough in their code. Add in a validation function for your objects and call that on method start and method end. Are you compiling -wall ? If not, do so. Find yourself a lint tool like PC-Lint . A small app like yours might fit in the PC-lint demo page, meaning no purchase for you! Check you're NULLing out pointers after deleteing them. Nobody likes a dangling pointer. Same gig with declared but unallocated pointers. Stop using arrays. Use a vector instead. Don't use raw pointers. Use a smart pointer . Don't use auto_ptr ! That thing is... surprising; its semantics are very odd. Instead, choose one of the Boost smart pointers , or something out of the Loki library . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
]
} |
7,535 | What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005? | This can be done via SQL Enterprise Manager or like this: ALTER DATABASE <database> SET COMPATIBILITY_LEVEL = { 80 | 90 | 100 } Use 90 for 2005 compatibility. This replaces the functionality used for previous releases, the stored procedure sp_dbcmptlevel . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
]
} |
7,539 | Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal . If yes why does not it round the decimal digits but even mantissa part. From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online. Please let me know if you have any idea on this. | @jatan Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method. There's nothing special about BigDecimal.round() vs. any other BigDecimal method. In all cases, the MathContext specifies the number of significant digits and the rounding technique. Basically, there are two parts of every MathContext . There's a precision, and there's also a RoundingMode . The precision again specifies the number of significant digits. So if you specify 123 as a number, and ask for 2 significant digits, you're going to get 120 . It might be clearer if you think in terms of scientific notation. 123 would be 1.23e2 in scientific notation. If you only keep 2 significant digits, then you get 1.2e2 , or 120 . By reducing the number of significant digits, we reduce the precision with which we can specify a number. The RoundingMode part specifies how we should handle the loss of precision. To reuse the example, if you use 123 as the number, and ask for 2 significant digits, you've reduced your precision. With a RoundingMode of HALF_UP (the default mode), 123 will become 120 . With a RoundingMode of CEILING , you'll get 130 . For example: System.out.println(new BigDecimal("123.4", new MathContext(4,RoundingMode.HALF_UP)));System.out.println(new BigDecimal("123.4", new MathContext(2,RoundingMode.HALF_UP)));System.out.println(new BigDecimal("123.4", new MathContext(2,RoundingMode.CEILING)));System.out.println(new BigDecimal("123.4", new MathContext(1,RoundingMode.CEILING))); Outputs: 123.41.2E+21.3E+22E+2 You can see that both the precision and the rounding mode affect the output. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/7539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
]
} |
7,551 | When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management) ? When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints. While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged. Any discussion or links to relevant documents would be very much appreciated.If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the .NET Framework. | As tweakt said, Amazon S3 is a good model to work with. Their request signatures do have some features (such as incorporating a timestamp) that help guard against both accidental and malicious request replaying. The nice thing about HTTP Basic is that virtually all HTTP libraries support it. You will, of course, need to require SSL in this case because sending plaintext passwords over the net is almost universally a bad thing. Basic is preferable to Digest when using SSL because even if the caller already knows that credentials are required, Digest requires an extra roundtrip to exchange the nonce value. With Basic, the callers simply sends the credentials the first time. Once the identity of the client is established, authorization is really just an implementation problem. However, you could delegate the authorization to some other component with an existing authorization model. Again the nice thing about Basic here is your server ends up with a plaintext copy of the client's password that you can simply pass on to another component within your infrastructure as needed. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/7551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/541/"
]
} |
7,579 | In the SSW rules to better SQL Server Database there is an example of a full database maintenance plan: SSW . In the example they run both a Reorganize Index and then a Rebuild Index and then Update Statistics. Is there any point to this? I thought Reorganize Index was a fast but less effective version of Rebuild Index? and that an index rebuild would also update the statistics automatically (on the clustered index at least). | Doing a REORGANIZE and then a REBUILD on the same indexes is pointless, as any changes by the REORGANIZE would be lost by doing the REBUILD . Worse than that is that in the maintenance plan diagram from SSW, it performs a SHRINK first, which fragments the indexes as a side effect of the way it releases space. Then the REBUILD allocates more space to the database files again as working space during the REBUILD operation. REORGANIZE is an online operation that defragments leaf pages in a clustered or non-clustered index page by page using little extra working space. REBUILD is an online operation in Enterprise editions, offline in other editions, and uses as much extra working space again as the index size. It creates a new copy of the index and then drops the old one, thus getting rid of fragmentation. Statistics are recomputed by default as part of this operation, but that can be disabled. See Reorganizing and Rebuilding Indexes for more information. Don't use SHRINK except with the TRUNCATEONLY option and even then if the file will grow again then you should think hard as to whether it's necessary: sqlservercentral_SHRINKFILE | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961/"
]
} |
7,592 | I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much. The mail created by the mailto action has the syntax: subject: undefined subject body: param1=value1 param2=value2 . . . paramn=valuen Can I use JavaScript to format the mail like this? Subject:XXXXX Body: Value1;Value2;Value3...ValueN | What we used in a projet is a popup window that opens a mailto: link, it is the only way we found to compose a mail within the default mail client that works with all mail clients (at least all our clients used). var addresses = "";//between the speech mark goes the receptient. Seperate addresses with a ;var body = ""//write the message text between the speech marks or put a variable in the place of the speech marksvar subject = ""//between the speech marks goes the subject of the messagevar href = "mailto:" + addresses + "?" + "subject=" + subject + "&" + "body=" + body;var wndMail;wndMail = window.open(href, "_blank", "scrollbars=yes,resizable=yes,width=10,height=10");if(wndMail){ wndMail.close(); } | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518/"
]
} |
7,596 | First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier. I myself have always had problems with naming, placing So, Where do you put your domain specific constants (and what is the best name for such a class)? Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)? Where to put Exceptions? Are there any standards to which I can refer? | I've really come to like Maven's Standard Directory Layout . One of the key ideas for me is to have two source roots - one for production code and one for test code like so: MyProject/src/main/java/com/acme/Widget.javaMyProject/src/test/java/com/acme/WidgetTest.java (here, both src/main/java and src/test/java are source roots). Advantages: Your tests have package (or "default") level access to your classes under test. You can easily package only your production sources into a JAR by dropping src/test/java as a source root. One rule of thumb about class placement and packages: Generally speaking, well structured projects will be free of circular dependencies . Learn when they are bad (and when they are not ), and consider a tool like JDepend or SonarJ that will help you eliminate them. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917/"
]
} |
7,622 | In C, are the shift operators ( << , >> ) arithmetic or logical? | According to K&R 2nd edition the results are implementation-dependent for right shifts of signed values. Wikipedia says that C/C++ 'usually' implements an arithmetic shift on signed values. Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/7622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/973/"
]
} |
7,642 | Is there an official convention for naming private fields in VB.NET? For example, if I have a property called 'Foo', I normally call the private field '_Foo'. This seems to be frowned upon in the Offical Guidelines : "Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields." In C#, you could call the private field 'foo', the property 'Foo', and refer to the private field as 'this.foo' in the constructor. As VB.NET is case insensitive you can't do this - any suggestions? | I still use the _ prefix in VB for private fields, so I'll have _foo as the private field and Foo as the property. I do this for c# as well and pretty much any code I write. Generally I wouldn't get too caught up in "what is the right way to do it" because there isn't really a "right" way (altho there are some very bad ways) but rather be concerned with doing it consistently. At the end of the day, being consistent will make your code much more readable and maintainable than using any set of "right" conventions. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133/"
]
} |
7,651 | I have an array in Perl: my @my_array = ("one","two","three","two","three"); How do I remove the duplicates from the array? | You can do something like this as demonstrated in perlfaq4 : sub uniq { my %seen; grep !$seen{$_}++, @_;}my @array = qw(one two three two three);my @filtered = uniq(@array);print "@filtered\n"; Outputs: one two three If you want to use a module, try the uniq function from List::MoreUtils | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/7651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
]
} |
7,662 | Whenever I design a database, I always wonder if there is a best way of naming an item in my database. Quite often I ask myself the following questions: Should table names be plural? Should column names be singular? Should I prefix tables or columns? Should I use any case in naming items? Are there any recommended guidelines out there for naming items in a database? | I recommend checking out Microsoft's SQL Server sample databases: https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks The AdventureWorks sample uses a very clear and consistent naming convention that uses schema names for the organization of database objects. Singular names for tables Singular names for columns Schema name for tables prefix (E.g.: SchemeName.TableName) Pascal casing (a.k.a. upper camel case) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/7662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
7,665 | Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time. If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X): $ ls -ld foo bardrwxr-xr-x 2 greg greg 68 Aug 11 22:36 barlrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar$ cd foo$ pwd/Users/greg/tmp/foo$ What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar". | readlink -f "$path" Editor's note: The above works with GNU readlink and FreeBSD/PC-BSD/OpenBSD readlink , but not on OS X as of 10.11. GNU readlink offers additional, related options, such as -m for resolving a symlink whether or not the ultimate target exists. Note since GNU coreutils 8.15 (2012-01-06), there is a realpath program available that is less obtuse and more flexible than the above. It's also compatible with the FreeBSD util of the same name. It also includes functionality to generate a relative path between two files. realpath $path [Admin addition below from comment by halloleo — danorton] For Mac OS X (through at least 10.11.x), use readlink without the -f option: readlink $path Editor's note: This will not resolve symlinks recursively and thus won't report the ultimate target; e.g., given symlink a that points to b , which in turn points to c , this will only report b (and won't ensure that it is output as an absolute path ). Use the following perl command on OS X to fill the gap of the missing readlink -f functionality: perl -MCwd -le 'print Cwd::abs_path(shift)' "$path" | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/7665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893/"
]
} |
7,685 | I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here. | Wonder why it should be big challenge as it is stated here, here is a straightforward implementation in Java with out any "clever tricks". //The main functionpublic static Node merge_sort(Node head) { if(head == null || head.next == null) return head; Node middle = getMiddle(head); //get the middle of the list Node left_head = head; Node right_head = middle.next; middle.next = null; //split the list into two halfs return merge(merge_sort(left_head), merge_sort(right_head)); //recurse on that}//Merge subroutine to merge two sorted listspublic static Node merge(Node a, Node b){ Node dummyHead = new Node(); for(Node current = dummyHead; a != null && b != null; current = current.next;) { if(a.data <= b.data) { current.next = a; a = a.next; } else { current.next = b; b = b.next; } } dummyHead.next = (a == null) ? b : a; return dummyHead.next;}//Finding the middle element of the list for splittingpublic static Node getMiddle(Node head){ if(head == null) return head; Node slow = head, fast = head; while(fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } return slow;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608/"
]
} |
7,694 | Is this even a valid question? I have a .NET Windows app that is using MSTDC and it is throwing an exception: System.Transactions.TransactionManagerCommunicationException: Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool ---> System.Runtime.InteropServices.COMException (0x8004D024): The transaction manager has disabled its support for remote/network transactions. (Exception from HRESULT: 0x8004D024) at System.Transactions.Oletx.IDtcProxyShimFactory.ReceiveTransaction(UInt32 propgationTokenSize, Byte[] propgationToken, IntPtr managedIdentifier, Guid& transactionIdentifier, OletxTransactionIsolationLevel& isolationLevel, ITransactionShim& transactionShim).... I followed the Kbalertz guide to enable MSDTC on the PC on which the app is installed, but the error still occurs. I was wondering if this was a database issue? If so, how can I resolve it? | Use this for windows Server 2008 r2 and Windows Server 2012 R2 Click Start , click Run , type dcomcnfg and then click OK to open Component Services . In the console tree, click to expand Component Services , click to expand Computers , click to expand My Computer , click to expand Distributed Transaction Coordinator and then click Local DTC . Right click Local DTC and click Properties to display the Local DTC Properties dialog box. Click the Security tab. Check mark "Network DTC Access" checkbox. Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes. Click Apply , OK . A message will pop up about restarting the service. Click OK and That's all. Reference : https://msdn.microsoft.com/en-us/library/dd327979.aspx Note: Sometimes the network firewall on the Local Computer or the Server could interrupt your connection so make sure you create rules to "Allow Inbound" and "Allow Outbound" connection for C:\Windows\System32\msdtc.exe | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/7694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
]
} |
7,707 | I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set max-height: 100px and overflow:auto , hoping for scrollbars to appear when the content does not fit. It all works fine in Firefox and IE7, but IE8 behaves as if overflow:hidden was present instead of overflow:auto . I tried overflow:scroll , still does not help, IE8 simply truncates the content without showing scrollbars. Changing max-height declaration to height makes overflow work OK, it's the combination of max-height and overflow:auto that breaks things. This is also logged as an official bug in the final, release version of IE8 Is there a workaround? For now I resorted to using height instead of max-height , but it leaves plenty of empty space in case there isn't much data. | This is a really nasty bug as it affects us heavily on Stack Overflow with <pre> code blocks, which have max-height:600 and width:auto . It is logged as a bug in the final version of IE8 with no fix. http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759 There is a really, really hacky CSS workaround: http://my.opera.com/dbloom/blog/2009/03/11/css-hack-for-ie8-standards-mode /*SUPER nasty IE8 hack to deal with this bug*/pre { max-height: none\9 } and of course conditional CSS as others have mentioned, but I dislike that because it means you're serving up extra HTML cruft in every page request. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/7707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979/"
]
} |
7,720 | I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a .jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular .exe for him/her to run. Has anyone had any experience with any of the .exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own? Edit: I should perhaps mention that I am unable to spend a lot of money on a commercial solution. | To follow up on pauxu's answer, I'm using launch4j and NSIS on a project of mine and thought it would be helpful to show just how I'm using them. Here's what I'm doing for Windows. BTW, I'm creating .app and .dmg for Mac, but haven't figured out what to do for Linux yet. Project Copies of launch4j and NSIS In my project I have a "vendor" directory and underneath it I have a directory for "launch4j" and "nsis". Within each is a copy of the install for each application. I find it easier to have a copy local to the project rather than forcing others to install both products and set up some kind of environment variable to point to each. Script Files I also have a "scripts" directory in my project that holds various configuration/script files for my project. First there is the launch4j.xml file: <launch4jConfig> <dontWrapJar>true</dontWrapJar> <headerType>gui</headerType> <jar>rpgam.jar</jar> <outfile>rpgam.exe</outfile> <errTitle></errTitle> <cmdLine></cmdLine> <chdir>.</chdir> <priority>normal</priority> <downloadUrl>http://www.rpgaudiomixer.com/</downloadUrl> <supportUrl></supportUrl> <customProcName>false</customProcName> <stayAlive>false</stayAlive> <manifest></manifest> <icon></icon> <jre> <path></path> <minVersion>1.5.0</minVersion> <maxVersion></maxVersion> <jdkPreference>preferJre</jdkPreference> </jre> <splash> <file>..\images\splash.bmp</file> <waitForWindow>true</waitForWindow> <timeout>60</timeout> <timeoutErr>true</timeoutErr> </splash></launch4jConfig> And then there's the NSIS script rpgam-setup.nsis. It can take a VERSION argument to help name the file. ; The name of the installerName "RPG Audio Mixer"!ifndef VERSION !define VERSION A.B.C!endif; The file to writeoutfile "..\dist\installers\windows\rpgam-${VERSION}.exe"; The default installation directoryInstallDir "$PROGRAMFILES\RPG Audio Mixer"; Registry key to check for directory (so if you install again, it will ; overwrite the old one automatically)InstallDirRegKey HKLM "Software\RPG_Audio_Mixer" "Install_Dir"# create a default section.section "RPG Audio Mixer" SectionIn RO ; Set output path to the installation directory. SetOutPath $INSTDIR File /r "..\dist\layout\windows\" ; Write the installation path into the registry WriteRegStr HKLM SOFTWARE\RPG_Audio_Mixer "Install_Dir" "$INSTDIR" ; Write the uninstall keys for Windows WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "DisplayName" "RPG Audio Mixer" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "UninstallString" '"$INSTDIR\uninstall.exe"' WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoModify" 1 WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoRepair" 1 WriteUninstaller "uninstall.exe" ; read the value from the registry into the $0 register ;readRegStr $0 HKLM "SOFTWARE\JavaSoft\Java Runtime Environment" CurrentVersion ; print the results in a popup message box ;messageBox MB_OK "version: $0"sectionEndSection "Start Menu Shortcuts" CreateDirectory "$SMPROGRAMS\RPG Audio Mixer" CreateShortCut "$SMPROGRAMS\RPG Audio Mixer\Uninstall.lnk" "$INSTDIR\uninstall.exe" "" "$INSTDIR\uninstall.exe" 0 CreateShortCut "$SMPROGRAMS\RPG AUdio Mixer\RPG Audio Mixer.lnk" "$INSTDIR\rpgam.exe" "" "$INSTDIR\rpgam.exe" 0SectionEndSection "Uninstall" ; Remove registry keys DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" DeleteRegKey HKLM SOFTWARE\RPG_Audio_Mixer ; Remove files and uninstaller Delete $INSTDIR\rpgam.exe Delete $INSTDIR\uninstall.exe ; Remove shortcuts, if any Delete "$SMPROGRAMS\RPG Audio Mixer\*.*" ; Remove directories used RMDir "$SMPROGRAMS\RPG Audio Mixer" RMDir "$INSTDIR"SectionEnd Ant Integration I have some targets in my Ant buildfile (build.xml) to handle the above. First I tel Ant to import launch4j's Ant tasks: <property name="launch4j.dir" location="vendor/launch4j" /><taskdef name="launch4j" classname="net.sf.launch4j.ant.Launch4jTask" classpath="${launch4j.dir}/launch4j.jar:${launch4j.dir}/lib/xstream.jar" /> I then have a simple target for creating the wrapper executable: <target name="executable-windows" depends="jar" description="Create Windows executable (EXE)"> <launch4j configFile="scripts/launch4j.xml" outfile="${exeFile}" /></target> And another target for making the installer: <target name="installer-windows" depends="executable-windows" description="Create the installer for Windows (EXE)"> <!-- Lay out files needed for building the installer --> <mkdir dir="${windowsLayoutDirectory}" /> <copy file="${jarFile}" todir="${windowsLayoutDirectory}" /> <copy todir="${windowsLayoutDirectory}/lib"> <fileset dir="${libraryDirectory}" /> <fileset dir="${windowsLibraryDirectory}" /> </copy> <copy todir="${windowsLayoutDirectory}/icons"> <fileset dir="${iconsDirectory}" /> </copy> <copy todir="${windowsLayoutDirectory}" file="${exeFile}" /> <mkdir dir="${windowsInstallerDirectory}" /> <!-- Build the installer using NSIS --> <exec executable="vendor/nsis/makensis.exe"> <arg value="/DVERSION=${version}" /> <arg value="scripts/rpgam-setup.nsi" /> </exec></target> The top portion of that just copies the necessary files for the installer to a temporary location and the second half executes the script that uses all of it to make the installer. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998/"
]
} |
7,773 | I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page. What can I do to resolve this? | If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example: <asp:Label runat="server" id="Label1" style="display: none;" /> Then, you could make it visible on the client side with: document.getElementById('Label1').style.display = 'inherit'; You could make it hidden again with: document.getElementById('Label1').style.display = 'none'; Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013/"
]
} |
7,864 | As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on Active Record . Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains why it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?) Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record. If it doesn't scale well, why not? What other problems does it have? | There's ActiveRecord the Design Pattern and ActiveRecord the Rails ORM Library , and there's also a ton of knock-offs for .NET, and other languages. These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says "ActiveRecord Sucks" it needs to be qualified by saying "which ActiveRecord, there's heaps?" I'm only familiar with Rails' ActiveRecord, I'll try address all the complaints which have been raised in context of using it. @BlaM The problem that I see with Active Records is, that it's always just about one table Code: class Person belongs_to :companyendpeople = Person.find(:all, :include => :company ) This generates SQL with LEFT JOIN companies on companies.id = person.company_id , and automatically generates associated Company objects so you can do people.first.company and it doesn't need to hit the database because the data is already present. @pix0r The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records Code: person = Person.find_by_sql("giant complicated sql query") This is discouraged as it's ugly, but for the cases where you just plain and simply need to write raw SQL, it's easily done. @Tim Sullivan ...and you select several instances of the model, you're basically doing a "select * from ..." Code: people = Person.find(:all, :select=>'name, id') This will only select the name and ID columns from the database, all the other 'attributes' in the mapped objects will just be nil, unless you manually reload that object, and so on. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/7864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
]
} |
7,880 | I want to open a file for reading, the C++ way. I need to be able to do it for: text files, which would involve some sort of read line function. binary files, which would provide a way to read raw data into a char* buffer. | There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen / fread / fclose , or you could use the C++ fstream facilities ( ifstream / ofstream ), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations. All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text: int nsize = 10;std::vector<char> somedata(nsize);ifstream myfile;myfile.open("<path to file>");myfile.read(somedata.data(), nsize);myfile.close(); Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
7,884 | I've just come across this in a WHERE clause: AND NOT (t.id = @id) How does this compare with: AND t.id != @id Or with: AND t.id <> @id I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using <> or != is going to bust any hopes for using an index that I might have had, but surely the first approach above will suffer the same problem? | These 3 will get the same exact execution plan declare @id varchar(40)select @id = '172-32-1176'select * from authorswhere au_id <> @idselect * from authorswhere au_id != @idselect * from authorswhere not (au_id = @id) It will also depend on the selectivity of the index itself of course. I always use au_id <> @id myself | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
]
} |
7,885 | Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties? | You should definitely take a look at Moose . package Point;use Moose; # automatically turns on strict and warningshas 'x' => (is => 'rw', isa => 'Int');has 'y' => (is => 'rw', isa => 'Int');sub clear { my $self = shift; $self->x(0); $self->y(0);} Moose gives you (among other things) a constructor, accessor methods, and type checking for free! So in your code you can: my $p = Point->new({x=>10 , y=>20}); # Free constructor$p->x(15); # Free setterprint $p->x(); # Free getter$p->clear();$p->x(15.5); # FAILS! Free type check. A good starting point is Moose::Manual and Moose::Cookbook If you just need the basic stuff you can also use Mouse which is not as complete, but without most of the compile time penalty. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
7,913 | I've always found checkin (commit) mails to be very useful for keeping track of what work other people are doing in the codebase / repository. How do I set up SVN to email a distribution list on each commit? I'm running clients on Windows and the Apache Subversion server on Linux. The answers below for various platforms will likely be useful to other people though. | You use the post-commit hooks . Here's a guide . Here's a sample Ruby script that sends an email after each commit: commit-email.rb | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/7913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031/"
]
} |
7,940 | Even though I always strive for complete validation these days, I often wonder if it's a waste of time. If the code runs and it looks the same in all browsers (I use browsershots.org to verify) then do I need to take it any further or am I just being overly anal? What level do you hold your code to when you create it for: a) yourselfb) your clients P.S. Jeff and company, why doesn't stack overflow validate? :) EDIT: Some good insights, I think that since I've been so valid-obsessed for so long I program knowing what will cause problems and what won't so I'm in a better position than people who create a site first and then "go back and fix the validation problems" I think I may post another question on stack overflow; "Do you validate as you go or do you finish and then go back and validate?" as that seems to be where this question is going | a) Must look the same b) As standards-compliant as possible, but not so anal that it blocks finishing work In a situation where you have perpetual access to the code, I don't think standards-compliance is all that important, since you can always make changes to the code if something breaks. If you don't have perpetual access (ie, you sign off on the code and it becomes someone else's responsibility), it's probably best to be as standards-compliant as possible to minimize maintenance headaches later... even if you never have to deal with the code again, your reputation persists and can be transmitted to other potential clients, and many teams like to blame the previous developer(s) for problems that come up. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
]
} |
7,990 | I am working on a project right now that involves receiving a message from another application, formatting the contents of that message, and sending it to a printer. The technology of choice is C# windows service. The output could be called a report, I suppose, but a reporting engine is not necessary. A simple templating engine, like StringTemplate, or even XSLT outputting HTML would be fine. The problem I'm having is finding a free way to print this kind of output from a service. Since it seems that it will work, I'm working on a prototype using Microsoft's RDLC, populating a local report and then rendering it as an image to a memory stream, which I will then print. Issues with that are: Multi-page printing will be a big headache. Still have to use PrintDocument to print the memory stream, which is unsupported in a Windows Service (though it may work - haven't gotten that far with the prototype yet) If the data coming across changes, I have to change the dataset and the class that the data is being deserialized into. bad bad bad. Has anyone had to do anything remotely like this? Any advice? I already posted a question about printing HTML without user input, and after wasting about 3 days on that, I have come to the conclusion that it cannot be done, at least not with any freely available tool. All help is appreciated. EDIT: We are on version 2.0 of the .NET framework. | Trust me, you will spend more money trying to search/develop a solution for this as compared to buying a third party component. Do not reinvent the wheel and go for the paid solution. Printing is a complex problem and I would love to see the day when better framework support is added for this. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/7990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
]
} |
7,991 | I'm using the .NETCF (Windows Mobile) Graphics class and the DrawString() method to render a single character to the screen. The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset. For example, at text size 12, the offset is about 4, but at 32 the offset is about 10. I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. this is referencing the user control it's being drawn in. Graphics g = this.CreateGraphics();float padx = ((float)this.Size.Width) * (0.05F);float pady = ((float)this.Size.Height) * (0.05F);float width = ((float)this.Size.Width) - 2 * padx;float height = ((float)this.Size.Height) - 2 * pady;float emSize = height;g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular), new SolidBrush(Color.Black), padx, pady); Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the Graphics class. | I'd like to add another vote for the StringFormat object.You can use this simply to specify "center, center" and the text will be drawn centrally in the rectangle or points provided: StringFormat format = new StringFormat();format.LineAlignment = StringAlignment.Center;format.Alignment = StringAlignment.Center; However there is one issue with this in CF. If you use Center for both values then it turns TextWrapping off. No idea why this happens, it appears to be a bug with the CF. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/7991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
]
} |
8,021 | I'd like to allow a user to set up an SSH tunnel to a particular machine on a particular port (say, 5000), but I want to restrict this user as much as possible. (Authentication will be with public/private keypair). I know I need to edit the relevant ~/.ssh/authorized_keys file, but I'm not sure exactly what content to put in there (other than the public key). | On Ubuntu 11.10, I found I could block ssh commands, sent with and without -T, and block scp copying, while allowing port forwarding to go through. Specifically I have a redis-server on "somehost" bound to localhost:6379 that I wish to share securely via ssh tunnels to other hosts that have a keyfile and will ssh in with: $ ssh -i keyfile.rsa -T -N -L 16379:localhost:6379 someuser@somehost This will cause the redis-server, "localhost" port 6379 on "somehost" to appear locally on the host executing the ssh command, remapped to "localhost" port 16379. On the remote "somehost" Here is what I used for authorized_keys: cat .ssh/authorized_keys (portions redacted)no-pty,no-X11-forwarding,permitopen="localhost:6379",command="/bin/echo do-not-send-commands" ssh-rsa rsa-public-key-code-goes-here keyuser@keyhost The no-pty trips up most ssh attempts that want to open a terminal. The permitopen explains what ports are allowed to be forwarded, in this case port 6379 the redis-server port I wanted to forward. The command="/bin/echo do-not-send-commands" echoes back "do-not-send-commands" if someone or something does manage to send commands to the host via ssh -T or otherwise. From a recent Ubuntu man sshd , authorized_keys / command is described as follows: command="command" Specifies that the command is executed whenever this key is used for authentication. The command supplied by the user (if any) is ignored. Attempts to use scp secure file copying will also fail with an echo of "do-not-send-commands" I've found sftp also fails with this configuration. I think the restricted shell suggestion, made in some previous answers, is also a good idea.Also, I would agree that everything detailed here could be determined from reading "man sshd" and searching therein for "authorized_keys" | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/8021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
]
} |
8,128 | How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET? | This guy seems to have your answer. https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net And in case the blog ever goes away or breaks the url, here's the github link: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs Usage of the Crc32 class from the blog post: Crc32 crc32 = new Crc32();String hash = String.Empty;using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open)) foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();Console.WriteLine("CRC-32 is {0}", hash); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/8128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17/"
]
} |
8,213 | I need to import a csv file into Firebird and I've spent a couple of hours trying out some tools and none fit my needs. The main problem is that all the tools I've been trying like EMS Data Import and Firebird Data Wizard expect that my CSV file contains all the information needed by my Table. I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS. My insert statement would be something like this: INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID), :NAME, (SELECT CITY_ID FROM CITY WHERE NAME = :CITY_NAME) How can I approach this? | It's a bit crude - but for one off jobs, I sometimes use Excel. If you import the CSV file into Excel, you can create a formula which creates an INSERT statement by using string concatenation in the formula. So - if your CSV file has 3 columns that appear in columns A, B, and C in Excel, you could write a formula like... ="INSERT INTO MyTable (Col1, Col2, Col3) VALUES (" & A1 & ", " & B1 & ", " & C1 & ")" Then you can replicate the formula down all of your rows, and copy, and paste the answer into a text file to run against your database. Like I say - it's crude - but it can be quite a 'quick and dirty' way of getting a job done! | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/8213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
]
} |
8,223 | Is it necessary or advantageous to write custom connection pooling code when developing applications in .NET with an SQL Server database? I know that ADO.NET gives you the option to enable/disable connection pooling -- does that mean that it's built into the framework and I don't need to worry about it? Why do people talk about writing their own connection pooling software and how is this different than what's built into ADO.NET? | The connection pooling built-in to ADO.Net is robust and mature. I would recommend against attempting to write your own version. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72/"
]
} |
8,236 | How can I figure out the size of a file, in bytes? #include <stdio.h>unsigned int fsize(char* file){ //what goes here?} | On Unix-like systems, you can use POSIX system calls: stat on a path , or fstat on an already-open file descriptor (POSIX man page , Linux man page ). (Get a file descriptor from open(2) , or fileno(FILE*) on a stdio stream). Based on NilObject's code: #include <sys/stat.h>#include <sys/types.h>off_t fsize(const char *filename) { struct stat st; if (stat(filename, &st) == 0) return st.st_size; return -1; } Changes: Made the filename argument a const char . Corrected the struct stat definition, which was missing the variable name. Returns -1 on error instead of 0 , which would be ambiguous for an empty file. off_t is a signed type so this is possible. If you want fsize() to print a message on error, you can use this: #include <sys/stat.h>#include <sys/types.h>#include <string.h>#include <stdio.h>#include <errno.h>off_t fsize(const char *filename) { struct stat st; if (stat(filename, &st) == 0) return st.st_size; fprintf(stderr, "Cannot determine size of %s: %s\n", filename, strerror(errno)); return -1;} On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64 , otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/8236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
8,284 | I'm looking for an online solution for generating .ICO files. I'd like the ICO files to have the ability to have transparency as well. What software or web site do you use to create them? [Update] To clarify, I have an existing image in PNG format, 32 x 32 pixels. I want to generate the icon from this existing file, not create a brand new one online. Sorry for the confusion. | I have found the application IcoFx useful, you can import pretty much any image type to use for icon creation, including PNG's. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/519/"
]
} |
8,351 | I'm trying to fix some JavaScript bugs. Firebug makes debugging these issues a lot easier when working in Firefox, but what do you do when the code works fine on Firefox but IE is complaining? | you can also check out the IE Developer Toolbar which isn't a debugger but will help you analyze the contents of your code. Visual Studio will help with the debugging Fiddler should help analyse the traffic travelling to and from your browser | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/8351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
]
} |
8,371 | How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches. I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for. On my client's desktops I have SOME shortcuts which point to http://production_server and https://production_server (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at https://mirror_server (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL). It's very easy to find Apache solutions for http->https redirection , but for the life of me I can't do the opposite. Ideas? | This has not been tested but I think this should work using mod_rewrite RewriteEngine OnRewriteCond %{HTTPS} onRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/8371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
]
} |
8,435 | I'd like to get the Tree icon to use for a homegrown app. Does anyone know how to extract the images out as .icon files? I'd like both the 16x16 and 32x32, or I'd just do a screen capture. | In Visual Studio, choose "File Open..." then "File...". Then pick the Shell32.dll. A folder tree should be opened, and you will find the icons in the "Icon" folder. To save an Icon, you can right-click on the icon in the folder tree and choose "Export". | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/8435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733/"
]
} |
8,439 | I know there's a bug with conditional visibility and page breaks with SQL 2005, but I wonder if anyone has come up with a work around. I have a table that has a conditional visibility expression, and I need a page break at the end of the table. If I set the PageBreakAtEnd property to true. It is ignored no matter what. Remove the visibility condition and it works. If I place the table inside a rectangle with the conditional visibility on the table, and the page break on the table. Same result. The page break property is ignored. If I set the rectangle with the PageBreakAtEnd property and the table with the visibility condition, then I still get a page break even when the table isn't shown. Any other ideas on what to try? I'm almost at the point where I need a separate report rather than conditional visibility :( Edit: @Josh: That has the same problems. If the second table has conditional visibility it doesn't work. If it doesn't have the visibility expression, then I get the page break all the time. @ Erick: I really wanted that to be the answer but unfortunately it doesn't work. When the visibility expression evaluates to hidden, there's a big gap where the rectangles would be (which I can live with), and when it evaluates to visible, the page breaks still don't work. | Place two rectangles, one inside the other. Place your table inside the inner rectangle and set it to always be visible. Set the inner rectangle's Page Break to Insert After Rectangle. Set the outer rectangle's visibility to use your conditional expression. The page break and the conditional visibility are now separated, and the inner rectangle's page break won't be processed if it is not visible, but it will if it is visible. Edit : When I tried this, it did not appear to work in the Preview tab in Visual Studio, but it did work in the Print Preview and when I exported the report to PDF. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
]
} |
8,441 | I'm using .htaccess and mod_rewrite to point to files that reside behind the DocumentRoot. My folder structure looks like this: home/ webroot/ other_files/ I have a .htaccess file in webroot with the following content: RewriteEngine onRewriteRule ^(.*)$ /home/other_files/$1 If I try to access http://example.com/file.html I receive the following error: The requested URL /home/other_files/file.html was not found on this server. Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction? | I believe you need to add a section with <Directory "/home/other_files"> (options)</Directory> to your server configuration before apache will be able to serve anything from it. For an example, my DocumentRoot is /var/www but there is this section in the default available site: Alias /doc/ "/usr/share/doc/"<Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128</Directory> You could then rewrite a URL to go to /doc/ and the server would know where to get the files from. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57/"
]
} |
8,447 | From time to time I see an enum like the following: [Flags]public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8} I don't understand what exactly the [Flags] attribute does. Anyone have a good explanation or example they could post? | The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example: var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue; Note that the [Flags] attribute doesn't enable this by itself - all it does is allow a nice representation by the .ToString() method: enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }...var str1 = (Suits.Spades | Suits.Diamonds).ToString(); // "5"var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString(); // "Spades, Diamonds" It is also important to note that [Flags] does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment. Incorrect declaration: [Flags]public enum MyColors{ Yellow, // 0 Green, // 1 Red, // 2 Blue // 3} The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags. Here's an example of a correct declaration: [Flags]public enum MyColors{ Yellow = 1, Green = 2, Red = 4, Blue = 8} To retrieve the distinct values in your property, one can do this: if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)){ // Yellow is allowed...} or prior to .NET 4: if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow){ // Yellow is allowed...}if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green){ // Green is allowed...} Under the covers This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros: Yellow: 00000001 Green: 00000010 Red: 00000100 Blue: 00001000 Similarly, after you've set your property AllowedColors to Red, Green and Blue using the binary bitwise OR | operator, AllowedColors looks like this: myProperties.AllowedColors: 00001110 So when you retrieve the value you are actually performing bitwise AND & on the values: myProperties.AllowedColors: 00001110 MyColor.Green: 00000010 ----------------------- 00000010 // Hey, this is the same as MyColor.Green! The None = 0 value And regarding the use of 0 in your enumeration, quoting from MSDN: [Flags]public enum MyColors{ None = 0, ....} Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. You can find more info about the flags attribute and its usage at msdn and designing flags at msdn | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/8447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
]
} |
8,448 | Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept? | (Edit: a small Ocaml FP Koan to start things off) The Koan of Currying (A koan about food, that is not about food) A student came to Jacques Garrigue and said, "I do not understand what currying is good for." Jacques replied, "Tell me your favorite meal and your favorite dessert". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened ... until the next morning when he woke up and his stomach felt fine. My examples will cover using it for the reuse and encapsulation of code. This is fairly obvious once you look at these and should give you a concrete, simple example that you can think of applying in numerous situations. We want to do a map over a tree. This function could be curried and applied to each node if it needs more then one argument -- since we'd be applying the one at the node as it's final argument. It doesn't have to be curried, but writing another function (assuming this function is being used in other instances with other variables) would be a waste. type 'a tree = E of 'a | N of 'a * 'a tree * 'a treelet rec tree_map f tree = match tree with | N(x,left,right) -> N(f x, tree_map f left, tree_map f right) | E(x) -> E(f x)let sample_tree = N(1,E(3),E(4)let multiply x y = x * ylet sample_tree2 = tree_map (multiply 3) sample_tree but this is the same as: let sample_tree2 = tree_map (fun x -> x * 3) sample_tree So this simple case isn't convincing. It really is though, and powerful once you use the language more and naturally come across these situations. The other example with some code reuse as currying. A recurrence relation to create prime numbers . Awful lot of similarity in there: let rec f_recurrence f a seed n = match n with | a -> seed | _ -> let prev = f_recurrence f a seed (n-1) in prev + (f n prev)let rowland = f_recurrence gcd 1 7let cloitre = f_recurrence lcm 1 1let rowland_prime n = (rowland (n+1)) - (rowland n)let cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1 Ok, now rowland and cloitre are curried functions, since they have free variables, and we can get any index of it's sequence without knowing or worrying about f_recurrence. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
]
} |
8,451 | I want to create an allocator which provides memory with the following attributes: cannot be paged to disk. is incredibly hard to access through an attached debugger The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem. Updates Josh mentions using VirtualAlloc to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the VirtualLock function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem. //template<class _Ty>class LockedVirtualMemAllocator : public std::allocator<_Ty>{public: template<class _Other> LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&) { // assign from a related LockedVirtualMemAllocator (do nothing) return (*this); } template<class Other> struct rebind { typedef LockedVirtualMemAllocator<Other> other; }; pointer allocate( size_type _n ) { SIZE_T allocLen = (_n * sizeof(_Ty)); DWORD allocType = MEM_COMMIT; DWORD allocProtect = PAGE_READWRITE; LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect ); if ( pMem != NULL ) { ::VirtualLock( pMem, allocLen ); } return reinterpret_cast<pointer>( pMem ); } pointer allocate( size_type _n, const void* ) { return allocate( _n ); } void deallocate(void* _pPtr, size_type _n ) { if ( _pPtr != NULL ) { SIZE_T allocLen = (_n * sizeof(_Ty)); ::SecureZeroMemory( _pPtr, allocLen ); ::VirtualUnlock( _pPtr, allocLen ); ::VirtualFree( _pPtr, 0, MEM_RELEASE ); } }}; and is used //a memory safe std::string typedef std::basic_string<char, std::char_traits<char>, LockedVirtualMemAllocato<char> > modulestring_t; Ted Percival mentions mlock, but I have no implementation of that yet. I found Practical Cryptography by Neil Furguson and Bruce Schneier quite helpful as well. | You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way. Even if you could somehow completely lock down your process and guarantee that the OS would never allow anyone else to access your process, you still don't have full protection. The entire OS could be running in a virtual machine, which could be paused and inspected at any time. You cannot protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
]
} |
8,452 | I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands? | Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does. You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so: public static class CommandBank{ /// Command definition for Closing a window public static RoutedUICommand CloseWindow { get; private set; } /// Static private constructor, sets up all application wide commands. static CommandBank() { CloseWindow = new RoutedUICommand(); CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt)); // ... } Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above: /// Closes the window provided as a parameterpublic static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e){ ((Window)e.Parameter).Close();}/// Allows a Command to execute if the CommandParameter is not a null valuepublic static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e){ e.CanExecute = e.Parameter != null; e.Handled = true;} The second method there can even be shared with other Commands without me having to repeat it all over the place. Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close. public partial class SimpleWindow : Window{ private void WindowLoaded(object sender, RoutedEventArgs e) { // ... this.CommandBindings.Add( new CommandBinding( CommandBank.CloseWindow, CommandBank.CloseWindowExecute, CommandBank.CanExecuteIfParameterIsNotNull)); foreach (CommandBinding binding in this.CommandBindings) { RoutedCommand command = (RoutedCommand)binding.Command; if (command.InputGestures.Count > 0) { foreach (InputGesture gesture in command.InputGestures) { var iBind = new InputBinding(command, gesture); iBind.CommandParameter = this; this.InputBindings.Add(iBind); } } } // menuItemExit is defined in XAML menuItemExit.Command = CommandBank.CloseWindow; menuItemExit.CommandParameter = this; // ... } // ....} I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event. Let me know if you have any follow up questions. :) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/8452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
]
} |
8,472 | It looks like we'll be adding CAPTCHA support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here! We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense: http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs The advantage of this approach is that, for most people, the CAPTCHA won't ever be visible! However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky. I have written a traditional CAPTCHA control for ASP.NET which we can re-use. However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request. I've seen things like.. ASCII text captcha: \/\/(_)\/\/ math puzzles: what is 7 minus 3 times 2? trivia questions: what tastes better, a toad or a popsicle? Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based <noscript> compatible CAPTCHA if possible. Ideas? | A method that I have developed and which seems to work perfectly (although I probably don't get as much comment spam as you), is to have a hidden field and fill it with a bogus value e.g.: <input type="hidden" name="antispam" value="lalalala" /> I then have a piece of JavaScript which updates the value every second with the number of seconds the page has been loaded for: var antiSpam = function() { if (document.getElementById("antiSpam")) { a = document.getElementById("antiSpam"); if (isNaN(a.value) == true) { a.value = 0; } else { a.value = parseInt(a.value) + 1; } } setTimeout("antiSpam()", 1000);}antiSpam(); Then when the form is submitted, If the antispam value is still "lalalala", then I mark it as spam. If the antispam value is an integer, I check to see if it is above something like 10 (seconds). If it's below 10, I mark it as spam, if it's 10 or more, I let it through. If AntiSpam = A Integer If AntiSpam >= 10 Comment = Approved Else Comment = SpamElse Comment = Spam The theory being that: A spam bot will not support JavaScript and will submit what it sees If the bot does support JavaScript it will submit the form instantly The commenter has at least read some of the page before posting The downside to this method is that it requires JavaScript, and if you don't have JavaScript enabled, your comment will be marked as spam, however, I do review comments marked as spam, so this is not a problem. Response to comments @MrAnalogy: The server side approach sounds quite a good idea and is exactly the same as doing it in JavaScript. Good Call. @AviD: I'm aware that this method is prone to direct attacks as I've mentioned on my blog . However, it will defend against your average spam bot which blindly submits rubbish to any form it can find. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/8472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
]
} |
8,496 | I've moved from TFS to SVN (TortoiseSVN) with my current company. I really miss the "Shelve" feature of TFS. I've read various articles on how to "Shelve" with SVN, but I've read nothing that gives a very simple experience to "shelve" work. Ideally, I'd like extra items added to the TortoiseSVN context menu - "Shelve" & "Unshelve"."Shelve" would remove the current shelve-set, and upload the working directory under a suitable path defined by user options. "Unshelve" would merge the set with the working copy. Does something like this exist? Can anyone suggest any ways to "hack" this feature in the GUI? Note: The following link doesn't really achieve the user experience I was looking for: Shelving Subversion One of the greatest things about TFS Shelve is how easy it is to use... | I don't believe that SVN has this feature built into the server product. I also don't believe anything like this emulated in any clients that I have used, including TortoiseSVN. To get around this problem, I have resorted to using a DVCS such as Git or Mercurial , to allow me to branch/merge/shelve locally before pushing the content back to SVN. It's arguably a bit of a kludge, but it works really well. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
]
} |
8,546 | I need to try to lock on an object, and if its already locked just continue (after time out, or without it). The C# lock statement is blocking. | Ed's got the right function for you. Just don't forget to call Monitor.Exit() . You should use a try-finally block to guarantee proper cleanup. if (Monitor.TryEnter(someObject)){ try { // use object } finally { Monitor.Exit(someObject); }} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/8546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/195/"
]
} |
8,566 | First off, this is a question about a desktop application using Windows Forms, not an ASP.NET question. I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following... otherForm.Controls["nameOfControl"].Visible = false; It doesn't work the way I would expect. I end up with an exception thrown from Main . However, if I make the controls public instead of private , I can then access them directly, as so... otherForm.nameOfControl.Visible = false; But is that the best way to do it? Is making the controls public on the other form considered "best practice"? Is there a "better" way to access controls on another form? Further Explanation: This is actually a sort of follow-up to another question I asked, Best method for creating a “tree-view preferences dialog” type of interface in C#? . The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface. Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.) | Instead of making the control public, you can create a property that controls its visibility: public bool ControlIsVisible{ get { return control.Visible; } set { control.Visible = value; }} This creates a proper accessor to that control that won't expose the control's whole set of properties. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/551/"
]
} |
8,569 | I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off. Do you have any best practices , tipps or major DO NOTs for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate... | Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on: MyProject / src / main / resources / spring / datasource.xml - My single data source bean. persistence.xml - My DAOs/Repositories. Depends on datasource.xml beans. services.xml - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on persistence.xml beans. controllers.xml - My Spring MVC controllers. Depends on services.xml beans. views.xml - My view implementations. This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you. In my (limited) experience, I've seen this approach yeild the following benefits: Clearer architecture Clearly named context files gives those unfamiliar with your project structure a reasonable place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier. Helps domain design If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples: Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to services.xml , or put them in their own transactionPolicy.xml ? Talk it over with your team. Should your transaction policy be pluggable? Add Acegi/Spring Security beans to your controllers.xml file, or create a security.xml context file? Do you have different security requirements for different deployments/environments? Integration testing You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only datasource.xml and persistence.xml beans). Specifically, you can annotate an integration test class as such: @ContextConfiguration(locations = { "/spring/datasource.xml" , "/spring/persistence.xml" }) Works well with Spring IDE's Beans Graph Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's Beans Graph . I've used this before to give new team members a high-level overview of our application's organization. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/8569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834/"
]
} |
8,625 | I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add typed properties, so that the "value" returned is always of the type that I want it to be. The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion). So, I have created a class which is (roughly) this: public class TypedProperty<DataType> : Property{ public DataType TypedValue { get { // Having problems here! } set { base.Value = value.ToString();} }} So the question is: Is there a "generic" way to convert from string back to a primitive? I can't seem to find any generic interface that links the conversion across the board (something like ITryParsable would have been ideal!). | I am not sure whether I understood your intentions correctly, but let's see if this one helps. public class TypedProperty<T> : Property where T : IConvertible{ public T TypedValue { get { return (T)Convert.ChangeType(base.Value, typeof(T)); } set { base.Value = value.ToString();} }} | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/8625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
]
} |
8,626 | Is there anyplace where one can download a virtual machine containing a working install of some Linux distro with Globus Toolkit and some development tools (Java) for testing purposes? A real deployment of a grid is more complicated but I just need something portable, for development. | I am not sure whether I understood your intentions correctly, but let's see if this one helps. public class TypedProperty<T> : Property where T : IConvertible{ public T TypedValue { get { return (T)Convert.ChangeType(base.Value, typeof(T)); } set { base.Value = value.ToString();} }} | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/8626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
]
} |
8,676 | Now that .NET v3.5 SP1 has been released (along with VS2008 SP1), we now have access to the .NET entity framework. My question is this. When trying to decide between using the Entity Framework and LINQ to SQL as an ORM, what's the difference? The way I understand it, the Entity Framework (when used with LINQ to Entities) is a 'big brother' to LINQ to SQL? If this is the case - what advantages does it have? What can it do that LINQ to SQL can't do on its own? | LINQ to SQL only supports 1 to 1 mapping of database tables, views, sprocs and functions available in Microsoft SQL Server. It's a great API to use for quick data access construction to relatively well designed SQL Server databases. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5. LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1. This is a good introductory article on MSDN: Introducing LINQ to Relational Data | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/8676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475/"
]
} |
8,681 | If you're using Opera 9.5x you may notice that our client-side JQuery.Validate code is disabled here at Stack Overflow. function initValidation() { if (navigator.userAgent.indexOf("Opera") != -1) return; $("#post-text").rules("add", { required: true, minlength: 5 });} That's because it generates an exception in Opera! Of course it works in every other browser we've tried. I'm starting to seriously, seriously hate Opera. This is kind of a bummer because without proper client-side validation some of our requests will fail. We haven't had time to put in complete server-side messaging when data is incomplete, so you may see the YSOD on Opera much more than other browsers , if you forget to fill out all the fields on the form. Any Opera-ites want to uncomment those lines (they're on core Ask & Answer pages like this one -- just View Source and search for "Opera" ) and give it a go? | turns out the problem was in the { debug : true } option for the JQuery.Validate initializer. With this removed, things work fine in Opera. Thanks to Jörn Zaefferer for helping us figure this out! Oh, and the $50 will be donated to the JQuery project. :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
]
} |
8,692 | What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website? | libxml2 has a number of advantages: Compliance to the spec Active development and a community participation Speed. This is really a python wrapper around a C implementation. Ubiquity. The libxml2 library is pervasive and thus well tested. Downsides include: Compliance to the spec . It's strict. Things like default namespace handling are easier in other libraries. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic. If you are doing simple path selection, stick with ElementTree ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2. Sample of libxml2 XPath Use import libxml2doc = libxml2.parseFile("tst.xml")ctxt = doc.xpathNewContext()res = ctxt.xpathEval("//*")if len(res) != 2: print "xpath query: wrong node set size" sys.exit(1)if res[0].name != "doc" or res[1].name != "foo": print "xpath query: wrong node set value" sys.exit(1)doc.freeDoc()ctxt.xpathFreeContext() Sample of ElementTree XPath Use from elementtree.ElementTree import ElementTreemydoc = ElementTree(file='tst.xml')for e in mydoc.findall('/foo/bar'): print e.get('title').text | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/8692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
8,742 | I'm trying to rebuild an old metronome application that was originally written using MFC in C++ to be written in .NET using C#. One of the issues I'm running into is getting the timer to "tick" accurately enough. For example, assuming an easy BPM (beats per minute) of 120, the timer should tick every .5 seconds (or 500 milliseconds). Using this as the basis for the ticks, however, isn't entirely accurate as .NET only guarantees that your timer will not tick before the elapsed time has passed. Currently, to get around this for the same 120 BPM example used above, I am setting the ticks to something like 100 milliseconds and only playing the click sound on every 5th timer tick. This does improve the accuracy quite a bit, but if feels like a bit of a hack. So, what is the best way to get accurate ticks? I know there are more timers available than the windows forms timer that is readily available in Visual Studio, but I'm not really familiar with them. | There are three timer classes called 'Timer' in .NET. It sounds like you're using the Windows Forms one, but actually you might find the System.Threading.Timer class more useful - but be careful because it calls back on a pool thread, so you can't directly interact with your form from the callback. Another approach might be to p/invoke to the Win32 multimedia timers - timeGetTime, timeSetPeriod, etc. A quick google found this, which might be useful http://www.codeproject.com/KB/miscctrl/lescsmultimediatimer.aspx 'Multimedia' (timer) is the buzz-word to search for in this context. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
]
} |
8,790 | I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date. So I know I need to import the utils build file. <import file="../utils/build/build.xml" /> Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file <property name="baseDirUpOne" location=".." /> <import file="${baseDirUpOne}/utils/build/build.xml" /> So now that ive solved my import problem I need to call the task, well that should be easy right: <antcall target="utils.package" /> note that in the above, utils is the project name of ../utils/build/build.xml the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially: <antcall target="utils.package" runat="../utils/build" /> The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? | I've got something similar set up: I have a main Ant build.xml which calls a separate build.xml that takes care of building my tests. This is how I do it: <target name="build-tests"> <subant target="build"> <fileset dir="${test.home}" includes="build.xml"/> </subant></target> The trick is to use subant instead of antcall . You don't have to import the other build file. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/8790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
]
} |
8,800 | So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable? public class TokenTree{ public TokenTree() { /* I must admit to not fully understanding this, * I got it from msdn. As far as I can tell, IDictionary is an * interface, and Dictionary is the default implementation of * that interface, right? */ SubPairs = new Dictionary<string, string>(); } public string Key; public string Value; public IDictionary<string, string> SubPairs;} It's only really a simple shunt for passing around data. | There is an actual Data Type called KeyValuePair, use like this KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue"); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/8800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
]
} |
8,864 | Is there a difference between NULL and null in PHP? Sometimes they seem to be interchangeable and sometimes not. edit: for some reason when I read the documentation linked to in the answer (before posting this question) I read it as "case sensitive" instead of "case insensitive" which was the whole reason I posted this question in the first place... | Null is case insensitive. From the documentation : There is only one value of type null, and that is the case-insensitive keyword NULL. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/8864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
]
} |
8,876 | Are there any free tools that implement evidence-based scheduling like Joel talks about ? There is FogBugz, of course, but I am looking for a simple and free tool that can apply EBS on some tasks that I give estimates (and actual times which are complete) for. | FogBugz is free for up to 2 users by the way. As far I know this is the only tool that does EBS. See here http://www.workhappy.net/2008/06/get-fogbugz-for.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/8876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
]
} |
8,896 | Does anyone know IF , WHEN or HOW I can get Memcached running on a Windows 64bit environment? I'm setting up a new hosting solution and would much prefer to run a 64bit OS, and since it's an ASP.Net MVC solution with SQL Server DB, the OS is either going to be Windows Server 2003 or (hopefully!) 2008. I know that this could spill over into a debate regarding 32bit vs 64bit on servers, but let's just say that my preference is 64bit and that I have some very good reasons. So far, I've tried a number of options and found a bit of help related to getting this up on a 32bit machine (and succeeded I might add), but since the original Windows port is Win32 specific, this is hardly going to help when installing as a service on x64. It also has a dependency on the libevent for which I can only get a Win32 compiled version. I suspect that simply loading all this up in C++ and hitting "compile" (for 64bit) wouldn't work, not least because of the intricate differences in 32 and 64bit architectures, but I'm wondering if anyone is working on getting this off the ground? Unfortunately, my expertise lie in managed code (C#) only, otherwise I would try and take this on myself, but I can't believe I'm the only guy out there trying to get memcached running on a 64 bit Windows server....am I? Update Yes I'm afraid I'm still looking for an answer to this - all my efforts (with my pathetic C++ skills) to make a stable build have failed - I've trashed one server and 3 VM's just trying it out so now I turn to the real experts.Is anyone planning on porting this to 64bit? Or are you really suggesting that I use MS Velocity instead? I shudder at the thought. Update:@Lars - I do use Enyim actually - it's very good, but what you're referring to is a client, rather than the server part. @DannySmurf - I've only been able to install it as a service on a 32 bit OS. 64 bit OS rejects the installation of this Win32 service. Of course yes, lots of Win32 code works seamlessly on x64 architecture, hence you can run 32bit apps (like Office for instance) or games on Vista/XP 64 etc, but this doesn't translate directly when it comes to services. I'm no expert, I suspect that it has to do with the syncs or eventing that services need to subscribe to, and I suspect that 64 and 32 don't play nicely. I'm happy to be corrected on any of this, but to answer your question - yes I have tried. @OJ - thanks very much for the straight-forward response. I thought as much, but wasn't sure if anyone else had suggestions or had already gone down this route. Maybe when StackOverflow is LIVE, then more people will respond and let me know if this is something being looked into, and although I can try and compile it myself - I simply can't "trust" (with my C++ experience level) that it would provide "Enterprise Level" reliability in such a crucial component of large scalable solutions. I think it would need educated intervention rather than my unsanitised experimental approach before I could be confident. One little oversight on my part, could bring the site down. Oh well... till next time. | North Scale labs have released a build of memcached 1.4.4 for Windows x64: http://blog.couchbase.com/memcached-windows-64-bit-pre-release-available http://labs.northscale.com/memcached-packages/ UPDATE: they have recently released Memcached Server - still FREE but enhanced distro with clustering, web-based admin/stats UI etc. (I'm not related to them in any way) Check it out at http://northscale.com/products/memcached.html and download at: http://www.northscale.com/download.php?a=d UPDATE 2: NorthScale Memcached is no longer available as a standalone download. Now they have made it part of their commercial No-SQL DB offering called Membase. It can be configured to run in Memcached-only mode (i.e. without persistence) and there's a 100% free version too. Check it out here: http://www.membase.org/downloads UPDATE 3: MemBase has slept with CouchDB and produced a hybrid product offering, called CouchBase. They still do offer a free "Community" version at http://www.couchbase.com/download | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/8896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1107/"
]
} |
8,941 | Is there a way to enforce/limit the types that are passed to primitives? (bool, int, string, etc.) Now, I know you can limit the generic type parameter to a type or interface implementation via the where clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from object before someone says! :P). So, my current thoughts are to just grit my teeth and do a big switch statement and throw an ArgumentException on failure. EDIT 1: Just to clarify: The code definition should be like this: public class MyClass<GenericType> .... And instantiation: MyClass<bool> = new MyClass<bool>(); // LegalMyClass<string> = new MyClass<string>(); // LegalMyClass<DataSet> = new MyClass<DataSet>(); // IllegalMyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!) EDIT 2 @Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type. This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as Size ). Interesting problem no? :) Here it is: where T: struct Taken from MSDN . I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code. What do you guys think? The sad news is I am working in Framework 2!! :D EDIT 3 This was so simple following on from Jon Limjaps Pointer .. So simple I almost want to cry, but it's great because the code works like a charm! So here is what I did (you'll laugh!): Code added to the generic class bool TypeValid(){ // Get the TypeCode from the Primitive Type TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType)); // All of the TypeCode Enumeration refer Primitive Types // with the exception of Object and Empty (Null). // Since I am willing to allow Null Types (at this time) // all we need to check for is Object! switch (code) { case TypeCode.Object: return false; default: return true; }} Then a little utility method to check the type and throw an exception, private void EnforcePrimitiveType(){ if (!TypeValid()) throw new InvalidOperationException( "Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name + "' - this Class is Designed to Work with Primitive Data Types Only.");} All that then needs to be done is to call EnforcePrimitiveType() in the classes constructors. Job done! :-) The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like FxCop (which we don't use at work). Special thanks to Jon Limjap on this one! | public class Class1<GenericType> where GenericType : struct{} This one seemed to do the job.. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/8941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
]
} |
8,948 | Is there a maintained package I can use to retrieve and set MP3 ID3 metadata using Python? | I used eyeD3 the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to install using pip or download the tar and execute python setup.py install from the source folder. Relevant examples from the website are below. Reading the contents of an mp3 file containing either v1 or v2 tag info: import eyeD3 tag = eyeD3.Tag() tag.link("/some/file.mp3") print tag.getArtist() print tag.getAlbum() print tag.getTitle() Read an mp3 file (track length, bitrate, etc.) and access it's tag: if eyeD3.isMp3File(f): audioFile = eyeD3.Mp3AudioFile(f) tag = audioFile.getTag() Specific tag versions can be selected: tag.link("/some/file.mp3", eyeD3.ID3_V2) tag.link("/some/file.mp3", eyeD3.ID3_V1) tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION) # The default. Or you can iterate over the raw frames: tag = eyeD3.Tag() tag.link("/some/file.mp3") for frame in tag.frames: print frame Once a tag is linked to a file it can be modified and saved: tag.setArtist(u"Cro-Mags") tag.setAlbum(u"Age of Quarrel") tag.update() If the tag linked in was v2 and you'd like to save it as v1: tag.update(eyeD3.ID3_V1_1) Read in a tag and remove it from the file: tag.link("/some/file.mp3") tag.remove() tag.update() Add a new tag: tag = eyeD3.Tag() tag.link('/some/file.mp3') # no tag in this file, link returned False tag.header.setVersion(eyeD3.ID3_V2_3) tag.setArtist('Fugazi') tag.update() | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/8948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
]
} |
8,952 | Generally, how bad of a performance hit is storing a file in a database (specifically mssql) as opposed to the file system? I can't come up with a reason outside of application portability that I would want to store my files as varbinaries in SQL Server. | Have a look at this answer: Storing Images in DB - Yea or Nay? Essentially, the space and performance hit can be quite big, depending on the number of users. Also, keep in mind that Web servers are cheap and you can easily add more to balance the load, whereas the database is the most expensive and hardest to scale part of a web architecture usually. There are some opposite examples (e.g., Microsoft Sharepoint), but usually, storing files in the database is not a good idea. Unless possibly you write desktop apps and/or know roughly how many users you will ever have, but on something as random and unexpectable like a public web site, you may pay a high price for storing files in the database. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/8952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/565/"
]
} |
8,966 | I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem. In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0. Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different. Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there? | To access WIA, you'll need to add a reference to the COM library, "Microsoft Windows Image Acquisition Library v2.0" (wiaaut.dll).add a "using WIA;" const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";CommonDialogClass wiaDiag = new CommonDialogClass();WIA.ImageFile wiaImage = null;wiaImage = wiaDiag.ShowAcquireImage( WiaDeviceType.UnspecifiedDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, wiaFormatJPEG, true, true, false);WIA.Vector vector = wiaImage.FileData; (System.Drawing) Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));i.Save(filename) Thats a basic way, works with my flatbed/doc feeder. If you need more than one document/page at a time though, there is probably a better way to do it (from what I could see, this only handles one image at a time, although I'm not entirely sure). While it is a WIA v1 doc, Scott Hanselman's Coding4Fun article on WIA does contain some more info on how to do it for multiple pages, I think (I'm yet to go further than that myself) If its for a paperless office system, you might want also check out MODI (Office Document Imaging) to do all the OCR for you. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/8966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124/"
]
} |
9,009 | This snippet of Perl code in my program is giving the wrong result. $condition ? $a = 2 : $a = 3 ;print $a; No matter what the value of $condition is, the output is always 3, how come? | This is explained in the Perl documentation . Because of Perl operator precedence the statement is being parsed as ($condition ? $a= 2 : $a ) = 3 ; Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition. When $condition is true this means ($a=2)=3 giving $a=3 When $condition is false this means ($a)=3 giving $a=3 The correct way to write this is $a = ( $condition ? 2 : 3 );print $a; We got bitten by this at work, so I am posting here hoping others will find it useful. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/9009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
]
} |
9,018 | I am working at a client site where there is a proxy server ( HTTP ) in place. If I do a hard reset of the emulator it forgets network connection settings for the emulator and settings in the hosted Windows Mobile OS. If I 'save state and exit' it will lose all of these settings. I need to do hard resets regularly which means that I lose this information and spend a lot of time setting: The emulators associated network card DNS servers for network card in the WM OS. Proxy servers in connection settings of WM OS. How can I make my life easier? Can I save this as defaults in the emulator, or create an installer easily? | This is explained in the Perl documentation . Because of Perl operator precedence the statement is being parsed as ($condition ? $a= 2 : $a ) = 3 ; Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition. When $condition is true this means ($a=2)=3 giving $a=3 When $condition is false this means ($a)=3 giving $a=3 The correct way to write this is $a = ( $condition ? 2 : 3 );print $a; We got bitten by this at work, so I am posting here hoping others will find it useful. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/9018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
]
} |
9,033 | This came to my mind after I learned the following from this question : where T : struct We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc. Some of us even mastered the stuff like Generics , anonymous types , lambdas , LINQ , ... But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know? Here are the revealed features so far: Keywords yield by Michael Stum var by Michael Stum using() statement by kokos readonly by kokos as by Mike Stone as / is by Ed Swangren as / is (improved) by Rocketpants default by deathofrats global:: by pzycoman using() blocks by AlexCuse volatile by Jakub Šturc extern alias by Jakub Šturc Attributes DefaultValueAttribute by Michael Stum ObsoleteAttribute by DannySmurf DebuggerDisplayAttribute by Stu DebuggerBrowsable and DebuggerStepThrough by bdukes ThreadStaticAttribute by marxidad FlagsAttribute by Martin Clarke ConditionalAttribute by AndrewBurns Syntax ?? (coalesce nulls) operator by kokos Number flaggings by Nick Berardi where T:new by Lars Mæhlum Implicit generics by Keith One-parameter lambdas by Keith Auto properties by Keith Namespace aliases by Keith Verbatim string literals with @ by Patrick enum values by lfoust @variablenames by marxidad event operators by marxidad Format string brackets by Portman Property accessor accessibility modifiers by xanadont Conditional (ternary) operator ( ?: ) by JasonS checked and unchecked operators by Binoj Antony implicit and explicit operators by Flory Language Features Nullable types by Brad Barker Anonymous types by Keith __makeref __reftype __refvalue by Judah Himango Object initializers by lomaxx Format strings by David in Dakota Extension Methods by marxidad partial methods by Jon Erickson Preprocessor directives by John Asbeck DEBUG pre-processor directive by Robert Durgin Operator overloading by SefBkn Type inferrence by chakrit Boolean operators taken to next level by Rob Gough Pass value-type variable as interface without boxing by Roman Boiko Programmatically determine declared variable type by Roman Boiko Static Constructors by Chris Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacid __arglist by Zac Bowling Visual Studio Features Select block of text in editor by Himadri Snippets by DannySmurf Framework TransactionScope by KiwiBastard DependantTransaction by KiwiBastard Nullable<T> by IainMH Mutex by Diago System.IO.Path by ageektrapped WeakReference by Juan Manuel Methods and Properties String.IsNullOrEmpty() method by KiwiBastard List.ForEach() method by KiwiBastard BeginInvoke() , EndInvoke() methods by Will Dean Nullable<T>.HasValue and Nullable<T>.Value properties by Rismo GetValueOrDefault method by John Sheehan Tips & Tricks Nice method for event handlers by Andreas H.R. Nilsson Uppercase comparisons by John Access anonymous types without reflection by dp A quick way to lazily instantiate collection properties by Will JavaScript-like anonymous inline-functions by roosteronacid Other netmodules by kokos LINQBridge by Duncan Smart Parallel Extensions by Joel Coehoorn | This isn't C# per se, but I haven't seen anyone who really uses System.IO.Path.Combine() to the extent that they should. In fact, the whole Path class is really useful, but no one uses it! I'm willing to bet that every production app has the following code, even though it shouldn't: string path = dir + "\\" + fileName; | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/9033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
]
} |
9,081 | How do I grep and show the preceding and following 5 lines surrounding each matched line? | For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. grep -B 3 -A 2 foo README.txt If you want the same number of lines before and after you can use -C num . grep -C 3 foo README.txt This will show 3 lines before and 3 lines after. | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/9081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
9,104 | I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes... I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL. I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now. | What you want is a bookmarklet they are easy to create and should work in most major browsers. Edit: Stack overflow seems not to allow creating bookmarklets in the context of the site, basically you can create a new bookmark and type the following in the location field javascript:window.location='http://www.google.com/search?q='+Date() to get a bookmarklet that searches google for the current date. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/9104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.