Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
When used like this: ``` import static com.showboy.Myclass; public class Anotherclass{} ``` what's the difference between `import static com.showboy.Myclass` and `import com.showboy.Myclass`?
See [Documentation](http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html) > The static import declaration is > analogous to the normal import > declaration. Where the normal import > declaration imports classes from > packages, allowing them to be used > without package qualification, the > static import declaration imports > static members from classes, allowing > them to be used without class > qualification. > > So when should you use static import? > Very sparingly! Only use it when you'd > otherwise be tempted to declare local > copies of constants, or to abuse > inheritance (the Constant Interface > Antipattern). In other words, use it > when you require frequent access to > static members from one or two > classes. If you overuse the static > import feature, it can make your > program unreadable and unmaintainable, > polluting its namespace with all the > static members you import. Readers of > your code (including you, a few months > after you wrote it) will not know > which class a static member comes > from. Importing all of the static > members from a class can be > particularly harmful to readability; > if you need only one or two members, > import them individually. Used > appropriately, static import can make > your program more readable, by > removing the boilerplate of repetition > of class names.
There is no difference between those two imports you state. You can, however, use the static import to allow unqualified access to static members of other classes. Where I used to have to do this: ``` import org.apache.commons.lang.StringUtils; . . . if (StringUtils.isBlank(aString)) { . . . ``` I can do this: ``` import static org.apache.commons.lang.StringUtils.isBlank; . . . if (isBlank(aString)) { . . . ``` You can see more in the [documentation](https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html).
What does the "static" modifier after "import" mean?
[ "", "java", "modifier", "static-import", "" ]
Why does the JavaScript function `encodeURIComponent` encode spaces to the hex Unicode value `%20` instead of `+`. Should URI parameters not spaces to `+`? ­­­­­­­­­­­­­­­­­­­­­­­­­­­
Spaces encode to %20, I believe that's their ASCII character code. However, developers have taken a shine to encoding spaces to + because it generates URLs that are readable and typeable by human beings.
The + is not recognised as a space in all uses of a URI for example try using this link:- mailto:bloke@somewhere?subject=Hello+World The subject line still has the + whereas:- mailto:bloke@somewhere?subject=Hello%20World works.
Encoding spaces with the javascript encodeURIComponent function
[ "", "javascript", "" ]
Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in `Foo **`) in C++?
Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns. ``` #include <iostream> using namespace std; struct Foo { int a; }; void CreateFoo(Foo** p) { *p = new Foo(); (*p)->a = 12; } int main(int argc, char* argv[]) { Foo* p = NULL; CreateFoo(&p); cout << p->a << endl; delete p; return 0; } ``` This will print ``` 12 ``` But there are several other useful usages as in the following example to iterate an array of strings and print them to the standard output. ``` #include <iostream> using namespace std; int main(int argc, char* argv[]) { const char* words[] = { "first", "second", NULL }; for (const char** p = words; *p != NULL; ++p) { cout << *p << endl; } return 0; } ```
IMO most common usage is to pass reference to pointer variable ``` void test(int ** var) { ... } int *foo = ... test(&foo); ``` You can create multidimensional jagged array using double pointers: ``` int ** array = new *int[2]; array[0] = new int[2]; array[1] = new int[3]; ```
To what use is multiple indirection in C++?
[ "", "c++", "pointers", "" ]
Is there a way to prevent VS2008 creating browse info file files for C++ projects. I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed. EDIT - it's also needed for go to declaration/definition
There is a registry key for this as well: `[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++]` Intellisense ON ``` "IntellisenseOptions"=dword:00000000 ``` Intellisense OFF ``` "IntellisenseOptions"=dword:00000007 ``` Intellisense ON - NO Background UPDATE ``` "IntellisenseOptions"=dword:00000005 ``` More flags are available and you can [Control Intellisense through Macros](http://blogs.msdn.com/vcblog/archive/2007/11/19/controlling-intellisense-through-macros.aspx) as well. ``` ISENSE_NORMAL = 0 'normal (Intellisense On) ISENSE_NOBG = &H1 'no bg parsing (Intellisense Updating Off - although NCB file will be opened r/w and repersisted at shutdown) ISENSE_NOQUERY = &H2 'no queries (don't run any ISense queries) ISENSE_NCBRO = &H4 'no saving of NCB (must be set before opening NCB, doesn't affect updating or queries, just persisting of NCB) ISENSE_OFF = &H7 ```
In the project properties, you will find the browse information under: Configuration Properties -> C/C++ -> Browse Information Just tell it not to generate browse information. All it is used for is quickly browsing between code components (like using 'Go to Definition') and so forth. I personally like being able to quickly jump between the components, but if it is adding unnecessary time to your compile don't worry about turning it off.
Prevent visual studio creating browse info (.ncb) files
[ "", "c++", "visual-studio", "visual-studio-2008", "" ]
I'm using the Excel interop in C# (`ApplicationClass`) and have placed the following code in my finally clause: ``` while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { } excelSheet = null; GC.Collect(); GC.WaitForPendingFinalizers(); ``` Although this kind of works, the `Excel.exe` process is still in the background even after I close Excel. It is only released once my application is manually closed. What am I doing wrong, or is there an alternative to ensure interop objects are properly disposed of?
Excel does not quit because your application is still holding references to COM objects. **I guess you're invoking at least one member of a COM object without assigning it to a variable.** For me it was the *excelApp.Worksheets* object which I directly used without assigning it to a variable: ``` Worksheet sheet = excelApp.Worksheets.Open(...); ... Marshal.ReleaseComObject(sheet); ``` I didn't know that internally C# created a wrapper for the **Worksheets** COM object which didn't get released by my code (because I wasn't aware of it) and was the cause why Excel was not unloaded. I found the solution to my problem on [this page](http://www.velocityreviews.com/forums/showpost.php?s=f87f0674feda4442dcbd40019cbca65b&p=528575&postcount=2), which also has a nice rule for the usage of COM objects in C#: > Never use two dots with COM objects. --- So with this knowledge the right way of doing the above is: ``` Worksheets sheets = excelApp.Worksheets; // <-- The important part Worksheet sheet = sheets.Open(...); ... Marshal.ReleaseComObject(sheets); Marshal.ReleaseComObject(sheet); ``` **POST MORTEM UPDATE:** I want every reader to read this answer by Hans Passant very carefully as it explains the trap I and lots of other developers stumbled into. When I wrote this answer years ago I didn't know about the effect the debugger has to the garbage collector and drew the wrong conclusions. I keep my answer unaltered for the sake of history but please read this link and **don't** go the way of "the two dots": [Understanding garbage collection in .NET](https://stackoverflow.com/questions/17130382/understanding-garbage-collection-in-net/17131389#17131389) and [Clean up Excel Interop Objects with IDisposable](https://stackoverflow.com/questions/25134024/clean-up-excel-interop-objects-with-idisposable/25135685#25135685)
You can actually release your Excel Application object cleanly, but you do have to take care. The advice to maintain a named reference for absolutely every COM object you access and then explicitly release it via `Marshal.FinalReleaseComObject()` is correct in theory, but, unfortunately, very difficult to manage in practice. If one ever slips anywhere and uses "two dots", or iterates cells via a `for each` loop, or any other similar kind of command, then you'll have unreferenced COM objects and risk a hang. In this case, there would be no way to find the cause in the code; you would have to review all your code by eye and hopefully find the cause, a task that could be nearly impossible for a large project. The good news is that you do not actually have to maintain a named variable reference to every COM object you use. Instead, call `GC.Collect()` and then `GC.WaitForPendingFinalizers()` to release all the (usually minor) objects to which you do not hold a reference, and then explicitly release the objects to which you do hold a named variable reference. You should also release your named references in reverse order of importance: range objects first, then worksheets, workbooks, and then finally your Excel Application object. For example, assuming that you had a Range object variable named `xlRng`, a Worksheet variable named `xlSheet`, a Workbook variable named `xlBook` and an Excel Application variable named `xlApp`, then your cleanup code could look something like the following: ``` // Cleanup GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.FinalReleaseComObject(xlRng); Marshal.FinalReleaseComObject(xlSheet); xlBook.Close(Type.Missing, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(xlBook); xlApp.Quit(); Marshal.FinalReleaseComObject(xlApp); ``` In most code examples you'll see for cleaning up COM objects from .NET, the `GC.Collect()` and `GC.WaitForPendingFinalizers()` calls are made TWICE as in: ``` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); ``` This should not be required, however, unless you are using Visual Studio Tools for Office (VSTO), which uses finalizers that cause an entire graph of objects to be promoted in the finalization queue. Such objects would not be released until the *next* garbage collection. However, if you are not using VSTO, you should be able to call `GC.Collect()` and `GC.WaitForPendingFinalizers()` just once. I know that explicitly calling `GC.Collect()` is a no-no (and certainly doing it twice sounds very painful), but there is no way around it, to be honest. Through normal operations you will generate hidden objects to which you hold no reference that you, therefore, cannot release through any other means other than calling `GC.Collect()`. This is a complex topic, but this really is all there is to it. Once you establish this template for your cleanup procedure you can code normally, without the need for wrappers, etc. :-) I have a tutorial on this here: [Automating Office Programs with VB.Net / COM Interop](http://www.xtremevbtalk.com/showthread.php?t=160433) It's written for VB.NET, but don't be put off by that, the principles are exactly the same as when using C#.
How do I properly clean up Excel interop objects?
[ "", "c#", "excel", "interop", "com-interop", "" ]
I'm trying to use CSS (**under `@media print`**) and JavaScript to print a one-page document with a given piece of text made as large as possible while still fitting inside a given width. The length of the text is not known beforehand, so simply using a fixed-width font is not an option. To put it another way, I'm looking for proper resizing, so that, for example, "IIIII" would come out in a much larger font size than "WWWWW" because "I" is much skinnier than "W" in a variable-width font. The closest I've been able to get with this is using JavaScript to try various font sizes until the `clientWidth` is small enough. **This works well enough for screen media, but when you switch to print media**, is there any guarantee that the 90 DPI I appear to get on my system (i.e., I put the margins to 0.5in either side, and for a text resized so that it fits just within that, I get about 675 for `clientWidth`) will be the same anywhere else? How does a browser decide what DPI to use when converting from pixel measurements? Is there any way I can access this information using JavaScript? I would love it if this were just a CSS3 feature (`font-size:max-for-width(7.5in)`) but if it is, I haven't been able to find it.
Here's some code I ended up using, in case someone might find it useful. All you need to do is make the outer DIV the size you want in inches. ``` function make_big(id) // must be an inline element inside a block-level element { var e = document.getElementById(id); e.style.whiteSpace = 'nowrap'; e.style.textAlign = 'center'; var max = e.parentNode.scrollWidth - 4; // a little padding e.style.fontSize = (max / 4) + 'px'; // make a guess, then we'll use the resulting ratio e.style.fontSize = (max / (e.scrollWidth / parseFloat(e.style.fontSize))) + 'px'; e.style.display = 'block'; // so centering takes effect } ```
The CSS font-size property accepts [length units](http://htmlhelp.com/reference/css/units.html#length) that include absolute measurements in inches or centimeters: > Absolute length units are highly dependent on the output medium, and > so are less useful than relative units. The following absolute units > are available: > > * in (inches; 1in=2.54cm) > * cm (centimeters; 1cm=10mm) > * mm (millimeters) > * pt (points; 1pt=1/72in) > * pc (picas; 1pc=12pt) Since you don't know how many characters your text is yet, you may need to use a combination of javascript and CSS in order to dynamically set the font-size property correctly. For example, take the length of the string in characters, and divide 8.5 (assuming you're expecting US letter size paper) by the number of characters and that gives you the size in inches to set the font-size to for that chunk of text. Tested the font-size with absolute measurements in Firefox, Safari, and IE6 so it should be pretty portable. Hope that helps. **EDIT**: Note that you may also need to play around with settings such as the letter-spacing property as well and experiment with what font you use, since the font-size setting isn't really the width of the letters, which will be different based on letter-spacing, and font, proportional to length. Oh, and using a monospace font helps ;)
How do you find the largest font size that won't break a given text?
[ "", "javascript", "css", "printing", "" ]
There's a lot of people today who sell unittesting as bread-and-butter of development. That might even work for strongly algorithmically-oriented routines. However, how would you unit-test, for example, a memory allocator (think malloc()/realloc()/free()). It's not hard to produce a working (but absolutely useless) memory allocator that satisfies the specified interface. But how to provide the proper context for unit-testing functionality that is absolutely desired, yet not part of the contract: coalescing free blocks, reusing free blocks on next allocations, returning excess free memory to the system, asserting that the allocation policy (e.g. first-fit) really is respected, etc. My experience is that assertions, even if complex and time-consuming (e.g. traversing the whole free list to check invariants) are much less work and are more reliable than unit-testing, esp. when coding complex, time-dependent algorithms. Any thoughts?
Highly testable code tends to be structured differently than other code. You describe several tasks that you want an allocator to do: * coalescing free blocks * reusing free blocks on next allocations * returning excess free memory to the system * asserting that the allocation policy (e.g. first-fit) really is respected While you might write your allocation code to be very coupled, as in doing several of those things inside one function body, you could also break each task out into code that is a testable chunk. This is almost an inversion of what you may be used to. I find that testable code tends to be very transparent and built from more small pieces. Next, I would say is that within reason automated testing of any sort is better than no automated testing. I would definitely focus more on making sure your tests do something useful than worrying if you've properly used mocks, whether you've ensured it's properly isolated and whether it's a true unit test. Those are all admirable goals that will hopefully make 99% of tests better. On the other hand, please use common sense and your best engineering judgment to get the job done. Without code samples I don't think I can be more specific.
**If there is any logic in there, it can be unit-tested.** If your logic involves making decisions and calling OS/hardware/system APIs, fake/mock out the device dependent calls and unit test your logic to verify if the right decisions are made under a given set of pre-conditions. Follow the Arrange-Act-Assert triad in your unit test. Assertions are no replacement for automated unit-tests. They dont tell you which scenario failed, they don't provide feedback during development, they can't be used to prove that all specs are being met by the code among other things. **Non-vague Update:** I don't know the exact method calls.. I think I'll 'roll my own' Let's say your code examines current conditions, makes a decision and make calls to the OS as required. Lets say your OS calls are (you may have many more): ``` void* AllocateMemory(int size); bool FreeMemory(void* handle); int MemoryAvailable(); ``` First turn this into an interface, `I_OS_MemoryFacade`. Create an implementation of this interface to make the actual calls to the OS. Now make your code use this interface - you now have decoupled your code/logic from the device/OS. Next in your unit test, you use a mock framework (its purpose is to give you a mock implementation of a specified interface. You can then tell the mock framework that **expect** these calls to be made, with these params and return this when they are made. At the end of the test, you can ask the mock framework to verify if all the expectations were met. (e.g. In this test, AllocateMemory should be called thrice with 10, 30, 50 as params followed by 3 FreeMemory calls. Check if MemoryAvailable returns the initial value.) Since your code depends on an interface, it doesn't know the difference between the real implementation and a fake/mock implementation that you use for testing. Google out 'mock frameworks' for more information on this.
How would you unittest a memory allocator?
[ "", "c++", "c", "unit-testing", "testing", "memory-management", "" ]
It often happens that characters such as *é* gets transformed to *é*, even though the collation for the MySQL DB, table and field is set to utf8\_general\_ci. The encoding in the *Content-Type* for the page is also set to UTF8. I know about utf8\_encode/decode, but I'm not quite sure about where and how to use it. I have read the "[The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)" article, but I need some MySQL / PHP specific pointers. How do I ensure that user entered data containing international characters doesn't get corrupted?
On the first look at <http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet> I think that one important thing is missing (perhaps I overlooked this one). Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a ``` SET NAMES utf8 ``` query prior to any other query you send to the MySQL server. If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using ``` $db=new PDO($dsn, $user, $pass); $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8"); ``` when initializing your db connection.
Collation and charset are not the same thing. Your collation needs to match the charset, so if your charset is utf-8, so should the collation. Picking the wrong collation won't garble your data though - Just make string-comparison/sorting work wrongly. That said, there are several places, where you can set charset settings in PHP. I would recommend that you use utf-8 throughout, if possible. Places that needs charset specified are: * The database. This can be set on database, table and field level, and even on a per-query level. * Connection between PHP and database. * HTTP output; Make sure that the HTTP-header `Content-Type` specifies utf-8. You can set default values in PHP and in Apache, or you can use PHP's [`header`](http://docs.php.net/manual/en/function.header.php) function. * HTTP input. Generally forms will be submitteed in the same charset as the page was served up in, but to make sure, you should specify the [`accept-charset`](http://reference.sitepoint.com/html/form/accept-charset) property. Also make sure that URL's are utf-8 encoded, or avoid using non-ascii characters in url's (And GET parameters). [`utf8_encode`](http://docs.php.net/manual/en/function.utf8-encode.php)/decode functions are a little strangely named. They specifically convert between latin1 (ISO-8859-1) and utf-8. If everything in your application is utf-8, you won't have to use them much. There are at least two gotchas in regards to utf-8 and PHP. The first is that PHP's builtin string functions expect strings to be single-byte. For a lot of operations, this doesn't matter, but it means than you can't rely on [`strlen`](http://docs.php.net/manual/en/function.strlen.php) and other functions. There is a good run-down of the limitations at [this page](http://www.phpwact.org/php/i18n/utf-8). Usually, it's not a big problem, but especially when using 3-party libraries, you need to be aware that things could blow up on this. One option is also to use the mb\_string extension, which has the option to replace all troublesome functions with utf-8 aware alternatives. It's still not a 100% bulletproof solution, but it'll work for most cases. Another problem is that some installations of PHP still has the [`magic_quotes`](http://docs.php.net/manual/en/info.configuration.php#ini.magic-quotes-runtime) setting turned on. This problem is orthogonal to utf-8, but can lead to some head scratching. Turn it off, for your own sanity's sake.
How do I ensure that user entered data containing international characters doesn't get corrupted?
[ "", "php", "mysql", "internationalization", "" ]
I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download? **Update Oct 1, 2008:** Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent `<div>` relatively positioned. It would have been much easier to combine the images and create the effect on that single image. It then got me thinking about online image editors like [Picnik](http://www.picnik.com/) and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page. ``` <img id="img1" src="imgfile1.png"> <img id="img2" src="imgfile2.png"> <canvas id="canvas"></canvas> <script type="text/javascript"> var img1 = document.getElementById('img1'); var img2 = document.getElementById('img2'); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.width = img1.width; canvas.height = img1.height; context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0); </script> ``` Or, if you want to load the images on the fly: ``` <canvas id="canvas"></canvas> <script type="text/javascript"> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var img1 = new Image(); var img2 = new Image(); img1.onload = function() { canvas.width = img1.width; canvas.height = img1.height; img2.src = 'imgfile2.png'; }; img2.onload = function() { context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0); }; img1.src = 'imgfile1.png'; </script> ```
[MarvinJ](https://www.marvinj.org) provides the method **combineByAlpha()** in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow: ``` Marvin.combineByAlpha(image, imageOver, imageOutput, x, y); ``` **image1:** [![enter image description here](https://i.stack.imgur.com/mOjU8m.jpg)](https://i.stack.imgur.com/mOjU8m.jpg) **image2:** [![enter image description here](https://i.stack.imgur.com/MqM2Jm.png)](https://i.stack.imgur.com/MqM2Jm.png) **image3:** [![enter image description here](https://i.stack.imgur.com/IfkJum.png)](https://i.stack.imgur.com/IfkJum.png) **Result:** [![enter image description here](https://i.stack.imgur.com/nNrEGm.png)](https://i.stack.imgur.com/nNrEGm.png) **Runnable Example:** ``` var canvas = document.getElementById("canvas"); image1 = new MarvinImage(); image1.load("https://i.imgur.com/ChdMiH7.jpg", imageLoaded); image2 = new MarvinImage(); image2.load("https://i.imgur.com/h3HBUBt.png", imageLoaded); image3 = new MarvinImage(); image3.load("https://i.imgur.com/UoISVdT.png", imageLoaded); var loaded=0; function imageLoaded(){ if(++loaded == 3){ var image = new MarvinImage(image1.getWidth(), image1.getHeight()); Marvin.combineByAlpha(image1, image2, image, 0, 0); Marvin.combineByAlpha(image, image3, image, 190, 120); image.draw(canvas); } } ``` ``` <script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script> <canvas id="canvas" width="450" height="297"></canvas> ```
Can you combine multiple images into a single one using JavaScript?
[ "", "javascript", "image-processing", "image-manipulation", "" ]
How do I copy a file in Python?
[`shutil`](http://docs.python.org/3/library/shutil.html) has many methods you can use. One of which is: ``` import shutil shutil.copyfile(src, dst) # 2nd option shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp ``` * Copy the contents of the file named `src` to a file named `dst`. Both `src` and `dst` need to be the entire filename of the files, including path. * The destination location must be writable; otherwise, an `IOError` exception will be raised. * If `dst` already exists, it will be replaced. * Special files such as character or block devices and pipes cannot be copied with this function. * With `copy`, `src` and `dst` are path names given as `str`s. Another `shutil` method to look at is [`shutil.copy2()`](https://docs.python.org/3/library/shutil.html#shutil.copy2). It's similar but preserves more metadata (e.g. time stamps). If you use `os.path` operations, use `copy` rather than `copyfile`. `copyfile` will only accept strings.
| Function | Copies metadata | Copies permissions | Uses file object | Destination may be directory | | --- | --- | --- | --- | --- | | [shutil.copy](https://docs.python.org/3/library/shutil.html#shutil.copy) | No | Yes | No | Yes | | [shutil.copyfile](https://docs.python.org/3/library/shutil.html#shutil.copyfile) | No | No | No | No | | [shutil.copy2](https://docs.python.org/3/library/shutil.html#shutil.copy2) | Yes | Yes | No | Yes | | [shutil.copyfileobj](https://docs.python.org/3/library/shutil.html#shutil.copyfileobj) | No | No | Yes | No |
How to copy files
[ "", "python", "file", "copy", "filesystems", "file-copying", "" ]
I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in `OnStart()` method). I had assumed that merely throwing an error in `OnStart()` would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. Is this correct?" (Paraphrase). How do I handle the error so it actually fails to start the service?
if you are running .NET 2.0 or higher, you can use [ServiceBase.Stop](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.stop) to stop the service from OnStart. Otherwise call Stop from a new thread. ref [devnewsgroups] (<http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic50404.aspx>) (news group gone)
If the main thing you want is for the Services window to report that there was an error, from what I've tried (.NET3.5 on Windows 7), the only way to do this is by setting the `ExitCode`. I recommend setting it to 13816, since this results in the message, "An unknown error has occurred." See [the windows error codes](http://msdn.microsoft.com/en-us/library/ms681384%28v=vs.85%29 "windows error codes"). The sample below accomplishes three things. 1. Setting ExitCode results in a useful message for the end-user. It doesn't affect the Windows Application log but does include a message in the System log. 2. Calling Stop results in a "Service successfully stopped" message in the Application log. 3. throwing the exception results in a useful log entry in the Application log. ``` protected override void OnStart(string[] args) { try { // Start your service }catch (Exception ex) { // Log exception this.ExitCode = 13816; this.Stop(); throw; } } ```
Handle exception on service startup
[ "", "c#", ".net", "windows-services", "error-handling", "" ]
I would like to know when I should include external scripts or write them inline with the html code, in terms of performance and ease of maintenance. What is the general practice for this? Real-world-scenario - I have several HTML pages that need client-side form validation. For this I use a jQuery plugin that I include on all these pages. But the question is, do I: * write the bits of code that configure this script inline? * include all bits in one file that's share among all these HTML pages? * include each bit in a separate external file, one for each HTML page?
At the time this answer was originally posted (2008), the rule was simple: All script should be external. Both for maintenance and performance. (Why performance? Because if the code is separate, it can easier be cached by browsers.) JavaScript doesn't belong in the HTML code and if it contains special characters (such as `<`, `>`) it even creates problems. Nowadays, web scalability has changed. Reducing the number of requests has become a valid consideration due to the latency of making multiple HTTP requests. This makes the answer more complex: in most cases, having JavaScript external is *still* recommended. But for certain cases, especially very small pieces of code, inlining them into the site’s HTML makes sense.
Maintainability is definitely a reason to keep them external, but if the configuration is a one-liner (or in general shorter than the HTTP overhead you would get for making those files external) it's performance-wise better to keep them inline. Always remember, that each HTTP request generates some overhead in terms of execution time and traffic. Naturally this all becomes irrelevant the moment your code is longer than a couple of lines and is not really specific to one single page. The moment you want to be able to reuse that code, make it external. If you don't, look at its size and decide then.
When should I use Inline vs. External JavaScript?
[ "", "javascript", "html", "" ]
I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook. I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting? Thanks
You need to use `\r\n` as a solution.
I've just been fighting with this today. Let's call the behavior of removing the extra line breaks "continuation." A little experimenting finds the following behavior: * Every message starts with continuation off. * Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will have their line breaks removed. * Lines 40 characters or longer turn continuation on. It remains on until an event occurs to turn it off. * Lines that end with a period, question mark, exclamation point or colon turn continuation off. (Outlook assumes it's the end of a sentence?) * Lines that turn continuation off will start with a line break, but will turn continuation back on if they are longer than 40 characters. * Lines that start or end with a tab turn continuation off. * Lines that start with 2 or more spaces turn continuation off. * Lines that end with 3 or more spaces turn continuation off. Please note that I tried all of this with Outlook 2007. YMMV. So if possible, end all bullet items with a sentence-terminating punctuation mark, a tab, or even three spaces.
How do I format a String in an email so Outlook will print the line breaks?
[ "", "java", "email", "outlook", "newline", "line-breaks", "" ]
I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop. The html looks like this: ``` <div onmouseover="jsHoverIn('1')" onmouseout="jsHoverOut('1')"> <div id="image1" /> <div id="text1" style="display: none;"> <p>some content</p> <p>some more content</p> </div> </div> ``` And the javascript (It uses scriptaculous): ``` function jsHoverIn(id) { if(!visible[id]) { new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } }); visible[id] = true; } } function jsHoverOut (id) { var scope = Effect.Queues.get(id); scope.each(function(effect) { effect.cancel(); }); new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } }); visible[id] = false; } ``` This seems really simple, but i just cant wrap my head around it.
I'd give the container div: ``` position: relative; ``` and add a third div in the container (should be the last child of the container) with: ``` position: absolute; top: 0; bottom: 0; left: 0; right: 0; ``` and catch the mouseover and mouseout events on this div instead. Because it has no child elements, you shouldn't get spurious mouseover and mouseout events propagating to it. *Edit:* What I believe happens, is that when the cursor moves from a parent element onto a child element, a mouseout event occurs on the parent element, and a mouseover event occurs on the child element. However, if the mouseover handler on the child element does not catch the event and stop it propagating, the parent element will also receive the mouseover event.
It sounds like what you really want is `mouseenter`/`mouseleave` (IE proprietary events, but easy to emulate): ``` // Observe mouseEnterLeave on mouseover/mouseout var mouseEnterLeave = function(e) { var rel = e.relatedTarget, cur = e.currentTarget; if (rel && rel.nodeType == 3) { rel = rel.parentNode; } if( // Outside window rel == undefined || // Firefox/other XUL app chrome (rel.tagName && rel.tagName.match(/^xul\:/i)) || // Some external element (rel && rel != cur && rel.descendantOf && !rel.descendantOf(cur)) ) { e.currentTarget.fire('mouse:' + this, e); return; } }; $(yourDiv).observe('mouseover', mouseEnterLeave.bind('enter')); $(yourDiv).observe('mouseout', mouseEnterLeave.bind('leave')); // Use mouse:enter and mouse:leave for your events $(yourDiv).observe(!!Prototype.Browser.IE ? 'mouseenter' : 'mouse:enter', yourObserver); $(yourDiv).observe(!!Prototype.Browser.IE ? 'mouseleave' : 'mouse:leave', yourObserver); ``` Alternatively, [patch prototype.js](http://dev.rubyonrails.org/attachment/ticket/8354/event_mouseenter_106rc1.patch) and use `mouseenter` and `mouseleave` with confidence. Note that I've expanded the check for leaving the window or entering XUL chrome; this seemed to fix some edge cases in Firefox for me.
Problems with mouseout event
[ "", "javascript", "html", "events", "scriptaculous", "" ]
Let's say you have a function that returns a date: ``` Date myFunc(paramA, paramB){ //conditionally return a date? } ``` Is it appropriate to return `null` from this function? This seems ugly because it forces clients to check for `null`. The "null object" pattern is an implementation pattern that addresses this concern. I'm not a huge fan of the null object pattern, but yes, it makes sense to always return a list, even if is empty, rather than to return `null`. However, say in Java, a null date would be one that is cleared and has the year 1970. What is the best implementation pattern here?
The null object pattern is not for what you are trying to do. That pattern is about creating an object with no functionality in it's implementation that you can pass to a given function that requires an object not being null. An example is [NullProgressMonitor](http://download.eclipse.org/eclipse/downloads/documentation/2.0/html/plugins/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/NullProgressMonitor.html) in Eclipse, which is an empty implementation of [IProgressMonitor](http://download.eclipse.org/eclipse/downloads/documentation/2.0/html/plugins/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/IProgressMonitor.html). If you return a "null" date, like 1970, your clients will still need to check if it's "null" by seeing if it's 1970. And if they don't, misbehaviour will happen. However, if you return null, their code will fail fast, and they'll know they should check for null. Also, 1970 *could* be a valid date. You should document that your method may return null, and that's it.
null is quite acceptable. However if you want to return null on an error, consider throwing an exception instead.
Should I return null from or apply the "null object" pattern to a function returning a Date?
[ "", "java", "" ]
I have an ASPX page (On server A) which is invoked using NTLM credentials. Part of that page's job is to call an HTML page (On server B) and proxy it back to the client. (The firewall allows access to A, but not to B. The user would normally be allowed access to both servers.). Server B is also not open to anonymous access, so I need to supply credentials to it. If I hardcode some credentials (as per the attached code), it works, but ideally I would echo the credentials that were received by the .aspx page. Is there some way to get those NetworkCredentials so I can pass them on? ``` protected void Page_Load(object sender, EventArgs e) { Response.Clear(); WebClient proxyFile = new WebClient(); CredentialCache cc = new CredentialCache(); cc.Add(new Uri("http://serverB/"), "NTLM", new NetworkCredential("userName", "password", "domain")); proxyFile.Credentials = cc; Stream proxyStream = proxyFile.OpenRead("http://serverB/Content/webPage.html"); int i; do { i = proxyStream.ReadByte(); if (i != -1) { Response.OutputStream.WriteByte((byte)i); } } while (i != -1); Response.End(); } ```
You can certainly obtain the login name of the caller, but not the password. NTLM uses a challenge/response mechanism, so the password is never transmitted. Your server must have access to a password-equivalent (a hash) in order to form the challenge and check the response, but even if you can get hold of it that password-equivalent will be no use to you in trying to form credentials that will be accepted by server B. If you can set up impersonation, as described in another answer, even that doesn't necessarily get you what you want. By default, an impersonating server process is not allowed to transmit its identity to another server. That second hop is known as delegation and needs to be configured explicitly on the servers involved (and/or in Active Directory). Apart from delegation I think your only option is to maintain a database of credentials that server A can access and present to server B. Building that in a secure manner is a subtle and time-consuming process. On the other hand, there is a reason why delegation is disabled by default. When I log into a server, do I want it to be allowed to use my identity for accessing other servers? Delegation is the simplest option for you, but you'll need to be sure that server A can't be compromised to do irresponsible things with your users' identities.
Page.User will get you the Security Principal of the user the page is running under. From there you should be able to figure it out.
Get the NTLM credentials from the Response on an APSX page
[ "", "c#", "asp.net", "credentials", "" ]
Compared to * Simple memory access * Disk access * Memory access on another computer(on the same network) * Disk access on another computer(on the same network) in C++ on windows.
relative timings (shouldn't be off by more than a factor of 100 ;-) * memory-access in cache = 1 * function call/return in cache = 2 * memory-access out of cache = 10 .. 300 * disk access = 1000 .. 1e8 (amortized depends upon the number of bytes transferred) + depending mostly upon seek times + the transfer itself can be pretty fast + involves at least a few thousand ops, since the user/system threshold must be crossed at least twice; an I/O request must be scheduled, the result must be written back; possibly buffers are allocated... * network calls = 1000 .. 1e9 (amortized depends upon the number of bytes transferred) + same argument as with disk i/o + the raw transfer speed can be quite high, but some process on the other computer must do the actual work
A function call is simply a shift of the frame pointer in memory onto the stack and addition of a new frame on top of that. The function parameters are shifted into local registers for use and the stack pointer is advanced to the new top of the stack for execution of the function. In comparison with time Function call ~ simple memory access Function call < Disk Access Function call < memory access on another computer Function call < disk access on another computer
What is the cost of a function call?
[ "", "c++", "optimization", "architecture", "memory", "" ]
I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times. Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)? Thanks!
Don't panic, every fresh Web programmer face this problem. You HAVE TO separate your program logic from your display. First, try to make your own solution using two files for each Web page : * one with only PHP code (no HTML) that fills variables * another with HTML and very few PHP : this is your page design Then include where / when you need it. E.G : myPageLogic.php ``` <?php // pure PHP code, no HTML $name = htmlspecialchars($_GET['name']); $age = date('Y') - htmlspecialchars($_GET['age']); ?> ``` myPageView.php ``` // very few php code // just enought to print variables // and some if / else, or foreach to manage the data stream <h1>Hello, <?php $name ?> !</h1> <p>So your are <?php $age?>, hu ?</p> ``` (You may want to use the [alternative PHP syntax](http://php.mirror.camelnetwork.com/manual/en/control-structures.alternative-syntax.php) for this one. But don't try to hard to make it perfect the first time, really.) myPage.php ``` <?php require('myPageLogic.php'); require('myPageView.php'); ?> ``` *Don't bother about performance issues for now*. This is not your priority as a newbie. This solution is imperfect, but will help you to solve the problem with your programming level and will teach you the basics. Then, once your are comfortable with this concept, buy a book about the MVC pattern (or look for stack overflow entries about it). That what you want to do the *NEXT TIME*. Then you'll try some templating systems and frameworks, but *LATER*. For now, just code and learn from the beginning. You can perfectly code a project like that, as a rookie, it's fine.
Use a mvc approach. <http://www.phpmvc.net/> This is not something that you will pick up in a couple of hours. You really need to practice it. Main thing is the controller will access your model (the db layer), do stuff to your data and then send it to the view for rendering. This is oversimplified but you just need to read and practice it to understand it. This is something I used to help me learn it. <http://www.onlamp.com/pub/a/php/2005/09/15/mvc_intro.html>
Keeping my PHP pretty
[ "", "php", "html", "formatting", "" ]
I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?
The command-line Python, IMO, definitely comes first. Get that to work, since that's the core of what you're doing. The issue is that using a web framework's ORM from a command line application isn't obvious. Django provides specific instructions for using their ORM from a command-line app. Those are annoying at first, but I think they're a life-saver in the long run. I use it heavily for giant uploads of customer-supplied files. Don't use bare CGI. It's not impossible, but too many things can go wrong, and they've all been solved by the frameworks. Why reinvent something? Just use someone else's code. Frameworks involve learning, but no real "overhead". They're not slow. They're code you don't have to write or debug. 1. Learn some Python. 2. Do the [Django](http://docs.djangoproject.com/en/dev/) tutorial. 3. Start to build a web app. a. Start a Django project. Build a small application in that project. b. Build your new model using the Django ORM. Create a Django unit test for the model. Be sure that it works. You'll be able to use the default admin pages and do a lot of playing around. Just don't build the *entire* web site yet. 4. Get your command-line app to work using Django ORM. Essentially, you have to finesse the settings file for this app to work nicely. See the [settings/configuration](http://docs.djangoproject.com/en/dev/topics/settings/#topics-settings) section. 5. Once you've got your command line and the default admin running, you can finish the web app. Here's the golden rule of frameworks: **It's code you don't have to write, debug or maintain.** Use them.
You might consider using something like [web.py](http://webpy.org/) which would be easy to distribute (since it's small) and it would also be easy to adapt your other tools to it since it doesn't require you to submit to the framework so much like Django does. Be forewarned, however, it's not the most loved framework in the Python community, but it might be just the thing for you. You might also check out [web2py](http://mdp.cti.depaul.edu/), but I know less about that.
Python web development - with or without a framework
[ "", "python", "frameworks", "" ]
I'm using Java 6, Tomcat 6, and Metro. I use WebService and WebMethod annotations to expose my web service. I would like to obtain information about the request. I tried the following code, but wsCtxt is always null. What step must I take to *not* get null for the WebServiceContext. In other words: how can I execute the following line to get a non-null value for wsCtxt? MessageContext msgCtxt = wsCtxt.getMessageContext(); ``` @WebService public class MyService{ @Resource WebServiceContext wsCtxt; @WebMethod public void myWebMethod(){ MessageContext msgCtxt = wsCtxt.getMessageContext(); HttpServletRequest req = (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST); String clientIP = req.getRemoteAddr(); } ```
I recommend you either rename your variable from wsCtxt to wsContext or assign the name attribute to the @Resource annotation. The [J2ee tutorial on @Resource](http://java.sun.com/javaee/5/docs/tutorial/doc/bncjk.html) indicates that the name of the variable is used as part of the lookup. I've encountered this same problem using resource injection in Glassfish injecting a different type of resource. Though your correct name may not be wsContext. I'm following this [java tip](http://www.java-tips.org/java-ee-tips/java-api-for-xml-web-services/using-jax-ws-based-web-services-wit.html). If you like the variable name wsCtxt, then use the name attribute in the variable declaration: > `@Resource(name="wsContext") WebServiceContext wsCtxt;`
The following code works for me using Java 5, Tomcat 6 and Metro Could it possibly be that there is a conflict between the WS support in Java 6 and the version of Metro you are using. Have you tried it on a Java 5 build? ``` @WebService public class Sample { @WebMethod public void sample() { HttpSession session = findSession(); //Stuff } private HttpSession findSession() { MessageContext mc = wsContext.getMessageContext(); HttpServletRequest request = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST); return request.getSession(); } @Resource private WebServiceContext wsContext; } ```
How can I get access to the HttpServletRequest object when using Java Web Services
[ "", "java", "web-services", "annotations", "servlets", "" ]
I hit this error while my web application was trying to execute a SELECT INTO on a MSSQL 2005 database. I really have two questions: 1. What does this error mean and how does this happen? 2. Is there a way to prevent these errors by coding in a different way?
Besides the obvious, that somebody changed the table while the code was executing, it could be a naming conflict with temp tables created in the SQL. It could be that there are two temp tables with different schemas, but they have the same name.
You can get this error if a database trigger(AFTER CREATE\_TABLE) changes the table, when using SELECT INTO.
How does a "Schema changed after the target table was created" error occur?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I often see code like: ``` Iterator i = list.iterator(); while(i.hasNext()) { ... } ``` but I write that (when Java 1.5 isn't available or for each can't be used) as: ``` for(Iterator i = list.iterator(); i.hasNext(); ) { ... } ``` because * It is shorter * It keeps `i` in a smaller scope * It reduces the chance of confusion. (Is `i` used outside the while? Where is `i` declared?) I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better? From: <http://jamesjava.blogspot.com/2006/04/iterating.html>
I prefer the for loop because it also sets the scope of the iterator to just the for loop.
There are appropriate uses for the while, the for, and the foreach constructs: * `while` - Use this if you are iterating and the deciding factor for looping or not is based merely on a condition. In this loop construct, keeping an index is only a secondary concern; everything should be based on the condition * `for` - Use this if you are looping and your primary concern is the index of the array/collection/list. It is more useful to use a for if you are most likely to go through *all* the elements anyway, and in a particular order (e.g., going backwards through a sorted list, for example). * `foreach` - Use this if you merely need to go through your collection regardless of order. Obviously there are exceptions to the above, but that's the general rule I use when deciding to use which. That being said I tend to use `foreach` more often.
Iterate with for loop or while loop?
[ "", "java", "for-loop", "iterator", "" ]
Ideally I'd like a way to enable the mouse wheel for scrolling in old compiled java runtime apps, but java code to explicitly utilise it for an individual app would suffice.
Without access to the source code, you can't do it. If you do have access to the source, then do what RichH said.
You shouldn't have to recompile against 1.5 or 1.6 to get mousewheel, unless you wrote custom components. The mousewheel behaviors were added to the swing classes, so just running old java apps against the new JRE should have mousewheel support without having to do anything (at least in scrollable/JScrollPane based stuff)
Is there any way to enable the mousewheel (for scrolling) in Java apps?
[ "", "java", "scroll", "mouse", "mousewheel", "" ]
I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django. I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block. How should I do this? It's a fairly large project, so adding code to every view is far from ideal. --- That solution works well. The Middleware Class I ended up with this this: ``` from django.http import HttpResponseRedirect class BetaMiddleware(object): """ Require beta code session key in order to view any page. """ def process_request(self, request): if request.path != '/beta/' and not request.session.get('in_beta'): return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path)) ```
Start with [this Django snippet](http://www.djangosnippets.org/snippets/136/), but modify it to check `request.session['has_beta_access']`. If they don't have it, then have it return a redirect to a "enter beta code" page that, when posted to with the right code, sets that session variable to `True`. Making it a public beta then just consists of removing that middleware from your `MIDDLEWARE_CLASSES` setting.
You can probably restrict access to the entire site via apache with htaccess, taking the problem out of the django's project space entirely.
Making a beta code for a public django site
[ "", "python", "django", "authentication", "django-authentication", "" ]
Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing. Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)?
You could try setting up your own handler for the [onerror event](http://developer.mozilla.org/En/DOM:window.onerror) and use XMLHttpRequest to tell the server what went wrong, however since it's not part of any specification, [support is somewhat flaky](http://www.quirksmode.org/dom/events/error.html). Here's an example from [Using XMLHttpRequest to log JavaScript errors](http://www.the-art-of-web.com/javascript/ajax-onerror/): ``` window.onerror = function(msg, url, line) { var req = new XMLHttpRequest(); var params = "msg=" + encodeURIComponent(msg) + '&amp;url=' + encodeURIComponent(url) + "&amp;line=" + line; req.open("POST", "/scripts/logerror.php"); req.send(params); }; ```
**Short answer:** Yes, it is possible. **Longer answer:** People have already written about how you can (at least partially) solve this issue by writing your own code. However, do note that there are services out there that seems to have made sure the JS code needed works in many browsers. I've found the following: * <http://trackjs.com> * <https://www.atatus.com> * <http://jserrlog.appspot.com> * <http://muscula.com> * <https://sentry.io> * <https://rollbar.com> * <https://catchjs.com> I can't speak for any of these services as I haven't tried them yet.
Logging Clientside JavaScript Errors on Server
[ "", "javascript", "logging", "error-handling", "" ]
I am encountering very infrequent yet annoying SQL deadlocks on a .NET 2.0 webapp running on top of MS SQL Server 2005. In the past, we have been dealing with the SQL deadlocks in the very empirical way - basically tweaking the queries until it work. Yet, I found this approach very unsatisfactory: time consuming and unreliable. I would highly prefer to follow deterministic query patterns that would ensure **by design** that no SQL deadlock will be encountered - ever. For example, in C# multithreaded programming, a simple design rule such as *the locks must be taken following their lexicographical order* ensures that no deadlock will *ever* happen. Are there any SQL coding patterns guaranteed to be deadlock-proof?
Writing deadlock-proof code is really hard. Even when you access the tables in the same order you may still get deadlocks [1]. I wrote [a post on my blog](http://samsaffron.com/archive/2008/08/27/Deadlocked+) that elaborates through some approaches that will help you avoid and resolve deadlock situations. If you want to ensure two statements/transactions will never deadlock you may be able to achieve it by observing which locks each statement consumes using the **sp\_lock** system stored procedure. To do this you have to either be very fast or use an open transaction with a holdlock hint. --- Notes: 1. Any SELECT statement that needs more than one lock at once can deadlock against an intelligently designed transaction which grabs the locks in reverse order.
Zero deadlocks is basically an incredibly costly problem in the general case because you must know all the tables/obj that you're going to read and modify for every running transaction (this includes SELECTs). The general philosophy is called **ordered strict two-phase locking** (not to be confused with two-phase commit) (<http://en.wikipedia.org/wiki/Two_phase_locking> ; even 2PL does not *guarantee* no deadlocks) Very few DBMS actually implement strict 2PL because of the massive performance hit such a thing causes (there are no free lunches) while all your transactions wait around for even simple SELECT statements to be executed. Anyway, if this is something you're really interested in, take a look at `SET ISOLATION LEVEL` in SQL Server. You can tweak that as necessary. <http://en.wikipedia.org/wiki/Isolation_level> For more info, see wikipedia on Serializability: <http://en.wikipedia.org/wiki/Serializability> That said -- a great analogy is like source code revisions: check in early and often. Keep your transactions small (in # of SQL statements, # of rows modified) and quick (wall clock time helps avoid collisions with others). It may be nice and tidy to do a LOT of things in a single transaction -- and in general I agree with that philosophy -- but if you're experiencing a lot of deadlocks, you may break the trans up into smaller ones and then check their status in the application as you move along. TRAN 1 - OK Y/N? If Y, send TRAN 2 - OK Y/N? etc. etc As an aside, in my many years of being a DBA and also a developer (of multiuser DB apps measuring thousands of concurrent users) I have never found deadlocks to be such a massive problem that I needed special cognizance of it (or to change isolation levels willy-nilly, etc).
Zero SQL deadlock by design - any coding patterns?
[ "", "sql", "sql-server", "design-patterns", "deadlock", "" ]
in Javascript, the following: ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/".*?"/g); alert(result); ``` yields "the quick","brown fox","jumps over","the lazy dog" I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog what regexp will do this?
This seems to work: ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/[^"]+(?=(" ")|"$)/g); alert(result); ``` Note: This doesn't match empty elements (i.e. ""). Also, it won't work in browsers that don't support JavaScript 1.5 (lookaheads are a 1.5 feature). See <http://www.javascriptkit.com/javatutors/redev2.shtml> for more info.
It is not one regexp, but two simpler regexps. ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/".*?"/g); // ["the quick","brown fox","jumps over","the lazy dog"] result.map(function(el) { return el.replace(/^"|"$/g, ""); }); // [the quick,brown fox,jumps over,the lazy dog] ```
Regexp matching of list of quotes strings - unquoted
[ "", "javascript", "regex", "actionscript-3", "" ]
Does anyone know of a Django 1.0 + postgresql + apache + mod\_python VMware appliance? A "vanilla" Django 1.0 appliance where postgresql can be installed manually would also do.
Configure and build your appliance at [Elastic Server On-Demand](https://elasticserver.com/).
Another option I've had moderate success with [TurnKey Linux Django Appliance](http://www.turnkeylinux.org/appliances/django)
Django VMware appliance
[ "", "python", "django", "vmware", "" ]
What is the difference between a method [decorated](https://peps.python.org/pep-0318/) with [`@staticmethod`](http://docs.python.org/library/functions.html#staticmethod) and one decorated with [`@classmethod`](http://docs.python.org/library/functions.html#classmethod)?
Maybe a bit of example code will help: Notice the difference in the call signatures of `foo`, `class_foo` and `static_foo`: ``` class A(object): def foo(self, x): print(f"executing foo({self}, {x})") @classmethod def class_foo(cls, x): print(f"executing class_foo({cls}, {x})") @staticmethod def static_foo(x): print(f"executing static_foo({x})") a = A() ``` Below is the usual way an object instance calls a method. The object instance, `a`, is implicitly passed as the first argument. ``` a.foo(1) # executing foo(<__main__.A object at 0xb7dbef0c>, 1) ``` --- **With classmethods**, the class of the object instance is implicitly passed as the first argument instead of `self`. ``` a.class_foo(1) # executing class_foo(<class '__main__.A'>, 1) ``` You can also call `class_foo` using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. `A.foo(1)` would have raised a TypeError, but `A.class_foo(1)` works just fine: ``` A.class_foo(1) # executing class_foo(<class '__main__.A'>, 1) ``` One use people have found for class methods is to create [inheritable alternative constructors](https://stackoverflow.com/a/1950927/190597). --- **With staticmethods**, neither `self` (the object instance) nor `cls` (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class: ``` a.static_foo(1) # executing static_foo(1) A.static_foo('hi') # executing static_foo(hi) ``` Staticmethods are used to group functions which have some logical connection with a class to the class. --- `foo` is just a function, but when you call `a.foo` you don't just get the function, you get a "partially applied" version of the function with the object instance `a` bound as the first argument to the function. `foo` expects 2 arguments, while `a.foo` only expects 1 argument. `a` is bound to `foo`. That is what is meant by the term "bound" below: ``` print(a.foo) # <bound method A.foo of <__main__.A object at 0xb7d52f0c>> ``` With `a.class_foo`, `a` is not bound to `class_foo`, rather the class `A` is bound to `class_foo`. ``` print(a.class_foo) # <bound method type.class_foo of <class '__main__.A'>> ``` Here, with a staticmethod, even though it is a method, `a.static_foo` just returns a good 'ole function with no arguments bound. `static_foo` expects 1 argument, and `a.static_foo` expects 1 argument too. ``` print(a.static_foo) # <function static_foo at 0xb7d479cc> ``` And of course the same thing happens when you call `static_foo` with the class `A` instead. ``` print(A.static_foo) # <function static_foo at 0xb7d479cc> ```
A **staticmethod** is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. A **classmethod**, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how `dict.fromkeys()`, a classmethod, returns an instance of the subclass when called on a subclass: ``` >>> class DictSubclass(dict): ... def __repr__(self): ... return "DictSubclass" ... >>> dict.fromkeys("abc") {'a': None, 'c': None, 'b': None} >>> DictSubclass.fromkeys("abc") DictSubclass >>> ```
What is the difference between @staticmethod and @classmethod in Python?
[ "", "python", "oop", "static-methods", "python-decorators", "class-method", "" ]
Under what circumstances will the Win32 API function OleGetClipboard() fail and return `CLIPBRD_E_CANT_OPEN`? More background: I am assisting with a Firefox bug fix. Details here: [bug 444800 - cannot retrieve image data from clipboard in lossless format](https://bugzilla.mozilla.org/show_bug.cgi?id=444800#c19 "cannot retrieve image data from clipboard in lossless format") In the automated test that I helped write, we see that OleGetClipboard() sometimes fails and returns `CLIPBRD_E_CANT_OPEN`. That is unexpected, and the Firefox code to pull image data off the Windows clipboard depends on that call succeeding.
The documentation says that `OleGetClipboard` can fail with this error code if `OpenClipboard` fails. In turn, if you read that documentation, it says: "**OpenClipboard** fails if another window has the clipboard open." It's an exclusive resource: only one window can have the clipboard open at a time. Basically, if you can't do it, wait a little while and try again.
Is your test running over Terminal Services? See [CLIPBRD\_E\_CANT\_OPEN error when setting the Clipboard from .NET](https://stackoverflow.com/questions/68666/clipbrdecantopen-error-when-setting-the-clipboard-from-net).
Why would the Win32 OleGetClipboard() function return CLIPBRD_E_CANT_OPEN?
[ "", "c++", "windows", "winapi", "ole", "" ]
Our server application is listening on a port, and after a period of time it no longer accepts incoming connections. (And while I'd love to solve this issue, it's not what I'm asking about here;) The strange this is that when our app stops accepting connections on port 44044, so does IIS (on port 8080). Killing our app fixes everything - IIS starts responding again. So the question is, can an application mess up the entire TCP/IP stack? Or perhaps, how can an application do that? Senseless detail: Our app is written in C#, under .Net 2.0, on XP/SP2. Clarification: IIS is not "refusing" the attempted connections. It is never seeing them. Clients are getting a "server did not respond in a timely manner" message (using the .Net TCP Client.)
You may well be starving the stack. It is pretty easy to drain in a high open/close transactions per second environment e.g. webserver serving lots of unpooled requests. This is exhacerbated by the default TIME-WAIT delay - the amount of time that a socket has to be closed before being recycled defaults to 90s (if I remember right) There are a bunch of registry keys that can be tweaked - suggest at least the following keys are created/edited ``` HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters TcpTimedWaitDelay = 30 MaxUserPort = 65534 MaxHashTableSize = 65536 MaxFreeTcbs = 16000 ``` Plenty of docs on MSDN & Technet about the function of these keys.
You haven't maxed out the available port handles have you ? `netstat -a` I saw something similar when an app was opening and closing ports (but not actually closing them correctly).
Can a TCP/IP Stack be killed programmatically?
[ "", "c#", "tcp", "" ]
I want to use modal pop-up windows in our web app in Ruby on Rails. Note that I don't want to create a new browser window, but a sub-window inside the existing webpage. We've tried things like TinyBox, but there are issues with returning error information from inside the controller. Any good method or tool that works well in ruby?
There's also [prototype-window](http://prototype-window.xilinus.com/).
I've never used it myself (not yet at least) but have you tried [RedBox](http://blog.craigambrose.com/articles/2006/08/16/redbox-a-rails-compatible-lightbox)?
What are some good pop-up dialog boxes for Ruby on Rails
[ "", "javascript", "ruby-on-rails", "user-interface", "modalpopups", "" ]
Does anyone know of any methods to create a file upload progress bar in PHP? I have often heard that it's impossible. I have one idea, but not sure if it would work: have a normal file upload, but instead submit to an iframe. When this is submitted, store the file information (size and temp location) in the session. At the same time, start an AJAX call to every say 10 seconds to check the size of the file compared to the size stored in the session. This would return the size to the AJAX and then a progress bar would be sized and maybe display the uploaded size to the user. Thoughts?
You can try [YUI](http://developer.yahoo.com/yui/uploader/) or [Prototype](http://www.google.com/search?q=prototype+upload+progress) or [JQuery](http://www.google.com/search?q=jquery+upload+progress)
You're pretty much figured out how to do it. The main problem is you usually don't have access to the size of the uploaded file until it's done uploading. There are workarounds for this: Enabling APC, you to access this information if you include a field called "APC\_UPLOAD\_PROGRESS" and use apc\_fetch() for retrieving a cache entry with the status. There's also a plugin called uploadprogress but it's not very well documented and doesn't work on Windows (last I checked anyway). An alternative is to use Flash for doing it. See scripts like [FancyUpload](http://digitarald.de/project/fancyupload/). Before APC came along I had to write a CGI script in C that wrote information to a text file. APC seems like a much better way to do it now though. Hope this helps.
Creating a file progress bar in PHP
[ "", "php", "ajax", "file-upload", "progress-bar", "" ]
What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used".
There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e. The number of sessions the database was configured to allow ``` SELECT name, value FROM v$parameter WHERE name = 'sessions' ``` The number of sessions currently active ``` SELECT COUNT(*) FROM v$session ``` As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.
The **sessions** parameter is derived from the **processes** parameter and changes accordingly when you change the number of max processes. See the [Oracle docs](http://docs.oracle.com/cd/B28359_01/server.111/b28320/initparams001.htm#i1124357) for further info. To get only the info about the sessions: ``` select current_utilization, limit_value from v$resource_limit where resource_name='sessions'; ``` ``` CURRENT_UTILIZATION LIMIT_VALUE ------------------- ----------- 110 792 ``` Try this to show info about both: ``` select resource_name, current_utilization, max_utilization, limit_value from v$resource_limit where resource_name in ('sessions', 'processes'); ``` ``` RESOURCE_NAME CURRENT_UTILIZATION MAX_UTILIZATION LIMIT_VALUE ------------- ------------------- --------------- ----------- processes 96 309 500 sessions 104 323 792 ```
How to check the maximum number of allowed connections to an Oracle database?
[ "", "sql", "oracle", "" ]
What would be the best practice way to handle the caching of images using PHP. The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag. When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid}.jpg which is rewritten to a php script. This allows my designers to specify (roughly - the source image maybe smaller) the file size. The php script then creates a hash of the size (200x200 in the url) and the GUID filename and if the file has been generated before (file with the name of the hash exists in TMP directory) sends the file from the application TMP directory. If the hashed filename does not exist, then it is created, written to disk and served up in the same manner, Is this efficient as it could be? (It also supports watermarking the images and the watermarking settings are stored in the hash as well, but thats out of scope for this.)
There is two typos in Dan Udey's rewrite example (and I can't comment on it), it should rather be : ``` RewriteCond %{REQUEST_URI} ^/images/cached/ RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f RewriteRule (.*) /images/generate.php?$1 [L] ``` Regards.
I would do it in a different manner. Problems: 1. Having PHP serve the files out is less efficient than it could be. 2. PHP has to check the existence of files every time an image is requested 3. Apache is far better at this than PHP will ever be. There are a few solutions here. You can use `mod_rewrite` on Apache. It's possible to use mod\_rewrite to test to see if a file exists, and if so, serve that file instead. This bypasses PHP entirely, and makes things far faster. The real way to do this, though, would be to generate a specific URL schema that should always exist, and then redirect to PHP if not. For example: ``` RewriteCond %{REQUEST_URI} ^/images/cached/ RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f RewriteRule (.*) /images/generate.php?$1 [L] ``` So if a client requests `/images/cached/<something>` and that file doesn't exist already, Apache will redirect the request to `/images/generate.php?/images/cached/<something>`. This script can then generate the image, write it to the cache, and then send it to the client. In the future, the PHP script is never called except for new images. Use caching. As another poster said, use things like `mod_expires`, Last-Modified headers, etc. to respond to conditional GET requests. If the client doesn't have to re-request images, page loads will speed dramatically, and load on the server will decrease. For cases where you do have to send an image from PHP, you can use `mod_xsendfile` to do it with less overhead. See [the excellent blog post from Arnold Daniels](http://blog.adaniels.nl/articles/how-i-php-x-sendfile/) on the issue, but note that his example is for downloads. To serve images inline, take out the Content-Disposition header (the third header() call). Hope this helps - more after my migraine clears up.
Best way to cache resized images using PHP and MySQL
[ "", "php", "image", "caching", "resize", "" ]
I know I can specify one for each form, or for the root form and then it'll cascade through to all of the children forms, but I'd like to have a way of overriding the default Java Coffee Cup for all forms even those I might forget. Any suggestions?
You can make the root form (by which I assume you mean `JFrame`) be your own subclass of `JFrame`, and put standard functionality in its constructor, such as: ``` this.setIconImage(STANDARD_ICON); ``` You can bundle other standard stuff in here too, such as memorizing the frame's window metrics as a user preference, managing splash panes, etc. Any new frames spawned by this one would also be instances of this `JFrame` subclass. The only thing you have to remember is to instantiate your subclass, instead of `JFrame`. I don't think there's any substitute for remembering to do this, but at least now it's a matter of remembering a subclass instead of a `setIconImage` call (among possibly other features).
There is another way, but its more of a "hack" then a real fix.... If you are distributing the JRE with your Application, you could replace the coffee cup icon resource in the java exe/dll/rt.jar wherever that is with your own icon. It might not be very legit, but it is a possibility...
How do I set an Application's Icon Globally in Swing?
[ "", "java", "swing", "" ]
I'm writing an application which reads large arrays of floats and performs some simple operations with them. I'm using floats, because I thought it'd be faster than doubles, but after doing some research I've found that there's some confusion about this topic. Can anyone elaborate on this?
The short answer is, "use whichever precision is required for acceptable results." Your one guarantee is that operations performed on floating point data are done in at least the highest precision member of the expression. So multiplying two **float**'s is done with at least the precision of **float**, and multiplying a **float** and a **double** would be done with at least double precision. The standard states that "[floating-point] operations may be performed with higher precision than the result type of the operation." Given that the JIT for .NET attempts to leave your floating point operations in the precision requested, we can take a look at documentation from Intel for speeding up our operations. On the Intel platform your floating point operations may be done in an intermediate precision of 80 bits, and converted down to the precision requested. From Intel's guide to C++ Floating-point Operations1 (sorry only have dead tree), they mention: > * Use a single precision type (for example, float) unless the extra precision obtained through double or long double is required. Greater precision types increase memory size and bandwidth requirements. > ... > * Avoid mixed data type arithmetic expressions That last point is important as [you can slow yourself down with unnecessary casts to/from float and double](http://weblog.ikvm.net/PermaLink.aspx?guid=f300c4e1-15b0-45ed-b6a6-b5dc8fb8089e), which result in JIT'd code which requests the x87 to cast away from its 80-bit intermediate format in between operations! *1. Yes, it says C++, but the C# standard plus knowledge of the CLR lets us know the information for C++ should be applicable in this instance.*
I just read the "Microsoft .NET Framework-Application Development Foundation 2nd" for the MCTS exam 70-536 and there is a note on page 4 (chapter 1): > **NOTE Optimizing performance with built-in types** > The runtime optimizes the performance of 32-bit integer types (Int32 and UInt32), so use those types for counters and other frequently accessed integral variables. For floating-point operations, Double is the most efficient type because those operations are optimized by hardware. It's written by Tony Northrup. I don't know if he's an authority or not, but I would expect that the official book for the .NET exam should carry some weight. It is of course not a gaurantee. I just thought I'd add it to this discussion.
Are doubles faster than floats in C#?
[ "", "c#", "performance", "floating-point", "precision", "" ]
How would I upload a file to a webserver using c++ and MFC. We are not using .Net. Would I need to open a socket and do everything myself? If so, where is a good reference to follow?
You don't want to use direct socket calls. It's hard to get HTTP right this way. The easier way is to the WinINet APIs. Check out the docs for InternetOpen, this will likely be the first call you make. Functions you will likely need: * InternetOpen * InternetConnect * HttpOpenRequest * HttpSendRequest * HttpQueryInfo * InternetCloseHandle You can find docs for all of these on msdn
Here is the code I ended up using. I stripped out the error checking, and other notification stuff. This does a multi-part form upload. ``` DWORD dwTotalRequestLength; DWORD dwChunkLength; DWORD dwReadLength; DWORD dwResponseLength; CHttpFile* pHTTP = NULL; dwChunkLength = 64 * 1024; void* pBuffer = malloc(dwChunkLength); CFile file ; CInternetSession session("sendFile"); CHttpConnection *connection = NULL; try { //Create the multi-part form data that goes before and after the actual file upload. CString strHTTPBoundary = _T("FFF3F395A90B452BB8BEDC878DDBD152"); CString strPreFileData = MakePreFileData(strHTTPBoundary, file.GetFileName()); CString strPostFileData = MakePostFileData(strHTTPBoundary); CString strRequestHeaders = MakeRequestHeaders(strHTTPBoundary); dwTotalRequestLength = strPreFileData.GetLength() + strPostFileData.GetLength() + file.GetLength(); connection = session.GetHttpConnection("www.YOURSITE.com",NULL,INTERNET_DEFAULT_HTTP_PORT); pHTTP = connection->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T("/YOUURL/submit_file.pl")); pHTTP->AddRequestHeaders(strRequestHeaders); pHTTP->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE); //Write out the headers and the form variables pHTTP->Write((LPSTR)(LPCSTR)strPreFileData, strPreFileData.GetLength()); //upload the file. dwReadLength = -1; int length = file.GetLength(); //used to calculate percentage complete. while (0 != dwReadLength) { dwReadLength = file.Read(pBuffer, dwChunkLength); if (0 != dwReadLength) { pHTTP->Write(pBuffer, dwReadLength); } } file.Close(); //Finish the upload. pHTTP->Write((LPSTR)(LPCSTR)strPostFileData, strPostFileData.GetLength()); pHTTP->EndRequest(HSR_SYNC); //get the response from the server. LPSTR szResponse; CString strResponse; dwResponseLength = pHTTP->GetLength(); while (0 != dwResponseLength ) { szResponse = (LPSTR)malloc(dwResponseLength + 1); szResponse[dwResponseLength] = '\0'; pHTTP->Read(szResponse, dwResponseLength); strResponse += szResponse; free(szResponse); dwResponseLength = pHTTP->GetLength(); } AfxMessageBox(strResponse); //close everything up. pHTTP->Close(); connection->Close(); session.Close(); CString CHelpRequestUpload::MakeRequestHeaders(CString& strBoundary) { CString strFormat; CString strData; strFormat = _T("Content-Type: multipart/form-data; boundary=%s\r\n"); strData.Format(strFormat, strBoundary); return strData; } CString CHelpRequestUpload::MakePreFileData(CString& strBoundary, CString& strFileName) { CString strFormat; CString strData; strFormat = _T("--%s"); strFormat += _T("\r\n"); strFormat += _T("Content-Disposition: form-data; name=\"user\""); strFormat += _T("\r\n\r\n"); strFormat += _T("%s"); strFormat += _T("\r\n"); strFormat += _T("--%s"); strFormat += _T("\r\n"); strFormat += _T("Content-Disposition: form-data; name=\"email\""); strFormat += _T("\r\n\r\n"); strFormat += _T("%s"); strFormat += _T("\r\n"); strFormat += _T("--%s"); strFormat += _T("\r\n"); strFormat += _T("Content-Disposition: form-data; name=\"filename\"; filename=\"%s\""); strFormat += _T("\r\n"); strFormat += _T("Content-Type: audio/x-flac"); strFormat += _T("\r\n"); strFormat += _T("Content-Transfer-Encoding: binary"); strFormat += _T("\r\n\r\n"); strData.Format(strFormat, strBoundary, m_Name, strBoundary, m_Email, strBoundary, strFileName); return strData; } CString CHelpRequestUpload::MakePostFileData(CString& strBoundary) { CString strFormat; CString strData; strFormat = _T("\r\n"); strFormat += _T("--%s"); strFormat += _T("\r\n"); strFormat += _T("Content-Disposition: form-data; name=\"submitted\""); strFormat += _T("\r\n\r\n"); strFormat += _T(""); strFormat += _T("\r\n"); strFormat += _T("--%s--"); strFormat += _T("\r\n"); strData.Format(strFormat, strBoundary, strBoundary); return strData; } ```
MFC File upload
[ "", "c++", "mfc", "upload", "" ]
I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server. Has anyone dealt with this that can give me some pointers?
poking around the facebox.js I came across this line in the function init(settings)... ``` $('body').append($.facebox.settings.faceboxHtml) ``` I changed that to ... ``` $('#aspnetForm').append($.facebox.settings.faceboxHtml) ``` and it loads up in the form tag, not sure yet if there are any side effects
You can use this code to register the PostBack event: ``` btn.OnClientClick = string.Format("{0}; $.facebox.close();",ClientScript.GetPostBackEventReference(btn, null)); ``` this will let the button fires a PostBack.
JQuery Facebox Plugin : Get it inside the form tag
[ "", "c#", "asp.net", "jquery", "facebox", "" ]
Our team has been experiencing a recurring problem with velocity templates. Upon rendering, some throw a RuntimeException with the message "Template.merge() failure - Unable to render Velocity Template, '/template.vm'". We have not been able to reproduce the problem and the documentation on the web is pretty insufficient. The problem is not consistently reproducible - the same templates whose rendering sometimes causes the error also manage to display without problems at other times. The Template class [source code](http://www.docjar.com/docs/api/org/apache/velocity/Template.html) is also of little help. Thank you in advance. --- Edit: Based on Nathan Bubna's response I need to clarify that we are using Velocity version 1.4. --- Edit: Since it was pointed out that a stack trace would be beneficial, here it is: 2008-09-15 11:07:57,336 ERROR velocity - Template.merge() failure. The document is null, most likely due to parsing error. 2008-09-15 11:07:57,336 ERROR VelocityResult - Unable to render Velocity Template, '/search/[template-redacted].vm' java.lang.Exception: Template.merge() failure. The document is null, most likely due to parsing error. at org.apache.velocity.Template.merge(Template.java:277) at com.opensymphony.webwork.dispatcher.VelocityResult.doExecute(VelocityResult.java:91) at com.opensymphony.webwork.dispatcher.WebWorkResultSupport.execute(WebWorkResultSupport.java:109) at com.opensymphony.xwork.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:258) at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:182) at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35) at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164) at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35) at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164) at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35) at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164) at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35) at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164) at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35) at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164) at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35) at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164) at com.opensymphony.xwork.DefaultActionProxy.execute(DefaultActionProxy.java:116) at com.opensymphony.webwork.dispatcher.ServletDispatcher.serviceAction(ServletDispatcher.java:272) at com.opensymphony.webwork.dispatcher.ServletDispatcher.service(ServletDispatcher.java:237) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at com.opensymphony.module.sitemesh.filter.PageFilter.doFilter(PageFilter.java:39) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at org.nanocontainer.nanowar.webwork2.PicoObjectFactoryFilter.doFilter(PicoObjectFactoryFilter.java:46) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at org.nanocontainer.nanowar.ServletRequestContainerFilter.doFilter(ServletRequestContainerFilter.java:44) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at com.bostoncapital.stuyvesant.RememberUserNameFilter.doFilter(RememberUserNameFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:526) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:825) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:738) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:526) at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684) at java.lang.Thread.run(Unknown Source)
What version of Velocity are you using? There were some race conditions in old versions that caused this. Most were squashed in the Velocity 1.5 release. Though i would personally recommend using Velocity 1.6-beta1. It has vastly improved performance (memory and speed) and a lot of minor bug fixes that didn't make it into 1.5. Edit: Since you say you are using 1.4, then, yes, i'm sure this is the race condition we fixed. Please consider upgrading. 1.6 is definitely your best bet, as it has the fix for your bug and improved performance. 1.6 final should be out very soon.
I am working on the same bug right now, on our website. It does appear to be a race condition: I can reproduce it consistently using multiple processes fetching the same page, but never reproduce it if I serialize the requests. I am using velocity-1.5; I tried migrating to 1.6-beta1 but see other errors. **RESOLVED**: see comments below
What causes a velocity Template.merge() failure? How does one avoid it?
[ "", "java", "velocity", "" ]
Is it possible to call a JavaScript function from the IMG SRC tag to get an image url? Like this: ``` <IMG SRC="GetImage()" /> <script language="javascript"> function GetImage() {return "imageName/imagePath.jpg"} </script> ``` This is using .NET 2.0.
Nope. It's not possible, at least not in all browsers. You can do something like this instead: ``` <img src="blank.png" id="image" alt="just nothing"> <script type="text/javascript"> document.getElementById('image').src = "yourpicture.png"; </script> ``` Your favourite JavaScript framework will provide nicer ways :)
If you're in the mood for hacks, this works as well. ``` <img src='blah' onerror="this.src='url to image'"> ```
IMG SRC tags and JavaScript
[ "", "javascript", "asp.net", "image", "" ]
I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The original author wrote the code using a single thread, then later modified it to allow it to use multiple threads. In the code he defines a constant; ``` // number of threads public static final int THREADS = Runtime.getRuntime().availableProcessors(); ``` Which then sets the number of threads that are used to create the image. I understand his reasoning that the number of threads cannot be greater than the number of available processors, so set it the the amount to get the full potential out of the processor(s). Is this correct? or is there a better way to utilize the full potential of the processor(s)? EDIT: To give some more clarification, The specific algorithm that is being threaded scales to the resolution of the picture being created, (1 thread per pixel). That is obviously not the best solution though. The work that this algorithm does is what takes all the time, and is wholly mathematical operations, there are no locks or other factors that will cause any given thread to sleep. I just want to maximize the programs CPU utilization to decrease the time to completion.
Threads are fine, but as others have noted, you have to be highly aware of your bottlenecks. Your algorithm sounds like it would be susceptible to cache contention between multiple CPUs - this is particularly nasty because it has the potential to hit the performance of all of your threads (normally you think of using multiple threads to continue processing while waiting for slow or high latency IO operations). Cache contention is a very important aspect of using multi CPUs to process a highly parallelized algorithm: Make sure that you take your memory utilization into account. If you can construct your data objects so each thread has it's own memory that it is working on, you can greatly reduce cache contention between the CPUs. For example, it may be easier to have a big array of ints and have different threads working on different parts of that array - but in Java, the bounds checks on that array are going to be trying to access the same address in memory, which can cause a given CPU to have to reload data from L2 or L3 cache. Splitting the data into it's own data structures, and configure those data structures so they are thread local (might even be more optimal to use [ThreadLocal](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html) - that actually uses constructs in the OS that provide guarantees that the CPU can use to optimize cache. The best piece of advice I can give you is test, test, test. Don't make assumptions about how CPUs will perform - there is a *huge* amount of magic going on in CPUs these days, often with counterintuitive results. Note also that the JIT runtime optimization will add an additional layer of complexity here (maybe good, maybe not).
On the one hand, you'd like to think Threads == CPU/Cores makes perfect sense. Why have a thread if there's nothing to run it? The detail boils down to "what are the threads doing". A thread that's idle waiting for a network packet or a disk block is CPU time wasted. If your threads are CPU heavy, then a 1:1 correlation makes some sense. If you have a single "read the DB" thread that feeds the other threads, and a single "Dump the data" thread and pulls data from the CPU threads and create output, those two could most likely easily share a CPU while the CPU heavy threads keep churning away. The real answer, as with all sorts of things, is to measure it. Since the number is configurable (apparently), configure it! Run it with 1:1 threads to CPUs, 2:1, 1.5:1, whatever, and time the results. Fast one wins.
How many threads should I use in my Java program?
[ "", "java", "multithreading", "" ]
I'm thinking floats. For the record I'm also using NHibernate.
`decimal` You won't lose precision due to rounding.
The answer is application-dependent. Others have pointed out that decimal is better than float for representing an exact value. But sometimes it's better to use a float for the increased precision (e.g. a set of calculated weights that add up to 100% is probably better represented as a float)
What types should I use to represent percentages in C# and SQL Server?
[ "", "c#", "sql-server", "" ]
How can I know what encoding will be used by PHP when sending data to the browser? I.e. with the Cotent-Type header, for instance: iso-8859-1.
Usually Apache + PHP servers of webhosters are configured to send out **NO `charset` header**. The shortest way to test how your server is configured are these: * Use [this tool to see the server header](http://www.seoconsultants.com/tools/headers) by getting any one of your pages on your webiste. If in the server headers you see a `charset` it means your server is using it, usually it won't contain a `charset`. * Another way is to run this simple script on your server: `<?php echo ini_get('default_charset'); ?>` As said above this usually prints out an empty string, if different it will show you the `charset` of the PHP. The 2nd solution is supposing Apache is not configured with `AddDefaultCharset some_charset` which is not usually the case, but in such case I'm afraid Apache setting might override PHP deafult\_charset ini directive.
You can use the header() solution that William suggested, however if you are running Apache, and the Apache config is using a default charset, that will win everytime (Internet Explorer will go crazy) See: [AddDefaultCharset](http://httpd.apache.org/docs/2.0/mod/core.html#adddefaultcharset)
PHP: Current encoding used to send data to the browser
[ "", "php", "header", "character-encoding", "" ]
I am **very** new to the entity framework, so please bear with me... How can I relate two objects from different contexts together? The example below throws the following exception: > System.InvalidOperationException: The > relationship between the two objects > cannot be defined because they are > attached to different ObjectContext > objects. ``` void MyFunction() { using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123); er.Roles = GetDefaultRole(); model.SaveChanges(); } } private static Roles GetDefaultRole() { Roles r = null; using (TCPSEntities model = new TCPSEntities()) { r = model.Roles.First(p => p.RoleId == 1); } return r; } ``` Using one context is not an option because we are using the EF in an ASP.NET application.
You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity. EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs. You could simply pass the context.. IE: ``` void MyFunction() { using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123); er.Roles = GetDefaultRole(model); model.SaveChanges(); } } private static Roles GetDefaultRole(TCPSEntities model) { Roles r = null; r = model.Roles.First(p => p.RoleId == 1); return r; } ```
Another approach that you could use here is to detach objects from one context, and then attach them to another context. That's a bit of a hack, and it may not work in your situation, but it might be an option. ``` public void GuestUserTest() { SlideLincEntities ctx1 = new SlideLincEntities(); GuestUser user = GuestUser.CreateGuestUser(); user.UserName = "Something"; ctx1.AddToUser(user); ctx1.SaveChanges(); SlideLincEntities ctx2 = new SlideLincEntities(); ctx1.Detach(user); user.UserName = "Something Else"; ctx2.Attach(user); ctx2.SaveChanges(); } ```
How to relate objects from multiple contexts using the Entity Framework
[ "", "c#", ".net", "entity-framework", "" ]
I have a LinkedList, where Entry has a member called id. I want to remove the Entry from the list where id matches a search value. What's the best way to do this? I don't want to use Remove(), because Entry.Equals will compare other members, and I only want to match on id. I'm hoping to do something kind of like this: ``` entries.RemoveWhereTrue(e => e.id == searchId); ``` edit: Can someone re-open this question for me? It's NOT a duplicate - the question it's supposed to be a duplicate of is about the List class. List.RemoveAll won't work - that's part of the List class.
``` list.Remove(list.First(e => e.id == searchId)); ```
Here's a simple solution: ``` list.Remove(list.First((node) => node.id == searchId)); ```
How do I remove an element that matches a given criteria from a LinkedList in C#?
[ "", "c#", ".net", "data-structures", "" ]
In this code I am debugging, I have this code snipit: ``` ddlExpYear.SelectedItem.Value.Substring(2).PadLeft(2, '0'); ``` What does this return? I really can't run this too much as it is part of a live credit card application. The DropDownList as you could imagine from the name contains the 4-digit year. UPDATE: Thanks everyone. I don't do a lot of .NET development so setting up a quick test isn't as quick for me.
It takes the last two digits of the year and pads the left side with zeroes to a maximum of 2 characters. Looks like a "just in case" for expiration years ending in 08, 07, etc., making sure that the leading zero is present.
This prints "98" to the console. ``` class Program { static void Main(string[] args) { Console.Write("1998".Substring(2).PadLeft(2, '0')); Console.Read(); } } ```
Can't figure out what this SubString.PadLeft is doing
[ "", "c#", "substring", "padleft", "" ]
For RMI on server-side, do we need to start `rmiregistry` program, or just call `LocateRegistry.createRegistry`? If both are possible, what are the advantages and disadvantages?
They're the same thing... `rmiregistry` is a separate program, which you can run from a command line or a script, while `LocateRegistry.createRegistry` does the same thing programatically. In my experience, for "real" servers you will want to use `rmiregistry` so that you know it's always running regardless of whether or not the client application is started. `createRegistry` is very useful for testing, as you can start and stop the registry from your test as necessary.
If we start rmiregistry first, RmiServiceExporter would register itself to the running rmiregistry. In this case, we have to set the system property 'java.rmi.server.codebase' to where the 'org.springframework.remoting.rmi.RmiInvocationWrapper\_Stub' class can be found. Otherwise, the RmiServiceExporter would not be started and got the exception " ClassNotFoundException class not found: org.springframework.remoting.rmi.RmiInvocationWrapper\_Stub; nested exception is: ..." If your rmi server, rmi client and rmiregistry can access the same filesystem, you may want the system property to be automatically configured to where the spring.jar can be found on the shared filesystem. The following utility classes and spring configuration show how this can be achieved. ``` abstract public class CodeBaseResolver { static public String resolveCodeBaseForClass(Class<?> clazz) { Assert.notNull(clazz); final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource(); if (codeSource != null) { return codeSource.getLocation().toString(); } else { return ""; } } } public class SystemPropertyConfigurer { private Map<String, String> systemProperties; public void setSystemProperties(Map<String, String> systemProperties) { this.systemProperties = systemProperties; } @PostConstruct void init() throws BeansException { if (systemProperties == null || systemProperties.isEmpty()) { return; } for (Map.Entry<String, String> entry : systemProperties.entrySet()) { final String key = entry.getKey(); final String value = SystemPropertyUtils.resolvePlaceholders(entry.getValue()); System.setProperty(key, value); } } } <bean id="springCodeBase" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="xx.CodeBaseResolver.resolveCodeBaseForClass" /> <property name="arguments"> <list> <value>org.springframework.remoting.rmi.RmiInvocationWrapper_Stub</value> </list> </property> </bean> <bean id="springCodeBaseConfigurer" class="xx.SystemPropertyConfigurer" depends-on="springCodeBase"> <property name="systemProperties"> <map> <entry key="java.rmi.server.codebase" value-ref="springCodeBase" /> </map> </property> </bean> <bean id="rmiServiceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter" depends-on="springCodeBaseConfigurer"> <property name="serviceName" value="XXX" /> <property name="service" ref="XXX" /> <property name="serviceInterface" value="XXX" /> <property name="registryPort" value="${remote.rmi.port}" /> </bean> ``` The above example shows how system property be set automatically only when rmi server, rmi client and rmi registry can access the same filesystem. If that is not true or spring codebase is shared via other method (e.g. HTTP), you may modify the CodeBaseResolver to fit your need.
RMI server: rmiregistry or LocateRegistry.createRegistry
[ "", "java", "rmi", "rmiregistry", "" ]
Using VC2005, I have 3 projects to build: * libA (contains a typelib, results in libA.dll): IDL has a line `library libA { ...` * libB (contains a typelib importing libA, results in libB.dll): IDL has a line `importlib( "libA " );` * libC (imports libB): one of the source files contains `#import <libB.dll>` the `#import <libB.dll>` is handled by the compiler in the following way (according to documentation): 1. search directories of %PATH% 2. search directories of %LIB% 3. search the "additional include paths" (/I compiler option) When compiling libC, I can see that cl.exe clearly is able to find the libA.dll on the executable path (using Filemon.exe) VC error C4772: #import of typelib with another dependency However, still the libA namespace is *not* found and all references to libA types are replaced by `__missing_type__` (edit) Meanwhile, I found out the problem only appears when using the debug dlls. Anyone seen this problem before? And solved it?
Finally Found It! In the Visual Studio project, the A.idl file in LibA had the **MkTypeLib Compatible** setting ON. This overruled the behaviour inherited from the A project. To make things worse, it was only ON in the Debug configuration. The consequence was that for every ``` typedef [public] tagE enum { cE1, cE2 } eE; ``` This resulted in the `tagE` not being defined in the resulting typelib. When LibB did it's `import( "A.dll" )`, all references to `tagE` were replaced with `__missing_type__`...
Are you explicitly setting the project's dependencies? In other words have you set up the solution in the IDE so that project C depends on project B, and project B depends on project A?
Indirect Typelib not imported well from Debug dll
[ "", "c++", "visual-c++", "import", "typelib", "" ]
I want to save the objects I generated in a program. After restart the App should load automaticly all Objects in an Array. I want to write them in a file and parse them after restart. Are the other smarter possibilities than do it by hand? Thank you
You can use the *Berkeley DB* `PersistentMap` class to save your (`Serializable`) objects in a `Map` implementation (a cache) which persists them to a file. It's pretty simple to use and means you don't have to worry about what to save where. Three things to note about serialization: 1. How are you going to cope with schema changes (i.e. changing what data your classes consist of - adding a new field for example) 2. What happens if your file(s) become corrupted? Depending on how reliable your program's storage needs to be will affect your decision of how you save the data which your objects implicitly contain. Remember, you can always use a relational database such as **MySQL** and then convert this data into your objects 3. Do you need to be able to view or query the data *outside* of your program? What if you want to answer some simple question like "How many object's have property X?" Easy to do if you've used a (relational) database; not so easy if you've serialized stuff to files!
Yes, the concept you are looking for is called serialization. There's a fine tutorial at Sun [here](http://java.sun.com/developer/technicalArticles/Programming/serialization/). The idea is that classes you want to persist have to implement the Serializable interface. After that you use java.io.ObjectOutputStream.writeObject() to write the object to a file and java.io.ObjectInputStream.readObject() to read it back. You can't serialize everything, as there are things that don't make sense to serialize, but you can work around them. Here's a quote about that: > The basic mechanism of Java > serialization is simple to use, but > there are some more things to know. As > mentioned before, only objects marked > Serializable can be persisted. The > java.lang.Object class does not > implement that interface. Therefore, > not all the objects in Java can be > persisted automatically. The good news > is that most of them -- like AWT and > Swing GUI components, strings, and > arrays -- are serializable. > > On the other hand, certain > system-level classes such as Thread, > OutputStream and its subclasses, and > Socket are not serializable. Indeed, > it would not make any sense if they > were. For example, thread running in > my JVM would be using my system's > memory. Persisting it and trying to > run it in your JVM would make no sense > at all. Another important point about > java.lang.Object not implementing the > Serializable interface is that any > class you create that extends only > Object (and no other serializable > classes) is not serializable unless > you implement the interface yourself > (as done with the previous example). > > That situation presents a problem: > what if we have a class that contains > an instance of Thread? In that case, > can we ever persist objects of that > type? The answer is yes, as long as we > tell the serialization mechanism our > intentions by marking our class's > Thread object as transient.
Java: Save objects in a textfile? Are there readymade solutions?
[ "", "java", "object", "store", "flat-file", "" ]
To pop up the UAC dialog in Vista when writing to the HKLM registry hive, we opt to not use the Win32 Registry API, as when Vista permissions are lacking, we'd need to relaunch our entire application with administrator rights. Instead, we do this trick: ``` ShellExecute(hWnd, "runas" /* display UAC prompt on Vista */, windir + "\\Reg", "add HKLM\\Software\\Company\\KeyName /v valueName /t REG_MULTI_TZ /d ValueData", NULL, SW_HIDE); ``` This solution works fine, besides that our application is a 32-bit one, and it runs the REG.EXE command as it would be a 32-bit app using the WOW compatibility layer! :( If REG.EXE is ran from the command line, it's properly ran in 64-bit mode. This matters, because if it's ran as a 32-bit app, the registry keys will end up in the wrong place due to [registry reflection](http://msdn.microsoft.com/en-us/library/aa384235(VS.85).aspx). So is there any way to launch a 64-bit app programmatically from a 32-bit app and not have it run using the WOW64 subsystem like its parent 32-bit process (i.e. a "\*" suffix in the Task Manager)?
try this (from a 32bit process): ``` > %WINDIR%\sysnative\reg.exe query ... ``` (found that [here](http://ovidiupl.spaces.live.com/blog/cns!1E8A6038167E4BE9!925.entry)).
Whether a 32-bit or 64-bit native (unmanaged) program is run depends solely on the executable. There are two copies of `reg.exe`, in C:\Windows\System32 (64-bit) and C:\Windows\SysWOW64 (32-bit). Because you don't specify a path, you're getting whatever appears first in the `PATH` environment variable, which is the 32-bit version for a 32-bit process. You should really factor this function out into a separate program or COM object, and mark the program with a manifest, or launch the COM object using the [COM elevation moniker](http://msdn.microsoft.com/en-us/library/ms679687(VS.85).aspx).
How to launch a Windows process as 64-bit from 32-bit code?
[ "", "c++", "winapi", "64-bit", "registry", "" ]
What role is Spring taking in Struts + Spring + Hibernate?
Spring provides many different "modules" and different programmers will use different parts of Spring. However, commonly in this sort of stack, you will see Spring being used as a provider of * An inversion of control container for dependency injection * An abstraction to Hibernate called "HibernateTemplate" * Framework classes for simplifying Aspect Oriented Programming * Transaction support, often "declaratively" via the IoC container and AOP.
Well, Hibernate handles the persistence part, JSP handles your GUI, Struts controls the flow between pages/actions/etc, and Spring can manage all your beans which contain the main business logic, instead of using EJB. Plus it can simplify the coding of your Hibernate DAO's and transaction managing. Instead of having to code your Locator to obtain some EJB through JNDI and all that stuff, you can just get the Spring ApplicationContext and ask for the bean you need. All the beans defined in Spring can be interconnected. If you have to connect one of your beans to an external EJB through JNDI you can even do so without any code (Spring offers a JNDI proxy object which obtains the reference you give it and returns it as an object with the interface you specify). This can help you simplify unit testing of all those beans and change the config without recoding anything; you can use one of Spring's PlatformTransactionManagers to manage a DataSource or point it to a J2EE container's JTA manager; define your own pooled DataSource or use your container's DataSource published through JNDI, etc.
What is the role of Spring in Struts + Spring + Hibernate?
[ "", "java", "hibernate", "spring", "struts", "" ]
Typically I use `E_ALL` to see anything that PHP might say about my code to try and improve it. I just noticed a error constant `E_STRICT`, but have never used or heard about it, is this a good setting to use for development? The manual says: > Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. So I'm wondering if I'm using the best `error_reporting` level with `E_ALL` or would that along with `E_STRICT` be the best? Or is there any other combination I've yet to learn?
In PHP 5, the things covered by `E_STRICT` are not covered by `E_ALL`, so to get the most information, you need to combine them: ``` error_reporting(E_ALL | E_STRICT); ``` In PHP 5.4, `E_STRICT` will be included in `E_ALL`, so you can use just `E_ALL`. You can also use ``` error_reporting(-1); ``` which will always enable *all* errors. Which is more semantically correct as: ``` error_reporting(~0); ```
Use the following in php.ini: ``` error_reporting = E_ALL | E_STRICT ``` Also you should install [Xdebug](http://xdebug.org "Xdebug"), it can highlight your errors in blinding bright colors and print useful detailed information. Never let any error or notice in your code, even if it's harmless.
What is the recommended error_reporting() setting for development? What about E_STRICT?
[ "", "php", "error-reporting", "" ]
Ideally something that will work with Oracle, MS SQL Server, MySQL and Posgress.
if you mean common lisp by lisp, then there's **[cl-rdbms](http://common-lisp.net/project/cl-rdbms/)**. it is heavily tested on postgres (uses [postmodern](http://common-lisp.net/project/postmodern/) as the backend lib), it has a toy sqlite backend and it also has an OCI based oracle backend. it supports abstracting away the different sql dialects, has an sql quasi-quote syntax extension installable on e.g. the [] characters. i'm not sure if it's the best, and i'm biased anyway... :) but we ended up rolling our own lib after using [clsql](http://clsql.b9.com/) for a while, which is i think the most widely used sql lib for cl. see [cliki page about sql](http://www.cliki.net/SQL) for a further reference.
At the moment there's no open-source library that supports all the SQL backends you mention. [CLSQL](http://clsql.b9.com/) comes quite close (lacking only support for MS SQL). The alternatives are: * [CL-RDBMS](http://common-lisp.net/project/cl-rdbms/) (which supports Oracle, Postgres through Postmodern and SQLite3) * [Postmodern](http://common-lisp.net/project/postmodern/) (only Postgres). If you can use a commercial Lisp, you can give a try to [CommonSQL](http://www.lispworks.com/documentation/sql-tutorial/index.html) included with Lispworks, which supports all the databases you mentioned. CLSQL looks like the most popular open source library at the moment. Unfortunately, it seems to suffer from bit rot, and the developers had to make some compromises to support all those platforms. If the RDB backend is not a constraint, then I recommend Postmodern. It is very well documented and has a clean API (and a nice small language compiled to SQL). Also, it is well maintained and small enough to keep being understandable and extensible. It focuses only on Postgres, not trying to be all things for all people.
What is the best SQL library for use in Common Lisp?
[ "", "sql", "database", "postgresql", "lisp", "common-lisp", "" ]
if I call php's `parse_ini_file("foo.ini")`, in what paths does it look for foo.ini ? the include path? the function's documentation doesn't mention it.
The filename argument for parse\_ini\_file is a standard php filename, so the same rules will apply as opening a file using [fopen](https://www.php.net/manual/en/function.fopen.php). You must either specify an absolute file path ("/path/to/my.ini") or a path relative to your current working directory ("my.ini"). See [getcwd](https://www.php.net/manual/en/function.getcwd.php) for your current working directory. Unlike the default fopen command, if a relative path is specified ("my.ini") parse\_ini\_file **will** search include paths after searching your current working directory. I verified this in php 5.2.6.
I would imagine it only looks in the current working directory - See <https://www.php.net/manual/en/function.getcwd.php> if you want to know what that is. You can always find a path relative to your application by basing it on $\_SERVER['DOCUMENT\_ROOT']
PHP parse_ini_file() - where does it look?
[ "", "php", "file", "parsing", "path", "ini", "" ]
Since I upgraded to Visual Studio 2008 from vs2005, I have found a very annoying behaviour when debugging large projects. If I attempt to step into inline code, the debugger appears to lock up for tens of seconds. Each time that I step inside such a function, there is a similar pause. Has anyone experienced this and is anyone aware of a work around? Postscript: After learning that MS had a service pack for vs2008 and needing to get it because of other compiling issues, the problem that I was encountering with the debugger was resolved.
I used to get this - I think it's a bug with the 'Autos' debug window: <http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/eabc58b1-51b2-49ce-b710-15e2bf7e7516/>
I get delays like this when debugging ASP.NET apps and it seems to happen when a symbol(pdb) file is getting accessed in the background. The larger the library, the longer the wait. My delay is at most about 10 seconds, but it does seem to happen with symbols that have already been accessed. I do get a lot of 1-3 second waits when i try to step over items that cause VS to give me the "Step into Specific" message (<http://blogesh.wordpress.com/category/visual-studio-2008/> #3). Perhaps this may be causing a real blow up for you.
Visual Studio debugger slows down in in-line code
[ "", "c++", "windows", "visual-studio", "debugging", "" ]
I am writing a web server in Java and I want it to support HTTP 1.1 Keep-Alive connections. But how can I tell when the client is done sending requests for a given connection? (like a double end-of-line or something). Lets see how stackoverflow handles this very obscure question -- answers for which, on Google, are mired in technical specifications and obscure language. I want a plain-english answer for a non-C programmer :) --- I see. that confirms my suspicion of having to rely on the SocketTimeoutException. But i wasn't sure if there was something i could rely on from the client that indicates it is done with the connection--which would allow me to close the connections sooner in most cases--instead of waiting for the timeout. Thanks
If you're building your server to meet the standard, then you've got a lot of information to guide you here already. Simple spoken, *it should be based on a time since a connection was used, and not so much at the level of request data.* In a longer-winded way, the [practical considerations section](http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.1.4) of the HTTP/1.1 document has some guidance for you: > "Servers will usually have some > time-out value beyond which they will > no longer maintain an inactive > connection. Proxy servers might make > this a higher value since it is likely > that the client will be making more > connections through the same server. > The use of persistent connections > places no requirements on the length > (or existence) of this time-out for > either the client or the server." or > "When a client or server wishes to > time-out it SHOULD issue a graceful > close on the transport connection. > Clients and servers SHOULD both > constantly watch for the other side of > the transport close, and respond to it > as appropriate. If a client or server > does not detect the other side's close > promptly it could cause unnecessary > resource drain on the network."
> Lets see how stackoverflow handles this very obscure question -- answers for which, on Google, are mired in technical specifications and obscure language. I just put [When should I close an HTTP 1.1 connection?](http://www.google.co.uk/search?q=When+should+I+close+an+HTTP+1.1+connection%3F) into Google, and the third hit was HTTP Made Really Easy. In the table of contents, there is a link to a section entitled [Persistent Connections and the "Connection: close" Header](http://www.jmarshall.com/easy/http/#http1.1s4). This section is three paragraphs long, uses very simple language, and tells you exactly what you want to know. > I want a plain-english answer for a non-C programmer :) With all due respect, programming is a technical endeavour where the details matter a great deal. Reading technical documentation is an absolutely essential skill. Relying on "plain English" third-party interpretations of the specifications will only result in you doing a poor job.
How do I know WHEN to close an HTTP 1.1 Keep-Alive Connection?
[ "", "java", "http", "http-headers", "network-protocols", "" ]
I have read on Stack Overflow some people that have converting to C#2.0 to C#3, but is it really worth it? I have a project that is done at 75% before going in maintenance phase. I am asking to myself if it is worth it to switch to C#3.0? ### Update: The project will have a web interface now so before entering the maintenance phase we have to develop the web part (all was done for internal purposes with Windows Forms). Most parts will be resused (back-end). Most people have said that it wasn't worth it in the past because it was already at 75%... but now do you still think it's not worth it? ### What have been done finally Finally since we are continuing the project with the web interface we will update to 3.5 for the new year. Thank you everybody for all your input.
No, I would advise not. I would advise starting 3.5 on new projects only, unless there is a specific reason otherwise. You will not have any benefit from 3.5 by just recompiling, since your code is already written (or at least 75% of it). If you need to migrate to 3.5 in the future, you can easily do it. Of course, you will have code in 2.0 style, but what is done is done. * Be conservative, don't do something unless you need it. * An application which is 75% in C#2.0 and 25% in C#3.0 is not exactly a nice beast to maintain. A 100% C#2.0 application is certainly more maintainable. When you are going to start a new project, then by all means switch! The new framework version is very interesting and the switch is hotly recommended.
**Clarification** C# 3.5 doesn't exist. There is C#1.0, C#2.0 and C#3.0. Then there is .NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0, and .NET 3.5. We should not confuse the two. **C# 3.0 vs C#2.0** Now, is C#3.0 worth the move? I would say that with the existence of Extension methods and Lambda expressions, the answer is yes. These two features alone make for easier to read and quicker to write code. Add that to auto-implemented properties, LINQ, and partial methods, and C#3.0 shows itself to be an advantageous move. However, it is not necessarily beneficial to move an existing project. You have to weigh the pros and the cons, especially with regards to introducing new bugs and instability, before deciding to migrate existing work. For new projects, I'd say start with C#3.0.
Is the C# 2.0 to C# 3.0 transition worth it for this project?
[ "", "c#", ".net", "project-management", "code-migration", "" ]
I realize that since UNIX sockets are platform-specific, there has to be some non-Java code involved. Specifically, we're interested in using JDBC to connect to a MySQL instance which only has UNIX domain sockets enabled. It doesn't look like this is supported, but from what I've read it should be at least possible to write a SocketFactory for JDBC based on UNIX sockets *if* we can find a decent implementation of UNIX sockets for Java. Has anyone tried this? Does anyone know of such an implementation?
Checkout the JUDS library. It is a Java Unix Domain Socket library... <https://github.com/mcfunley/juds>
You could use junixsocket: <https://github.com/kohlschutter/junixsocket> It already provides code for connecting to MySQL from Java (Connector/J) via Unix sockets. One big advantage compared to other implementations is that junixsocket uses the standard Java Socket API.
UNIX socket implementation for Java?
[ "", "java", "unix", "jdbc", "unix-socket", "" ]
This has been an adventure. I started with the looping duplicate query located in [my previous question](https://stackoverflow.com/questions/161960), but each loop would go over all **17 million records**, **meaning it would take weeks** (just running `*select count * from MyTable*` takes my server 4:30 minutes using MSSQL 2005). I gleamed information from this site and at this [post](http://weblogs.sqlteam.com/jeffs/archive/2007/03/28/60146.aspx). And have arrived at the query below. The question is, is this the correct type of query to run on 17 million records for any type of performance? If it isn't, what is? SQL QUERY: ``` DELETE tl_acxiomimport.dbo.tblacxiomlistings WHERE RecordID in (SELECT RecordID FROM tl_acxiomimport.dbo.tblacxiomlistings EXCEPT SELECT RecordID FROM ( SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank FROM tl_acxiomimport.dbo.tblacxiomlistings ) al WHERE Rank = 1) ```
Seeing the QueryPlan would help. Is this feasible? ``` SELECT m.* into #temp FROM tl_acxiomimport.dbo.tblacxiomlistings m inner join (SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank FROM tl_acxiomimport.dbo.tblacxiomlistings ) al on (al.RecordID = m.RecordID and al.Rank = 1) truncate table tl_acxiomimport.dbo.tblacxiomlistings insert into tl_acxiomimport.dbo.tblacxiomlistings select * from #temp ```
Something's up with your DB, server, storage or some combination thereof. 4:30 for a select count \* seems VERY high. Run a DBCC\_SHOWCONTIG to see how fragmented your table is, this could cause a major performance hit over a table that size. Also, to add on to the comment by RyanKeeter, run the show plan and if there are any table scans create an index for the PK field on that table.
SQL Duplicate Delete Query over Millions of Rows for Performance
[ "", "sql", "sql-server", "duplicate-data", "sql-delete", "" ]
How to get the checked option in a group of radio inputs with JavaScript?
``` <html> <head> <script type="text/javascript"> function testR(){ var x = document.getElementsByName('r') for(var k=0;k<x.length;k++) if(x[k].checked){ alert('Option selected: ' + x[k].value) } } </script> </head> <body> <form> <input type="radio" id="r1" name="r" value="1">Yes</input> <input type="radio" id="r2" name="r" value="2">No</input> <input type="radio" id="r3" name="r" value="3">Don't Know</input> <br/> <input type="button" name="check" value="Test" onclick="testR()"/> </form> </body> </html> ```
<http://www.somacon.com/p143.php>
How to get the checked option in a group of radio inputs with JavaScript?
[ "", "javascript", "" ]
Does anyone know how to resize images proportionally using JavaScript? I have tried to modify the DOM by adding attributes `height` and `width` on the fly, but seems did not work on IE6.
To modify an image proportionally, simply only alter one of the width/height css properties, leave the other set to auto. ``` image.style.width = '50%' image.style.height = 'auto' ``` This will ensure that its aspect ratio remains the same. Bear in mind that browsers tend to *suck* at resizing images nicely - you'll probably find that your resized image looks horrible.
okay it solved, here is my final code ``` if($(this).width() > $(this).height()) { $(this).css('width',MaxPreviewDimension+'px'); $(this).css('height','auto'); } else { $(this).css('height',MaxPreviewDimension+'px'); $(this).css('width','auto'); } ``` Thanks guys
Javascript Image Resize
[ "", "javascript", "internet-explorer-6", "image-manipulation", "" ]
I'm developing an application targeting .NET Framework 2.0 using C# for which I need to be able to find the default application that is used for opening a particular file type. I know that, for example, if you just want to open a file using that application you can use something like: ``` System.Diagnostics.Process.Start( "C:\...\...\myfile.html" ); ``` to open an HTML document in the default browser, or ``` System.Diagnostics.Process.Start( "C:\...\...\myfile.txt" ); ``` to open a text file in the default text editor. However, what I want to be able to do is to open files that don't necessarily have a *.txt* extension (for example), in the default text editor, so I need to be able to find out the default application for opening *.txt* files, which will allow me to invoke it directly. I'm guessing there's some Win32 API that I'll need to P/Invoke in order to do this, however a quick look with both Google and MSDN didn't reveal anything of much interest; I did find a very large number of completely irrelevant pages, but nothing like I'm looking for.
You can check under registry section `HKEY_CLASSES_ROOT` for the extension and action details. Documentation for this is [on MSDN](http://msdn.microsoft.com/en-us/library/cc144148.aspx). Alternatively, you can use the [IQueryAssociations](http://msdn.microsoft.com/en-us/library/bb761400.aspx) interface.
All current answers are unreliable. The registry is an implementation detail and indeed such code is broken on my Windows 8.1 machine. The proper way to do this is using the Win32 API, specifically [AssocQueryString](http://msdn.microsoft.com/en-us/library/bb773471.aspx): ``` using System.Runtime.InteropServices; [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)] public static extern uint AssocQueryString( AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, ref uint pcchOut ); [Flags] public enum AssocF { None = 0, Init_NoRemapCLSID = 0x1, Init_ByExeName = 0x2, Open_ByExeName = 0x2, Init_DefaultToStar = 0x4, Init_DefaultToFolder = 0x8, NoUserSettings = 0x10, NoTruncate = 0x20, Verify = 0x40, RemapRunDll = 0x80, NoFixUps = 0x100, IgnoreBaseClass = 0x200, Init_IgnoreUnknown = 0x400, Init_Fixed_ProgId = 0x800, Is_Protocol = 0x1000, Init_For_File = 0x2000 } public enum AssocStr { Command = 1, Executable, FriendlyDocName, FriendlyAppName, NoOpen, ShellNewValue, DDECommand, DDEIfExec, DDEApplication, DDETopic, InfoTip, QuickTip, TileInfo, ContentType, DefaultIcon, ShellExtension, DropTarget, DelegateExecute, Supported_Uri_Protocols, ProgID, AppID, AppPublisher, AppIconReference, Max } ``` **Relevant documentation:** * [AssocQueryString](http://msdn.microsoft.com/en-us/library/bb773471.aspx) * [ASSOCF](https://web.archive.org/web/20130217094323/https://msdn.microsoft.com/en-us/library/windows/desktop/bb762471(v=vs.85).aspx) * [ASSOCSTR](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762475(v=vs.85).aspx) **Sample usage:** ``` static string AssocQueryString(AssocStr association, string extension) { const int S_OK = 0; const int S_FALSE = 1; uint length = 0; uint ret = AssocQueryString(AssocF.None, association, extension, null, null, ref length); if (ret != S_FALSE) { throw new InvalidOperationException("Could not determine associated string"); } var sb = new StringBuilder((int)length); // (length-1) will probably work too as the marshaller adds null termination ret = AssocQueryString(AssocF.None, association, extension, null, sb, ref length); if (ret != S_OK) { throw new InvalidOperationException("Could not determine associated string"); } return sb.ToString(); } ```
Finding the default application for opening a particular file type on Windows
[ "", "c#", ".net", "windows", "file-type", "" ]
The code is ``` return min + static_cast<int>(static_cast<double>(max - min + 1.0) * (number / (UINT_MAX + 1.0))); ``` number is a random number obtained by rand\_s. min and max are ints and represent minimum and maximum values (inclusive). If you provide a solution not using unsigned int as a number, please also explain how to make it be random. Please do not submit solutions using rand().
The `static_cast<double>` is redundant because the "+1.0"s will cause promotion to double anyway.
@[Andrew Stein](https://stackoverflow.com/questions/140786/how-to-simplify-this-code-generates-a-random-int-between-min-and-max-base-on-un#140826) In Numerical Recipes in C: The Art of Scientific Computing (William H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New York: Cambridge University Press, 1992 (2nd ed., p. 277)), the following comments are made: > "If you want to generate a random > integer between 1 and 10, you should > always do it by using high-order bits, > as in > > `j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));` > > and never by > anything resembling > > `j = 1 + (rand() % 10);` > > (which uses lower-order bits)." From `man 3 rand`
How to simplify this code (generates a random int between min and max base on unsigned int)?
[ "", "c++", "random", "" ]
I was browsing Scott Hanselman's [Developer Interview question list](http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx), and ran across this question: > What is wrong with > DateTime.Parse(myString)? While I know there are inherent risks in parsing a string of unknow format or origin, are there other reasons? Is it to use DateTime.ParseExact instead? Should it be myString.ToString() first?
In addition the locale problem, `DateTime.Parse()` could also throw an exception which you would then have to catch. Use `DateTime.TryParse()` or `DateTime.TryParseExact()` instead.
Using the current thread culture on the system is often a bad idea, as is "try a variety of formats, and see if any of them work." ParseExact with a specific culture is a much more controlled and precise approach. (Even if you specify the current culture, it makes it more obvious to readers that that's what's going on.)
What is wrong with DateTime.Parse(myString)?
[ "", "c#", "datetime", "" ]
Back in VB6, I wrote a few functions that would let me code without having to care about the difference between null and '' for strings, null and 0 for numbers, etc. Nothing kills my productivity more when coding than having to add special case code for dealing with data that might cause some irrelevant error; 9999/10000 if something I'm using as a number is null, then really I treat it as 0. I'm now in C#, and the difference between VB6 and C# 2005 is quite extensive...so I don't really know where to start to write my new set of helper functions, or if I even need to do them at all. So, I need to write a function that would accept a string, a database field, a request form/querysting field, ???, and then do whatever it could do to turn that into a Double, and return that to the calling procedure. I'd also need to do this for shorts, int16, int32, long, everything else I could possibly care about. Then I'd do this for strings. And Dates. Is this a worthwhile pursuit? Is there something in the framework or C# that I can use instead? I really desire something that would allow me to use data inline in calling other functions, and not having to create temporary variables, etc.
There are scads of conversion functions built-in. But... i'm not sure any of them do exactly what you want. Generally, .NET methods err on the side of caution when passed invalid input, and throw an exception. Fortunately, you can easily write a utility method to convert a string representation of a numeric value, an empty string empty, or null string to any output type: ``` public static T SafeConvert<T>(string s, T defaultValue) { if ( string.IsNullOrEmpty(s) ) return defaultValue; return (T)Convert.ChangeType(s, typeof(T)); } ``` Use: ``` SafeConvert(null, 0.0) == 0.0; SafeConvert("", 0.0) == 0.0; SafeConvert("0", 0.0) == 0.0; ``` This generic method takes its return type from the type of the second argument, which is used as the default value when the passed string is null or empty. Pass `0` and you'd get an `In32` back. Pass `0L`, `Int64`. And so on...
In C# most data types are not nullable (numbers, dates, etc), only strings are nullables. If you are getting data from a DB, then you will probable be working with [Nullable](http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx), or its syntactic-sugared version, int?, double?, DateTime?, etc. All nullables have [a method](http://msdn.microsoft.com/en-us/library/58x571cw.aspx) that allow you to get their actual value, or a default value if they are null. This should help you avoid creating those functions. As for strings, you have the String.IsNullOrEmpty(str) function. You also can [add extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx) if you want some special not-available functionality. Note that extension methods can be applied to null values, as long as you handle it in the code. For example: ``` public static string ValueOrDefault(this string str) { if (String.IsNullOrEmpty(str)) return MY_DEFAULT_VALUE; else return str; } ```
Helper functions for safe conversion from strings
[ "", "c#", "vb6", "type-conversion", "" ]
*[NOTE: This questions is similar to but **not the same** as [this one](https://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events).]* Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples: ``` ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ ``` Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled): ``` ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt ``` Of these, only four (`FrameworkDir`, `FrameworkSDKDir`, `VCInstallDir` and `VSInstallDir`) are set in the environment used for build-events. As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros. I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like: ``` postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" ``` Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated. Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?
As far as I can tell, the method described in the question is the only way to pass build variables to a Python script. Perhaps Visual Studio 2010 has something better?
You might want to look into PropertySheets. These are files containing Visual C++ settings, including user macros. The sheets can inherit from other sheets and are attached to VC++ projects using the PropertyManager View in Visual Studio. When you create one of these sheets, there is an interface for creating user macros. When you add a macro using this mechanism, there is a checkbox for setting the user macro as an environment variable. We use this type of mechanism in our build system to rapidly set up projects to perform out-of-place builds. Our various build directories are all defined as user macros. I have not actually verified that the environment variables are set in an external script called from post-build. I tend to use these macros as command line arguments to my post-build scripts - but I would expect accessing them as environment variables should work for you.
How to pass all Visual Studio 2008 "Macros" to Python script?
[ "", "python", "visual-studio", "visual-studio-2008", "visual-c++", "visual-studio-2005", "" ]
I've recently come across a problem which requires at least a basic degree of image processing, can I do this in Python, and if so, with what?
The best-known library is [PIL](http://effbot.org/zone/pil-index.htm). However if you are simply doing basic manipulation, you are probably better off with the Python bindings for [ImageMagick](http://wiki.python.org/moin/ImageMagick), which will be a good deal more efficient than writing the transforms in Python.
Depending on what you mean by "image processing", a better choice might be in the numpy based libraries: [mahotas](http://luispedro.org/software/mahotas), [scikits.image](http://scikit-image.org), or [scipy.ndimage](http://www.scipy.org/SciPyPackages/Ndimage). All of these work based on numpy arrays, so you can mix and match functions from one library and another. I started the website <http://pythonvision.org> which has more information on these.
Image Processing, In Python?
[ "", "python", "image", "image-processing", "image-manipulation", "" ]
I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that. ie. 50 + 100 = 150 int.Max + 50 = int.Max and not int.Min + 50
``` int penaltySum(int a, int b) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } ``` Update: If your penalties can be negative, this would be more appropriate: ``` int penaltySum(int a, int b) { if (a > 0 && b > 0) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } if (a < 0 && b < 0) { return (int.MinValue - a > b) ? int.MinValue : a + b; } return a + b; } ```
This answer... ``` int penaltySum(int a, int b) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } ``` fails the following test: ``` [TestMethod] public void PenaltySumTest() { int x = -200000; int y = 200000; int z = 0; Assert.AreEqual(z, penaltySum(x, y)); } ``` I would suggest implementing penaltySum() as follows: ``` private int penaltySum(int x, int y, int max) { long result = (long) x + y; return result > max ? max : (int) result; } ``` Notice I'm passing in the max value, but you could hardcode in the int.MaxValue if you would like. Alternatively, you could force the arithmetic operation overflow check and do the following: ``` private int penaltySum(int x, int y, int max) { int result = int.MaxValue; checked { try { result = x + y; } catch { // Arithmetic operation resulted in an overflow. } } return result; ``` }
Looking for a .NET Function that sums up number and instead of overflowing simply returns int.MaxValue
[ "", "c#", ".net", "math", "" ]
I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example: ``` select * from [User] where UserRolesBitmask | 22 = 22 ``` This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.
I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV. ``` from u in DataContext.Users where UserRolesBitmask | 22 == 22 select u ```
As a side note though for my fellow googlers: `UserRolesBitmask | 22 == 22` selects all users that don't have any other flags (its not a filter, its like saying `1==1`). What you want is either: * `UserRolesBitmask & 22 == 22` which selects users which have all the roles in their bitmask or: * `UserRolesBitmask & 22 != 0` which selects users which have at least one of the roles in their bitmask
Can LINQ (to SQL) do bitwise queries?
[ "", "c#", "linq-to-sql", "bitmask", "" ]
I've got a dictionary, something like ``` Dictionary<Foo,String> fooDict ``` I step through everything in the dictionary, e.g. ``` foreach (Foo foo in fooDict.Keys) MessageBox.show(fooDict[foo]); ``` It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned. How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."
If you read the documentation on MSDN you'll see this: "The order in which the items are returned is undefined." You can't gaurantee the order, because a Dictionary is not a list or an array. It's meant to look up a value by the key, and any ability to iterate values is just a convenience but the order is not behavior you should depend on.
You may be interested in the [`OrderedDicationary`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary) class that comes in [`System.Collections.Specialized`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized) namespace. If you look at the comments at the very bottom, someone from MSFT has posted this interesting note: > This type is actually misnamed; it is not an 'ordered' dictionary as such, but rather an 'indexed' dictionary. Although, today there is no equivalent generic version of this type, if we add one in the future it is likely that we will name such as type 'IndexedDictionary'. I think it would be trivial to derive from this class and make a generic version of OrderedDictionary.
Change cardinality of item in C# dictionary
[ "", "c#", "dictionary", "cardinality", "" ]
What is the best way to detect if a user leaves a web page? The `onunload` JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser). Creating one will probably be blocked by current browsers.
Try the `onbeforeunload` event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo *[onbeforeunload Demo](https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm)*. Alternatively, you can send out an [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) request when he leaves.
Mozilla Developer Network has a nice description and example of [onbeforeunload](https://developer.mozilla.org/en/DOM/window.onbeforeunload). If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data): ``` window.addEventListener('beforeunload', function(e) { var myPageIsDirty = ...; //you implement this logic... if(myPageIsDirty) { //following two lines will cause the browser to ask the user if they //want to leave. The text of this dialog is controlled by the browser. e.preventDefault(); //per the standard e.returnValue = ''; //required for Chrome } //else: user is allowed to leave without a warning dialog }); ```
Best way to detect when a user leaves a web page?
[ "", "javascript", "" ]
I'm trying to get started on what I'm hoping will be a relatively quick web application in Java, yet most of the frameworks I've tried (Apache Wicket, Liftweb) require so much set-up, configuration, and trying to wrap my head around Maven while getting the whole thing to play nice with Eclipse, that I spent the whole weekend just trying to get to the point where I write my first line of code! Can anyone recommend a simple Java webapp framework that doesn't involve Maven, hideously complicated directory structures, or countless XML files that must be manually edited?
Haven't tried it myself, but I think <http://www.playframework.org/> has a lot of potential... coming from php and classic asp, it's the first java web framework that sounds promising to me.... *Edit by original question asker - 2011-06-09* Just wanted to provide an update. I went with Play and it was exactly what I asked for. It requires very little configuration, and just works out of the box. It is unusual in that it eschews some common Java best-practices in favor of keeping things as simple as possible. In particular, it makes heavy use of static methods, and even does some introspection on the names of variables passed to methods, something not supported by the Java reflection API. Play's attitude is that its first goal is being a useful web framework, and sticking to common Java best-practices and idioms is secondary to that. This approach makes sense to me, but Java purists may not like it, and would be better-off with [Apache Wicket](http://wicket.apache.org/). In summary, if you want to build a web-app with convenience and simplicity comparable to a framework like Ruby on Rails, but in Java and with the benefit of Java's tooling (eg. Eclipse), then Play Framework is a great choice.
(Updated for Spring 3.0) I go with [Spring MVC](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html) as well. You need to download Spring from [here](http://www.springframework.org/download) To configure your web-app to use Spring add the following servlet to your `web.xml` ``` <web-app> <servlet> <servlet-name>spring-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>spring-dispatcher</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app> ``` You then need to create your Spring config file `/WEB-INF/spring-dispatcher-servlet.xml` Your first version of this file can be as simple as: ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.acme.foo" /> <mvc:annotation-driven /> </beans> ``` Spring will then automatically detect classes annotated with `@Controller` A simple controller is then: ``` package com.acme.foo; import java.util.logging.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/person") public class PersonController { Logger logger = Logger.getAnonymousLogger(); @RequestMapping(method = RequestMethod.GET) public String setupForm(ModelMap model) { model.addAttribute("person", new Person()); return "details.jsp"; } @RequestMapping(method = RequestMethod.POST) public String processForm(@ModelAttribute("person") Person person) { logger.info(person.getId()); logger.info(person.getName()); logger.info(person.getSurname()); return "success.jsp"; } } ``` And the `details.jsp` ``` <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <form:form commandName="person"> <table> <tr> <td>Id:</td> <td><form:input path="id" /></td> </tr> <tr> <td>Name:</td> <td><form:input path="name" /></td> </tr> <tr> <td>Surname:</td> <td><form:input path="surname" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Save Changes" /></td> </tr> </table> </form:form> ``` This is just the tip of the iceberg with regards to what Spring can do... Hope this helps.
Can anyone recommend a simple Java web-app framework?
[ "", "java", "web-frameworks", "" ]
I got a program that writes some data to a file using a method like the one below. ``` public void ExportToFile(string filename) { using(FileStream fstream = new FileStream(filename,FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine(text); } } ``` When running the program I get an error: > Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied. > at System.IO.\_\_Error.WinIOError(Int32 errorCode, String maybeFullPath) > at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, > nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions > ptions, SECURITY\_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) > at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access > FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea > bFromProxy) Question: What code do I need to catch this and how do I grant the access?
**UPDATE:** Modified the code based on [this answer](https://stackoverflow.com/a/4397002/11702) to get rid of obsolete methods. You can use the Security namespace to check this: ``` public void ExportToFile(string filename) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { using (FileStream fstream = new FileStream(filename, FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine("sometext"); } } else { //perform some recovery action here } } ``` As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)
When your code does the following: 1. Checks the current user has permission to do something. 2. Carries out the action that needs the entitlements checked in 1. You run the risk that the permissions change between *1* and *2* because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an *UnauthorisedAccessException* is thrown even if you have previously checked permissions. Note that the *SecurityManager* class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, *IsGranted* will always return true for locally running applications. **Example** (derived from [Josh's example](https://stackoverflow.com/questions/130617/how-do-you-check-for-permissions-to-write-to-a-directory-or-file#130641)): ``` //1. Provide early notification that the user does not have permission to write. FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); if(!SecurityManager.IsGranted(writePermission)) { //No permission. //Either throw an exception so this can be handled by a calling function //or inform the user that they do not have permission to write to the folder and return. } //2. Attempt the action but handle permission changes. try { using (FileStream fstream = new FileStream(filename, FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { writer.WriteLine("sometext"); } } catch (UnauthorizedAccessException ex) { //No permission. //Either throw an exception so this can be handled by a calling function //or inform the user that they do not have permission to write to the folder and return. } ``` It's tricky and **not recommended** to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the *System.Security.AccessControl* classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. [This](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/208347aa99a2de3b) post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.
How do you check for permissions to write to a directory or file?
[ "", "c#", ".net", "" ]
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: ``` if (datetime.now() - self.timestamp) > 100 # Where 100 is either seconds or minutes ``` This generates a type error. What is the proper way to do date time comparison in python? I already looked at [WorkingWithTime](http://wiki.python.org/moin/WorkingWithTime) which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. Please post lists of datetime best practices.
Use the `datetime.timedelta` class: ``` >>> from datetime import datetime, timedelta >>> then = datetime.now() - timedelta(hours = 2) >>> now = datetime.now() >>> (now - then) > timedelta(days = 1) False >>> (now - then) > timedelta(hours = 1) True ``` Your example could be written as: ``` if (datetime.now() - self.timestamp) > timedelta(seconds = 100) ``` or ``` if (datetime.now() - self.timestamp) > timedelta(minutes = 100) ```
Compare the difference to a timedelta that you create: ``` if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5): print 'older' ```
Python Date Comparisons
[ "", "python", "datetime", "" ]
I've been trying to consider how Row Level Security could be implemented with the Entity Framework. The idea is to have a database agnostic means that would offer methods to restrict the rows coming from the ObjectContext. Some of my inital ideas have involved modifying the partial classes created by the EDMGEN tool and that has offered some limited support. Users are still able to get around this solution by using their own eSQL statements and a QueryObject. I've been looking for a comprehensive solution that would exist above the database providers so that it would remain agnostic.
Sure you can do it. The important thing to do is to block direct access to the object context (preventing users from building their own ObjectQuery), and instead give the client a narrower gateway within which to access and mutate entities. We do it with the [Entity Repository pattern](http://www.martinfowler.com/eaaCatalog/repository.html). You can find an [example implementation of this pattern for the entity framework in this blog post](http://codeinsanity.com/archive/2008/08/11/the-repository-pattern.aspx "The Repository Pattern…"). Again, the key is blocking access to the object context. Note that the object context class is partial. So you should be able to prevent "unauthorized" means of instantiating it, namely, outside of your repository assembly. However, there are subtleties to consider. If you implement row-level view security on a certain entity type via the repository pattern, then you must consider other means by which a client could access the same entities. For example, via navigational relationships. You may need to make some of those relationships private, which you can do in your model. You also have the option of [specifying a custom query](http://msmvps.com/blogs/matthieu/archive/2008/10/01/ef-how-to-do-a-recursive-include.aspx "EF: how to do a recursive include?") or stored procedure for loading/saving entities. Stored procedures tend to be DB server specific, but SQL can be written in a generic manner. While I don't agree that this cannot be done with the Entity Framework, I do agree with the "do it on the DB server" comments insofar as you should implement [defense in depth](http://en.wikipedia.org/wiki/Defense_in_Depth_(computing)).
The place where you add security really depends on who you're trying to secure against. If, for example, you were securing a web site, then adding the filtering at the context level would be sufficient, because the "users" in this case are on the web site. They have no choice but to go through your context, since you would write the application entirely against the context. In your case, it sounds like the "users" you're trying to secure against are developers. That's quite a bit more difficult. If the developers don't have access to make modifications to the database itself, then you'll have to put the security at the database level. No amount of eSQL access is going to be able to get around the database saying "no".
Row Level Security with Entity Framework
[ "", "c#", "database", "security", "entity-framework", "row-level-security", "" ]
I've been working with sessions, MVC design and object oriented PHP. Where should I save or retrieve data from a session? I would like to retrieve it from within methods so I don't have to pass the data to the methods. Whats the best practice?
I typically put this inside the controller. It just makes sense.. The controller decides what happens and why not let it decide if people are allowed to do the requested actions. Typically you have multiple controllers in a MVC system. Eg. BaseController (abstract - common), NonSessionController extends BaseController (eg: used for static pages), SessionController extends BaseController (primary session handing here - this could be abstract). If you have for example different user types, you may want to polymorph this controller ones such as: AdminController, UserController, Etc.
Personally, I'm a huge fan of the [Zend\_Session](http://framework.zend.com/manual/en/zend.session.html#zend.session.introduction) wrapper class. I prefer to work with data in an object-oriented style and the namespacing advantage to using a wrapper is a huge plus. Which of these looks better to you? ``` $_SESSION['Zend_Auth']['user'] = "myusername"; ``` or ``` $authNamespace = new Zend_Session_Namespace('Zend_Auth'); $authNamespace->user = "myusername"; ``` I prefer the look that using the accessors gives you. **Note:** In an MVC system, no matter what method you choose, you should always be getting/setting session data in your controller.
Best way to use sessions with MVC and OO PHP
[ "", "php", "oop", "session", "" ]
Is there a good Eclipse plugin for recording and playing back macros? I've tried [this one](http://web.archive.org/web/20161025001953/http://www.bdaum.de:80/eclipse/), but it didn't do me any good- it seemed like it wasn't ready for prime time. I know about editor templates, but I'm looking for something that I can use to record my keystrokes and then apply multiple times against a wad of text. This seems like a strange hole in an IDE. Am I missing some built-in facility for this?
I put something together over the last month or so that you may find useful. It has limitations since the Eclipse editor/commands weren't designed with macro support in mind, but I think it works reasonably well. I just posted [Practical Macro](http://sourceforge.net/projects/practicalmacro/files/) at SourceForge a couple of days ago. It requires Eclipse 3.4.
Emacs+ Version 3.x adds keyboard macros (<http://www.mulgasoft.com/emacsplus>) to its feature set.
Is there a macro recorder for Eclipse?
[ "", "java", "eclipse", "ide", "editor", "macros", "" ]
We recently had a security audit and it exposed several weaknesses in the systems that are in place here. One of the tasks that resulted from it is that we need to update our partner credentials system make it more secure. The "old" way of doing things was to generate a (bad) password, give it to the partner with an ID and then they would send that ID and a Base 64 encoded copy of that password in with all of their XML requests over https. We then decode them and validate them. These passwords won't change (because then our partners would have to make coding/config changes to change them and coordinating password expirations with hundreds of partners for multiple environments would be a nightmare) and they don't have to be entered by a human or human readable. I am open to changing this if there is a better but still relatively simple implementation for our partners. Basically it comes down to two things: I need a more secure Java password generation system and to ensure that they are transmitted in a secure way. I've found a few hand-rolled password generators but nothing that really stood out as a standard way to do this (maybe for good reason). There may also be a more secure way to transmit them than simple Base 64 encoding over https. What would you do for the password generator and do you think that the transmission method in place is secure enough for it? Edit: The XML comes in a SOAP message and the credentials are in the header not in the XML itself. Also, since the passwords are a one-off operation for each partner when we set them up we're not too worried about efficiency of the generator.
### Password Generation As far as encoding a password for transmission, the only encoding that will truly add security is encryption. Using Base-64 or hexadecimal isn't for security, but just to be able to include it in a text format like XML. Entropy is used to measure password quality. So, choosing each bit with a random "coin-flip" will give you the best quality password. You'd want passwords to be as strong as other cryptographic keys, so I'd recommend a minimum of 128 bits of entropy. There are two easy methods, depending on how you want to encode the password as text (which really doesn't matter from a security standpoint). For [Base-64](http://en.wikipedia.org/wiki/Base64), use something like this: ``` SecureRandom rnd = new SecureRandom(); /* Byte array length is multiple of LCM(log2(64), 8) / 8 = 3. */ byte[] password = new byte[18]; rnd.nextBytes(password); String encoded = Base64.encode(password); ``` The following doesn't require you to come up with a Base-64 encoder. The resulting encoding is not as compact (26 characters instead of 24) and the password doesn't have as much entropy. (But 130 bits is already a lot, comparable to a password of at least 30 characters chosen by a human.) ``` SecureRandom rnd = new SecureRandom(); /* Bit length is multiple of log2(32) = 5. */ String encoded = new BigInteger(130, rnd).toString(32); ``` Creating new SecureRandom objects is computationally expensive, so if you are going to generate passwords frequently, you may want to create one instance and keep it around. ### A Better Approach Embedding the password in the XML itself seems like a mistake. First of all, it seems like you would want to authenticate a sender before processing any documents they send you. Suppose I hate your guts, and start sending you giant XML files to execute a denial of service attack. Do you want to have to parse the XML only to find out that I'm not a legitimate partner? Wouldn't it be better if the servlet just rejected requests from unauthenticated users up front? Second, the passwords of your legitimate partners were protected during transmission by HTTPS, but now they are likely stored "in the clear" on your system somewhere. That's bad security. A better approach would be to authenticate partners when they send you a document with credentials in the HTTP request headers. If you only allow HTTPS, you can take the password out of the document completely and put it into an [HTTP "Basic" authentication](http://www.ietf.org/rfc/rfc2617.txt) header instead. It's secured by SSL during transmission, and not stored on your system in the clear (you only store a one-way hash for authentication purposes). HTTP Basic authentication is simple, widely supported, and will be much easier for you and your partners to implement than SSL client certificates. ### Protecting Document Content If the content of the documents themselves is sensitive, they really should be encrypted by the sender, and stored by you in their encrypted form. The best way to do this is with public key cryptography, but that would be a subject for another question.
I'm unclear why transmitting the passwords over SSL -- via HTTPS -- is being considered "insecure" by your audit team. So when you ask for two things, it seems the second -- ensuring that the passwords are being transmitted in a secure way -- is already being handled just fine. As for the first, we'd have to know what about the audit exposed your passwords as insecure...
How would you implement a secure static login credentials system in Java?
[ "", "java", "security", "encryption", "https", "" ]
I've been using various javascript frameworks including mootools, jquery, prototype and scriptaculous and have found them all good, but difficult to extend to more complex ideas. If I am going to knuckle down and learn one, which is the simplest to extend and use whilst staying powerful enough to use in a variety of directions?
I propose jQuery. I'll give you some of the major arguments from the presentation that my team put on yesterday for senior management to convince them of that. Reasons: 1. Community acceptance. Look at [this graph](http://google.com/trends?q=jquery%2C+prototype%2C+yui%2C+scriptaculous+&ctab=0&geo=all&date=all&sort=0). It shows searches for "prototype", "yui" and "scriptaculous" growing from 2004 to 2008. Then out of nowhere in 2006 searches fro "jquery" shoot up to double the number of the other libraries. The community is actually converging on a single leading product, and it's jQuery. 2. jQuery is very very succinct and readable. I conducted an experiment in which I took existing code (selected at random) written in YUI, and tried re-writing it in jQuery. It was 1/4 as long in jQuery. That makes it 4 times as easy to write, and 4 times as easy to maintain. 3. jQuery integrates well with the rest of the web world. The use of CSS syntax as the key for selecting items is a brilliant trick which helps to meld together the highly diseparate worlds of HTML, CSS and JavaScript. 4. Documentation: jQuery has excellent documentation, with clear specifications and working examples of every method. It has excellent books (I recommend "jQuery in Action".) The only competitor which matches it is YUI. 5. Active user community: the Google group which is the main community discussion forum for Prototype has nearly 1000 members. The Google group for jQuery has 10 times as many members. And my personal experience is that the community tends to be helpful. 6. Easy learning curve. jQuery is easy to learn, even for people with experience as a designer, but no experience in coding. 7. Performance. Check out [this](http://mootools.net/slickspeed/), which is published by mootools. It compares the speed of different frameworks. jQuery is not always the VERY fastest, but it is quite good on every test. 8. Plays well with others: jQuery's noConflict mode and the core library's small size help it to work well in environments that are already using other libraries. 9. Designed to make JavaScript usable. Looping is a pain in JavaScript; jQuery works with set objects you almost never need to write the loop. JavaScript's greatest strength is that functions are first-class objects; jQuery makes extensive use of this feature. 10. Plug-ins. jQuery is designed to make it *easy* to write plugins. And there is an enormous community of people out there writing plugins. Anything you want is probably out there. Check out things like [this](http://ui.jquery.com/repository/real-world/effects/) or [this](http://interface.eyecon.ro/demos/) for visual examples. I hope you find this convincing!
In my opinion, jQuery is exceptionally powerful and simple. It uses CSS selector syntax to pull back elements and only adds two functions to the global namespace: jQuery() and $(), which is an alias for jQuery(). There are a massive number of plugins available for jQuery to let you do things like create slide shows, accordion controls, rich calendars, etc. The book "jQuery In Action" is a phenomenal companion to the online reference material. We used it on my last project to create a fairly rich scheduling tool and we liked it so much, we're encouraging it's adoption throughout our consulting company as the defacto standard for all JavaScript use. You can check out the results at <http://www.stanleysteemer.com>
Which Javascript Framework is the simplest and most powerful?
[ "", "javascript", "frameworks", "" ]
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading. What is the best way to achieve this?
There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than). However; if you just want it to work, then in .NET 3.5 there are some options... I have put together a library [here](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html) that allows efficient and simple access to operators with generics - such as: ``` T result = Operator.Add(first, second); // implicit <T>; here ``` It can be downloaded as part of [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/) Additionally, in C# 4.0, this becomes possible via `dynamic`: ``` static T Add<T>(T x, T y) { dynamic dx = x, dy = y; return dx + dy; } ``` I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as ``` interface ICalc<T> { T Add(T,T)() T Subtract(T,T)() } ``` etc, but then you need to pass an `ICalc<T>;` through all the methods, which gets messy.
I found that IL can actually handle this quite well. Ex. ``` ldarg.0 ldarg.1 add ret ``` Compiled in a generic method, the code will run fine as long as a primitive type is specified. It may be possible to extend this to call operator functions on non-primitive types. See [here](http://graphicsnut.blogspot.com/2011/06/solution-to-generic-arithmetic.html).
Solution for overloaded operator constraint in .NET generics
[ "", "c#", "generics", "operator-overloading", "constraints", "" ]
I have a command line executable that alters some bits in a file that i want to use from my program. Is it possible to create my own executable that uses this tool and distribute only one executable? [edit] Clarification: The command line tool takes an offset and some bits and changes the bits at this offset in a given file. So I want to create a patcher for an application that changes specific bits to a specific value, so what I can do i write something like a batch file to do it but i want to create an executable that does it, i.e. embed the tool into a wrapper program that calls it with specific values. I can code wrapper in (windows) c\c++, asm but no .net please.
It would be easier to roll your own implementation of this program than to write the wrapper; it sounds like it is trivial -- just open the file, seek to the right location, write your bits, close the file, you're done.
The easiest way is to embed this exe into your own and write it to disk to run it.
Combining two executables
[ "", "c++", "command-line", "assembly", "executable", "" ]
The system I work on here was written before .net 2.0 and didn't have the benefit of generics. It was eventually updated to 2.0, but none of the code was refactored due to time constraints. There are a number of places where the code uses ArraysLists etc. that store things as objects. From performance perspective, how important change the code to using generics? I know from a perfomance perspective, boxing and unboxing etc., it is inefficient, but how much of a performance gain will there really be from changing it? Are generics something to use on a go forward basis, or it there enough of a performance change that a conscience effort should be made to update old code?
Technically the performance of generics is, as you say, better. However, unless performance is hugely important AND you've already optimised in other areas you're likely to get MUCH better improvements by spending your time elsewhere. I would suggest: * use generics going forward. * if you have solid unit tests then refactor to generics as you touch code * spend other time doing refactorings/measurement that will significantly improve performance (database calls, changing data structures, etc) rather than a few milliseconds here and there. Of course there's reasons other than performance to change to generics: * less error prone, since you have compile-time checking of types * more readable, you don't need to cast all over the place and it's obvious what type is stored in a collection * if you're using generics going forward, then it's cleaner to use them everywhere
Here's the results I got from a simple parsing of a string from a 100KB file 100,000 times. The Generic List(Of char) took 612.293 seconds to go 100,000 times through the file. The ArrayList took 2,880.415 seconds to go 100,000 times through the file. This means in this scenario (as your mileage *will* vary) the Generic List(Of char) is 4.7 times faster. Here is the code I ran through 100,000 times: ``` Public Sub Run(ByVal strToProcess As String) Implements IPerfStub.Run Dim genList As New ArrayList For Each ch As Char In strToProcess.ToCharArray genList.Add(ch) Next Dim dummy As New System.Text.StringBuilder() For i As Integer = 0 To genList.Count - 1 dummy.Append(genList(i)) Next End Sub Public Sub Run(ByVal strToProcess As String) Implements IPerfStub.Run Dim genList As New List(Of Char) For Each ch As Char In strToProcess.ToCharArray genList.Add(ch) Next Dim dummy As New System.Text.StringBuilder() For i As Integer = 0 To genList.Count - 1 dummy.Append(genList(i)) Next End Sub ```
Generics vs. Array Lists
[ "", "c#", "performance", "generics", "" ]
I have a desktop application written in C#. It is trying to manage a socket connection and fails. The same application is successful if it is attached to the Visual Studio debugger. How can it be debugged?
This is a classic example of timing. If it works in the debugger then it means you have to re-factor your code a bit to handle this. Now if you are app is a server socket that receives connections from client and trying to spawn a thread for each of those connections, you might have to consider using select() to manage connections with in one thread.
I'd say timing issues too having the debugger attached will slow down the code slightly which might mean that a race condition isn't occuring. To debug it try to add some logging code to your application, I personally use [log4net](http://logging.apache.org/log4net/index.html) You shouldn't have and problems with malloc and the like as you are coding in c#. if you are running a web app it might also be there is a difference in the cassini webserver in VS and the one you are deploying to.
Why would an application act differently after the VS debugger is attached?
[ "", "c#", "visual-studio", "sockets", "debugging", "" ]
I would like to keep the overhead at a minimum. Right now I have: ``` // Launch a Message Box with advice to the user DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation); // The test will only be launched if the user has selected Yes on the Message Box if(result == DialogResult::Yes) { // Execute code } ``` Unfortunately my client would prefer "Continue" and "Cancel" in place of the default "Yes" and "No" button text. It seems like there should be an easy way to do this.
You can use "OK" and "Cancel" By substituting `MessageBoxButtons::YesNo` with `MessageBoxButtons::OKCancel` [MessageBoxButtons Enum](http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxbuttons.aspx) Short of that you would have to create a new form, as I don't believe the Enum can be extended.
From everything I can find it looks like [Corin](https://stackoverflow.com/users/1736/corin) is right. Here is the code that I used to accomplish the original goal. I am not usually a Managed C++ programmer, so any editing would be appreciated. CustomMessageBox.h: ``` using namespace System::Windows::Forms; /// <summary> /// A message box for the test. Used to ensure user wishes to continue before starting the test. /// </summary> public ref class CustomMessageBox : Form { private: /// Used to determine which button is pressed, default action is Cancel static String^ Button_ID_ = "Cancel"; // GUI Elements Label^ warningLabel_; Button^ continueButton_; Button^ cancelButton_; // Button Events void CustomMessageBox::btnContinue_Click(System::Object^ sender, EventArgs^ e); void CustomMessageBox::btnCancel_Click(System::Object^ sender, EventArgs^ e); // Constructor is private. CustomMessageBox should be accessed through the public ShowBox() method CustomMessageBox(); public: /// <summary> /// Displays the CustomMessageBox and returns a string value of "Continue" or "Cancel" /// </summary> static String^ ShowBox(); }; ``` CustomMessageBox.cpp: ``` #include "StdAfx.h" #include "CustomMessageBox.h" using namespace System::Windows::Forms; using namespace System::Drawing; CustomMessageBox::CustomMessageBox() { this->Size = System::Drawing::Size(420, 150); this->Text="Warning"; this->AcceptButton=continueButton_; this->CancelButton=cancelButton_; this->FormBorderStyle= ::FormBorderStyle::FixedDialog; this->StartPosition= FormStartPosition::CenterScreen; this->MaximizeBox=false; this->MinimizeBox=false; this->ShowInTaskbar=false; // Warning Label warningLabel_ = gcnew Label(); warningLabel_->Text="This may take awhile, do you wish to continue?"; warningLabel_->Location=Point(5,5); warningLabel_->Size=System::Drawing::Size(400, 78); Controls->Add(warningLabel_); // Continue Button continueButton_ = gcnew Button(); continueButton_->Text="Continue"; continueButton_->Location=Point(105,87); continueButton_->Size=System::Drawing::Size(70,22); continueButton_->Click += gcnew System::EventHandler(this, &CustomMessageBox::btnContinue_Click); Controls->Add(continueButton_); // Cancel Button cancelButton_ = gcnew Button(); cancelButton_->Text="Cancel"; cancelButton_->Location=Point(237,87); cancelButton_->Size=System::Drawing::Size(70,22); cancelButton_->Click += gcnew System::EventHandler(this, &CustomMessageBox::btnCancel_Click); Controls->Add(cancelButton_); } /// <summary> /// Displays the CustomMessageBox and returns a string value of "Continue" or "Cancel", depending on the button /// clicked. /// </summary> String^ CustomMessageBox::ShowBox() { CustomMessageBox^ box = gcnew CustomMessageBox(); box->ShowDialog(); return Button_ID_; } /// <summary> /// Event handler: When the Continue button is clicked, set the Button_ID_ value and close the CustomMessageBox. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void CustomMessageBox::btnContinue_Click(System::Object^ sender, EventArgs^ e) { Button_ID_ = "Continue"; this->Close(); } /// <summary> /// Event handler: When the Cancel button is clicked, set the Button_ID_ value and close the CustomMessageBox. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void CustomMessageBox::btnCancel_Click(System::Object^ sender, EventArgs^ e) { Button_ID_ = "Cancel"; this->Close(); } ``` And then finally the modification to the original code: ``` // Launch a Message Box with advice to the user String^ result = CustomMessageBox::ShowBox(); // The test will only be launched if the user has selected Continue on the Message Box if(result == "Continue") { // Execute Code } ```
What is an easy way to create a MessageBox with custom button text in Managed C++?
[ "", "c++", "" ]
If I have an object implementing the `Map` interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of elements depend on the specific map implementation that I have for the interface?
``` Map<String, String> map = ... for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } ``` On Java 10+: ``` for (var entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } ```
To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write: 1. Using **iterator** and **Map.Entry** ``` long i = 0; Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, Integer> pair = it.next(); i += pair.getKey() + pair.getValue(); } ``` 2. Using **foreach** and **Map.Entry** ``` long i = 0; for (Map.Entry<Integer, Integer> pair : map.entrySet()) { i += pair.getKey() + pair.getValue(); } ``` 3. Using **forEach** from Java 8 ``` final long[] i = {0}; map.forEach((k, v) -> i[0] += k + v); ``` 4. Using **keySet** and **foreach** ``` long i = 0; for (Integer key : map.keySet()) { i += key + map.get(key); } ``` 5. Using **keySet** and **iterator** ``` long i = 0; Iterator<Integer> itr2 = map.keySet().iterator(); while (itr2.hasNext()) { Integer key = itr2.next(); i += key + map.get(key); } ``` 6. Using **for** and **Map.Entry** ``` long i = 0; for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) { Map.Entry<Integer, Integer> entry = entries.next(); i += entry.getKey() + entry.getValue(); } ``` 7. Using the Java 8 **Stream API** ``` final long[] i = {0}; map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue()); ``` 8. Using the Java 8 **Stream API parallel** ``` final long[] i = {0}; map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue()); ``` 9. Using **IterableMap** of `Apache Collections` ``` long i = 0; MapIterator<Integer, Integer> it = iterableMap.mapIterator(); while (it.hasNext()) { i += it.next() + it.getValue(); } ``` 10. Using **MutableMap** of Eclipse (CS) collections ``` final long[] i = {0}; mutableMap.forEachKeyValue((key, value) -> { i[0] += key + value; }); ``` **Perfomance tests** (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB) 1. For a small map (100 elements), score 0.308 is the best ``` Benchmark Mode Cnt Score Error Units test3_UsingForEachAndJava8 avgt 10 0.308 ± 0.021 µs/op test10_UsingEclipseMap avgt 10 0.309 ± 0.009 µs/op test1_UsingWhileAndMapEntry avgt 10 0.380 ± 0.014 µs/op test6_UsingForAndIterator avgt 10 0.387 ± 0.016 µs/op test2_UsingForEachAndMapEntry avgt 10 0.391 ± 0.023 µs/op test7_UsingJava8StreamApi avgt 10 0.510 ± 0.014 µs/op test9_UsingApacheIterableMap avgt 10 0.524 ± 0.008 µs/op test4_UsingKeySetAndForEach avgt 10 0.816 ± 0.026 µs/op test5_UsingKeySetAndIterator avgt 10 0.863 ± 0.025 µs/op test8_UsingJava8StreamApiParallel avgt 10 5.552 ± 0.185 µs/op ``` 2. For a map with 10000 elements, score 37.606 is the best ``` Benchmark Mode Cnt Score Error Units test10_UsingEclipseMap avgt 10 37.606 ± 0.790 µs/op test3_UsingForEachAndJava8 avgt 10 50.368 ± 0.887 µs/op test6_UsingForAndIterator avgt 10 50.332 ± 0.507 µs/op test2_UsingForEachAndMapEntry avgt 10 51.406 ± 1.032 µs/op test1_UsingWhileAndMapEntry avgt 10 52.538 ± 2.431 µs/op test7_UsingJava8StreamApi avgt 10 54.464 ± 0.712 µs/op test4_UsingKeySetAndForEach avgt 10 79.016 ± 25.345 µs/op test5_UsingKeySetAndIterator avgt 10 91.105 ± 10.220 µs/op test8_UsingJava8StreamApiParallel avgt 10 112.511 ± 0.365 µs/op test9_UsingApacheIterableMap avgt 10 125.714 ± 1.935 µs/op ``` 3. For a map with 100000 elements, score 1184.767 is the best ``` Benchmark Mode Cnt Score Error Units test1_UsingWhileAndMapEntry avgt 10 1184.767 ± 332.968 µs/op test10_UsingEclipseMap avgt 10 1191.735 ± 304.273 µs/op test2_UsingForEachAndMapEntry avgt 10 1205.815 ± 366.043 µs/op test6_UsingForAndIterator avgt 10 1206.873 ± 367.272 µs/op test8_UsingJava8StreamApiParallel avgt 10 1485.895 ± 233.143 µs/op test5_UsingKeySetAndIterator avgt 10 1540.281 ± 357.497 µs/op test4_UsingKeySetAndForEach avgt 10 1593.342 ± 294.417 µs/op test3_UsingForEachAndJava8 avgt 10 1666.296 ± 126.443 µs/op test7_UsingJava8StreamApi avgt 10 1706.676 ± 436.867 µs/op test9_UsingApacheIterableMap avgt 10 3289.866 ± 1445.564 µs/op ``` Graphs (performance tests depending on map size) [![Enter image description here](https://i.stack.imgur.com/17VGh.png)](https://i.stack.imgur.com/17VGh.png) Table (perfomance tests depending on map size) ``` 100 600 1100 1600 2100 test10 0.333 1.631 2.752 5.937 8.024 test3 0.309 1.971 4.147 8.147 10.473 test6 0.372 2.190 4.470 8.322 10.531 test1 0.405 2.237 4.616 8.645 10.707 test2 0.376 2.267 4.809 8.403 10.910 test7 0.473 2.448 5.668 9.790 12.125 test9 0.565 2.830 5.952 13.220 16.965 test4 0.808 5.012 8.813 13.939 17.407 test5 0.810 5.104 8.533 14.064 17.422 test8 5.173 12.499 17.351 24.671 30.403 ``` All tests are on [GitHub](https://github.com/Vedenin/useful-java-links/blob/master/helloworlds/5.0-other-examples/src/main/java/other_examples/IterateThroughHashMapTest.java).
How do I efficiently iterate over each entry in a Java Map?
[ "", "java", "dictionary", "collections", "iteration", "" ]
It seems that C# 3 hit me without me even noticing, could you guys tell me about good in depth guides to C# 3? from lambda to linq to everything else that was introduced with the third version of the language. Printed books would be nice, but online guides would be even better!
[ScottGu](http://weblogs.asp.net/scottgu/default.aspx) has some great posts on C# 3: * [The C# ?? null coalescing operator (and using it with LINQ)](http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx) * [LINQ to SQL: Part 8](http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx) (this is an 8 part series, check the top of the post for links to the first 7) * [Automatic Properties, Object Initializers, and Collection Initializers](http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx) * [Extension Methods](http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx) * [Lambda Expressions](http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx) * [Query Syntax](http://weblogs.asp.net/scottgu/archive/2007/04/21/new-orcas-language-feature-query-syntax.aspx) * [Anonymous Types](http://weblogs.asp.net/scottgu/archive/2007/05/15/new-orcas-language-feature-anonymous-types.aspx?CommentPosted=true) Some more useful links: * [MSDN: Overview of C# 3.0](http://msdn.microsoft.com/en-us/library/bb308966.aspx) * [David Hayden: C# 3.0 Tutorials and Examples](http://davidhayden.com/blog/dave/archive/2006/11/30/CSharpTutorialsAndExamples.aspx)
There are some high quality blogs out there. some of my favorites: [Eric Lippert](http://blogs.msdn.com/ericlippert/archive/tags/Lambda+Expressions/default.aspx), [Eric White](http://blogs.msdn.com/ericwhite/pages/FP-Tutorial.aspx), [Scott Gu](http://weblogs.asp.net/scottgu/archive/tags/LINQ/default.aspx)
Where can i find a good in depth guide to C# 3?
[ "", "c#", "documentation", "c#-3.0", "" ]
What’s the best way to capitalize the first letter of each word in a string in SQL Server.
From <http://www.sql-server-helper.com/functions/initcap.aspx> ``` CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) ) RETURNS VARCHAR(4000) AS BEGIN DECLARE @Index INT DECLARE @Char CHAR(1) DECLARE @PrevChar CHAR(1) DECLARE @OutputString VARCHAR(255) SET @OutputString = LOWER(@InputString) SET @Index = 1 WHILE @Index <= LEN(@InputString) BEGIN SET @Char = SUBSTRING(@InputString, @Index, 1) SET @PrevChar = CASE WHEN @Index = 1 THEN ' ' ELSE SUBSTRING(@InputString, @Index - 1, 1) END IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(') BEGIN IF @PrevChar != '''' OR UPPER(@Char) != 'S' SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char)) END SET @Index = @Index + 1 END RETURN @OutputString END GO ``` There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."): <http://www.devx.com/tips/Tip/17608>
As a table-valued function: ``` CREATE FUNCTION dbo.InitCap(@v AS VARCHAR(MAX)) RETURNS TABLE AS RETURN WITH a AS ( SELECT ( SELECT UPPER(LEFT(value, 1)) + LOWER(SUBSTRING(value, 2, LEN(value))) AS 'data()' FROM string_split(@v, ' ') ORDER BY CHARINDEX(value,@v) FOR XML PATH (''), TYPE) ret) SELECT CAST(a.ret AS varchar(MAX)) ret from a GO ``` Note that `string_split` requires `COMPATIBILITY_LEVEL` 130.
How to capitalize the first letter of each word in a string in SQL Server
[ "", "sql", "sql-server", "string", "" ]
I'm building a Django project that needs search functionality, and until there's a `django.contrib.search`, I have to choose a search app. So, which is the best? By "best" I mean... * easy to install / set up * has a Django- or at least Python-friendly API * can perform reasonably complex searches Here are some apps I've heard of, please suggest others if you know of any: * [djangosearch](http://code.google.com/p/djangosearch/) * [django-sphinx](http://code.google.com/p/django-sphinx/) I'd also like to avoid using a third-party search engine (like Google SiteSearch), because some of the data I'd like to index is for site members only and should not be public.
Check out [Haystack Search](http://haystacksearch.org/) - a new model based search abstraction layer that currently supports [Xapian](http://xapian.org/), [Solr](http://lucene.apache.org/solr/) and [Whoosh](https://bitbucket.org/mchaput/whoosh/wiki/Home). Looks like it's well supported and documented.
Justin, I'd try [djangosearch](http://code.google.com/p/djangosearch/) first: Jacob Kaplan-Moss (Django's lead developer) is working on it. Potential hazards: * The home page warns the API might not be entirely stable Potential benefits: * “The long term goal is for this to become `django.contrib.search`.”
What's the best Django search app?
[ "", "python", "django", "search", "search-engine", "" ]
What is the proper way to minimize a WinForms app to the system tray? Note: minimize to ***system tray***; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window. I've seen hackish solutions like, "minimize, set ShowInTaskbar = false, then show your NotifyIcon." Solutions like that are hackish because the app doesn't appear to minimize to the tray like other apps, the code has to detect when to set ShowInTaskbar = true, among other issues. What's the proper way to do this?
There is actually no managed way to do that form of animation to the tray in native winforms, however you can P/Invoke shell32.dll to do it: Some good info here (In the comments not the post): <http://blogs.msdn.com/jfoscoding/archive/2005/10/20/483300.aspx> And here it is in C++: <http://www.codeproject.com/KB/shell/minimizetotray.aspx> You can use that to figure out what stuff to Pinvoke for your C# version.
``` this.WindowState = FormWindowState.Minimized ``` That is the built in way to do it and it looks fine to me most of the time. The only time is has some weirdness to it is if you call it on startup which has some weirdness sometimes which is why most people will also set the ShowInTaskbar = false and hide the form too. <http://msdn.microsoft.com/en-us/library/system.windows.forms.form.windowstate.aspx>
What's the proper way to minimize to tray a C# WinForms app?
[ "", "c#", "winforms", "trayicon", "" ]
I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following: ``` abstract class Animal { public Leg GetLeg() {...} } abstract class Leg { } class Dog : Animal { public override DogLeg Leg() {...} } class DogLeg : Leg { } ``` This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#. **EDIT**: I modified this somewhat, since I'm actually using properties instead of functions in my code. **EDIT**: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function **shouldn't** work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.
The short answer is that GetLeg is invariant in its return type. The long answer can be found here: [Covariance and contravariance](http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx) I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers.
Clearly, you'll need a cast if you're operating on a broken DogLeg.
Why doesn't inheritance work the way I think it should work?
[ "", "c#", "oop", "inheritance", "covariance", "contravariance", "" ]
I have a number of data classes representing various entities. Which is better: writing a generic class (say, to print or output XML) using generics and interfaces, or writing a separate class to deal with each data class? Is there a performance benefit or any other benefit (other than it saving me the time of writing separate classes)?
There's a significant performance benefit to using generics -- you do away with [boxing and unboxing](http://en.wikipedia.org/wiki/Boxing_(Computer_science)#Boxing). Compared with developing your own classes, it's a coin toss (with one side of the coin weighted more than the other). Roll your own only if you think you can out-perform the authors of the framework.
Not only yes, but HECK YES. I didn't believe how big of a difference they could make. We did testing in VistaDB after a rewrite of a small percentage of core code that used ArrayLists and HashTables over to generics. 250% or more was the speed improvement. [Read my blog about the testing](https://web.archive.org/web/20100709213139/http://www.vistadb.net/blog/post/2008/07/18/Strongly-type-everything!.aspx) we did on generics vs weak type collections. The results blew our mind. I have started rewriting lots of old code that used the weakly typed collections into strongly typed ones. One of my biggest grips with the ADO.NET interface is that they don't expose more strongly typed ways of getting data in and out. The casting time from an object and back is an absolute killer in high volume applications. Another side effect of strongly typing is that you often will find weakly typed reference problems in your code. We found that through [implementing structs](https://web.archive.org/web/20101124023832/http://www.vistadb.net/blog/post/2008/08/15/Class-v-Struct.aspx) in some cases to avoid putting pressure on the GC we could further speed up our code. Combine this with strongly typing for your best speed increase. Sometimes you have to use weakly typed interfaces within the dot net runtime. Whenever possible though look for ways to stay strongly typed. It really does make a huge difference in performance for non trivial applications.
Do C# Generics Have a Performance Benefit?
[ "", "c#", ".net", "performance", "generics", "" ]
I'm pretty sure the answer to this question is no, but in case there's some PHP guru is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of `'@'` Much like empty and isset do. You can pass in a variable you just made up and it won't error. ``` ex: empty($someBogusVar); // no error myHappyFunction($someBogusVar); // Php warning / notice ```
Summing up, the proper answer is **no, you shouldn't** (see caveat below). There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which you don't want. Summarizing an interesting comment discussion with [Gerry](https://stackoverflow.com/users/109561/gerry): Passing the variable by reference is indeed valid if you **check for the value of the variable inside the function** and handle undefined or null cases properly. Just don't use reference passing as a way of shutting PHP up (this is where my original shouldn't points to).
You don't get any error when a variable is passed by reference (PHP will create a new variable silently): ``` function myHappyFunction(&$var) { } ``` But I recommend against abusing this for hiding programming errors.
Php function argument error suppression, empty() isset() emulation
[ "", "php", "error-handling", "error-suppression", "" ]
I am trying to improve the performance of a web application. I have metrics that I can use to optimize the time taken to return the main HTML page, but I'm concerned about the external CSS and JavaScript files that are included from these HTML pages. These are served statically, with HTTP Expires headers, but are shared between all the pages of the application. I'm concerned that the browser has to parse these CSS and JavaScript files for each page that is displayed and so having all the CSS and JavaScript for the site shared into common files will negatively affect performance. Should I be trying to split out these files so I link from each page to only the CSS and JavaScript needed for that page, or would I get little return for my efforts? Are there any tools that could help me generate metrics for this? ­­­­­­­­­­­­­­­­­­­­­­­­­­­
**Context:** While it's true that HTTP overhead is more significant than parsing JS and CSS, ignoring the impact of parsing on browser performance (even if you have less than a meg of JS) is a good way to get yourself in trouble. YSlow, Fiddler, and Firebug are not the best tools to monitor parsing speed. Unless they've been updated very recently, they don't separate the amount of time required to fetch JS over HTTP or load from cache versus the amount of time spent parsing the actual JS payload. Parse speed is slightly difficult to measure, but we've chased this metric a number of times on projects I've worked on and the impact on pageloads were significant even with ~500k of JS. Obviously the older browsers suffer the most...hopefully Chrome, TraceMonkey and the like help resolve this situation. **Suggestion:** Depending on the type of traffic you have at your site, it may be well worth your while to split up your JS payload so some large chunks of JS that will never be used on a the most popular pages are never sent down to the client. Of course, this means that when a new client hits a page where this JS is needed, you'll have to send it over the wire. However, it may well be the case that, say, 50% of your JS is never needed by 80% of your users due to your traffic patterns. If this is so, you should definitely user smaller, packaged JS payloads only on pages where the JS is necessary. Otherwise 80% of your users will suffer unnecessary JS parsing penalties on *every single pageload*. **Bottom Line:** It's difficult to find the proper balance of JS caching and smaller, packaged payloads, but depending on your traffic pattern it's definitely well worth considering a technique other than smashing all of your JS into every single pageload.
I believe [YSlow](http://developer.yahoo.com/yslow/) does, but be aware that unless all requests are over a loopback connection you shouldn't worry. The HTTP overhead of split-up files will impact performance *far* more than parsing, unless your CSS/JS files exceed several megabytes.
Javascript and CSS parsing performance
[ "", "javascript", "css", "performance", "" ]
I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components. Has anyone had experience actually setting C# and PostgreSQL up to work together? If so, do you have any suggestions about how to go about it, issues you've found, etc.?
I'm working with C# and Postgres using **Npgsql2** component, and they work fast, I recommend you. You can download from <https://github.com/npgsql/Npgsql/releases> **Note:** If you want an application that works with any database you can use the **DbProviderFactory** class and make your queries using **IDbConnection**, **IDbCommand**, **IDataReader** and/or **IDbTransaction** interfaces.
**Npgsql** - .Net Provider for PostGreSQL - is an excellent driver. If you have used the more traditional ADO.NET framework you are really in luck here. I have code that connects to Oracle that looks almost identical to the PostGreSQL connections. Easier to transition off of Oracle and reuse brain cells. It supports all of the standard things you would want to do with calling SQL, but it also supports calling **Functions** (stored procedures). This includes the returning of **reference cursors**. The documentation is well written and provides useful examples without getting philosophical or arcane. Steal the code right out of the documentation and it will work instantly. Francisco Figueiredo, Jr's and team have done a great job with this. It is now available on **Github**. <https://github.com/franciscojunior/Npgsql2> The better site for info is: <http://npgsql.projects.postgresql.org/> Read the documentation! <http://npgsql.projects.postgresql.org/docs/manual/UserManual.html>
C# .NET + PostgreSQL
[ "", "c#", ".net", "postgresql", "" ]
Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this?
``` // Store the formatted string in 'result' String result = String.format("%4d", i * j); // Write the result to standard output System.out.println( result ); ``` See [format](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)) and its [syntax](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax)
Strings are immutable types. You cannot modify them, only return new string instances. Because of that, formatting with an instance method makes little sense, as it would have to be called like: ``` String formatted = "%s: %s".format(key, value); ``` The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string. Here is an example of why `format()` would be dumb as an instance method. In .NET (and probably in Java), `Replace()` is an instance method. You can do this: ``` "I Like Wine".Replace("Wine","Beer"); ``` However, nothing happens, because strings are immutable. `Replace()` tries to return a new string, but it is assigned to nothing. This causes lots of common rookie mistakes like: ``` inputText.Replace(" ", "%20"); ``` Again, nothing happens, instead you have to do: ``` inputText = inputText.Replace(" ","%20"); ``` Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for `Replace()` would be where `format()` is, as a static method of `String`: ``` inputText = String.Replace(inputText, " ", "%20"); ``` Now there is no question as to what's going on. The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods. Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas). Of course there are some methods that are perfect as instance methods, take String.Length() ``` int length = "123".Length(); ``` In this situation, it's obvious we are not trying to modify "123", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method. My simple rules for Instance Methods on Immutable Objects: * If you need to return a new instance of the same type, use a static method. * Otherwise, use an instance method.
Sprintf equivalent in Java
[ "", "java", "string", "formatting", "" ]
I have been looking at the new [Objective-J / Cappuccino](http://cappuccino.org/) javascript framework from [280North](http://280north.com/). They provide plug-ins for SubEthaEdit and TextMate to handle syntax highlighting, but I primarily use vi. Does anyone know of a way to get Objective-J syntax highlighting in vi, or a good way to convert whatever format the other two editors use?
The Objective-J Tools package (<http://cappuccino.org/download>) and the source on github now include a vim highlight module.
> the source on github now include a vim > highlight module. I've found just doing what is suggested here is not enough: * download the file as Francisco suggests * unzip, `cd Tools/` dir * run the shell, `sh install-tools` * copy the objj.vim file to vim dir, `cp Tools/Editors/objj.vim /usr/share/vim/vim71/syntax/` **Problem** I found no syntax highlighting worked for ".j" files. So the problem here is no file extension recognition. If you are using gvim as I am there is also no menu item. **Add Objective-J to gvim menu** To add a menu-item in gvim for Syntax->Ne-MO->Objective J: * `sudo vim /usr/share/vim/vim71/synmenu.vim` add the following line. * `an 50.70.465 &Syntax.Me-NO.Objective\ J :cal SetSyn("objj")<CR>` below the objective-C entry. save and quit * `:wq!` then reload a ".j" file in gvim. If you then go: * *Syntax->Ne-MO->Objective J* highlighting for your selected Objective-J file should occur. **Objective-J auto-highlighting?** But what about auto-highlighting when you load the file? There appears to be no file associations. So: * `sudo vim /usr/share/vim/vim7.1/filetype.vim` In the file you will find a list of filetype associations. If you want an idea where to add the line, search for "*setf ocaml*" in filetype.vim. Add the line below above (alphabetical): * `"" Objective J au BufNewFile,BufRead *.j setf objj` Save the result. You should now be able to load a file with a ".j" extension and syntax highlighting for Objective-J files works. **Result** Now you should get automatic recognition of the Objective-J files by file type ".j" and a way to set this filetype in gvim. This probably should be added by Bram or whoever does the official release of vim but for the moment this hack works for me. (Ubuntu 8.10, Vim 7.1)
Anyone know of Objective-J syntax highlighting in vi?
[ "", "javascript", "vi", "cappuccino", "objective-j", "" ]
We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree. Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS?
Got the same issue. I just found the solution : ``` ..new Ext.tree.TreePanel({ ... selModel : new Ext.tree.MultiSelectionModel() ... }) ```
Check out this post in the ExtJS forum that details how you can enable multi-select in a Javascript tree. <http://extjs.com/forum/showthread.php?t=28115>
Javascript tree views that support multiple item drag/drop
[ "", "javascript", "ajax", "treeview", "drag-and-drop", "extjs", "" ]
About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<https://example.com>") Is there a better way -- ideally some setting in the web.config?
Please use [HSTS](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) (HTTP Strict Transport Security) from <http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx> ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="HTTP to HTTPS redirect" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTPS}" pattern="off" ignoreCase="true" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /> </rule> </rules> <outboundRules> <rule name="Add Strict-Transport-Security when HTTPS" enabled="true"> <match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" /> <conditions> <add input="{HTTPS}" pattern="on" ignoreCase="true" /> </conditions> <action type="Rewrite" value="max-age=31536000" /> </rule> </outboundRules> </rewrite> </system.webServer> </configuration> ``` **Original Answer** (replaced with the above on 4 December 2015) basically ``` protected void Application_BeginRequest(Object sender, EventArgs e) { if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false)) { Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl); } } ``` that would go in the global.asax.cs (or global.asax.vb) i dont know of a way to specify it in the web.config
The other thing you can do is use [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) by returning the "Strict-Transport-Security" header to the browser. The browser has to support this (and at present, it's primarily Chrome and Firefox that do), but it means that once set, the browser won't make requests to the site over HTTP and will instead translate them to HTTPS requests before issuing them. Try this in combination with a redirect from HTTP: ``` protected void Application_BeginRequest(Object sender, EventArgs e) { switch (Request.Url.Scheme) { case "https": Response.AddHeader("Strict-Transport-Security", "max-age=300"); break; case "http": var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery; Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", path); break; } } ``` Browsers that aren't HSTS aware will just ignore the header but will still get caught by the switch statement and sent over to HTTPS.
Best way in asp.net to force https for an entire site?
[ "", "c#", "asp.net", "vb.net", "webforms", "https", "" ]
I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?
Create a new launch configuration (Python Run) **Main tab** Use paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory) Don't forget to add the root folder of your application in the PYTHONPATH zone **Arguments** Set the base directory to the root folder also. As Program Arguments use "serve development.ini" (or whatever you use to debug your app") **Common Tab** Check allocate console and launch in background
If you'd rather not include your Python installation in your project's workspace to get paster, you can create a pure-Python driver like: ``` #!/usr/bin/env python from paste.script.serve import ServeCommand ServeCommand("serve").run(["development.ini"]) ``` ...and run/debug that in Eclipse. Note: this is running without the `--reload` option, so you don't get hot deploys (i.e., you'll need to reload server to see changes). Alternatively, you can add the `--reload` option to get hot deploys, but then Pydev won't stop at your breakpoints. Can't have your cake and eat it too... ``` ServeCommand("serve").run(["--reload", "development.ini"]) ```
Debug Pylons application through Eclipse
[ "", "python", "eclipse", "pylons", "pydev", "pyramid", "" ]