qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
96,133
<p>I have uncovered another problem in the effort that we are making to port several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. See <a href="https://stackoverflow.com/questions/74372/how-to-overcome-an-incompatibility-between-the-ksh-on-linux-vs-that-installed-o">here</a> for the previous problem.</p> <p>This code:</p> <pre><code>#!/bin/ksh if [ -a k* ]; then echo "Oh yeah!" else echo "No way!" fi exit 0 </code></pre> <p>(when run in a directory with several files whose name starts with k) produces "Oh yeah!" when called with the AT&amp;T ksh variants (ksh88 and ksh93). On the other hand it produces and error message followed by "No way!" on the other ksh variants (pdksh, MKS ksh and bash).</p> <p>Again, my question are: </p> <ul> <li>Is there an environment variable that will cause pdksh to behave like ksh93? Failing that:</li> <li>Is there an option on pdksh to get the required behavior?</li> </ul>
[ { "answer_id": 96857, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 0, "selected": false, "text": "<p>You do realize that [ is an alias (often a link, symbolic or hard) for <code>/usr/bin/test</code>, right? So perhaps the actu...
2008/09/18
[ "https://Stackoverflow.com/questions/96133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13029/" ]
I have uncovered another problem in the effort that we are making to port several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. See [here](https://stackoverflow.com/questions/74372/how-to-overcome-an-incompatibility-between-the-ksh-on-linux-vs-that-installed-o) for the previous problem. This code: ``` #!/bin/ksh if [ -a k* ]; then echo "Oh yeah!" else echo "No way!" fi exit 0 ``` (when run in a directory with several files whose name starts with k) produces "Oh yeah!" when called with the AT&T ksh variants (ksh88 and ksh93). On the other hand it produces and error message followed by "No way!" on the other ksh variants (pdksh, MKS ksh and bash). Again, my question are: * Is there an environment variable that will cause pdksh to behave like ksh93? Failing that: * Is there an option on pdksh to get the required behavior?
Well after one year there seems to be no solution to my problem. I am adding this answer to say that I will have to live with it......
96,150
<p>I have an application that uploads an Excel .xls file to the file system, opens the file with an oledbconnection object using the .open() method on the object instance and then stores the data in a database. The upload and writing of the file to the file system works fine but I get an error when trying to open the file on our production server <strong>only</strong>. The application works fine on two other servers (development and testing servers).</p> <p>The following code generates an 'Unspecified Error' in the Exception.Message.</p> <p><strong>Quote:</strong></p> <pre><code> System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"); try { x.Open(); } catch (Exception exp) { string errorEmailBody = " OpenExcelSpreadSheet() in Utilities.cs. " + exp.Message; Utilities.SendErrorEmail(errorEmailBody); } </code></pre> <p><strong>:End Quote</strong></p> <p>The server's c:\\temp and c:\Documents and Settings\\aspnet\local settings\temp folder both give \aspnet full control.</p> <p>I believe that there is some kind of permissions issue but can't seem to find any difference between the permissions on the noted folders and the folder/directory where the Excel file is uploaded. The same location is used to save the file and open it and the methods do work on my workstation and two web servers. Windows 2000 SP4 servers.</p>
[ { "answer_id": 96166, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>Anything in the inner exception? Is this a 64-bit application? The OLEDB providers don't work in 64-bit. You have to have ...
2008/09/18
[ "https://Stackoverflow.com/questions/96150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18164/" ]
I have an application that uploads an Excel .xls file to the file system, opens the file with an oledbconnection object using the .open() method on the object instance and then stores the data in a database. The upload and writing of the file to the file system works fine but I get an error when trying to open the file on our production server **only**. The application works fine on two other servers (development and testing servers). The following code generates an 'Unspecified Error' in the Exception.Message. **Quote:** ``` System.Data.OleDb.OleDbConnection x = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"); try { x.Open(); } catch (Exception exp) { string errorEmailBody = " OpenExcelSpreadSheet() in Utilities.cs. " + exp.Message; Utilities.SendErrorEmail(errorEmailBody); } ``` **:End Quote** The server's c:\\temp and c:\Documents and Settings\\aspnet\local settings\temp folder both give \aspnet full control. I believe that there is some kind of permissions issue but can't seem to find any difference between the permissions on the noted folders and the folder/directory where the Excel file is uploaded. The same location is used to save the file and open it and the methods do work on my workstation and two web servers. Windows 2000 SP4 servers.
While the permissions issue may be more common you can also encounter this error from Windows file system/Access Jet DB Engine connection limits, 64/255 I think. If you bust the 255 Access read/write concurrent connections or the 64(?) connection limit per process you can get this exact same error. At least I've come across that in an application where connections were being continually created and never properly closed. A simple `Conn.close();` dropped in and life was good. I imagine Excel could have similar issues.
96,153
<p>I am trying to figure out how to click a button on a web page programmatically.</p> <p>Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the target ASP.NET login page I'm trying to work with, in the DocumentCompleted event handler I have the following coded:</p> <pre><code>HtmlDocument doc = webBrowser1.Document; HtmlElement userID = doc.GetElementById("userIDTextBox"); userID.InnerText = "user1"; HtmlElement password = doc.GetElementById("userPasswordTextBox"); password.InnerText = "password"; HtmlElement button = doc.GetElementById("logonButton"); button.RaiseEvent("onclick"); </code></pre> <p>This fills the userid and password text boxes fine, but I am not having any success getting that darned button to click; I've also tried "click", "Click", and "onClick" -- what else is there?. A search of msdn of course gives me no clues, nor groups.google.com. I gotta be close. Or maybe not -- somebody told me I should call the POST method of the page, but how this is done was not part of the advice given. </p> <p>BTW The button is coded:</p> <pre><code>&lt;input type="submit" name="logonButton" value="Login" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" id="logonButton" tabindex="4" /&gt; </code></pre>
[ { "answer_id": 96172, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>You can try and invoke the Page_ClientValidate() method directly through the clientscript instead of clicking t...
2008/09/18
[ "https://Stackoverflow.com/questions/96153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16964/" ]
I am trying to figure out how to click a button on a web page programmatically. Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the target ASP.NET login page I'm trying to work with, in the DocumentCompleted event handler I have the following coded: ``` HtmlDocument doc = webBrowser1.Document; HtmlElement userID = doc.GetElementById("userIDTextBox"); userID.InnerText = "user1"; HtmlElement password = doc.GetElementById("userPasswordTextBox"); password.InnerText = "password"; HtmlElement button = doc.GetElementById("logonButton"); button.RaiseEvent("onclick"); ``` This fills the userid and password text boxes fine, but I am not having any success getting that darned button to click; I've also tried "click", "Click", and "onClick" -- what else is there?. A search of msdn of course gives me no clues, nor groups.google.com. I gotta be close. Or maybe not -- somebody told me I should call the POST method of the page, but how this is done was not part of the advice given. BTW The button is coded: ``` <input type="submit" name="logonButton" value="Login" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" id="logonButton" tabindex="4" /> ```
How does this work? Works for me ``` HtmlDocument doc = webBrowser1.Document; doc.All["userIDTextBox"].SetAttribute("Value", "user1"); doc.All["userPasswordTextBox"].SetAttribute("Value", "Password!"); doc.All["logonButton"].InvokeMember("Click"); ```
96,196
<p>The <strong>C</strong> preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a <code>#define</code>.</p> <p>The following macro: </p> <pre><code>#define SUCCEEDED(hr) ((HRESULT)(hr) &gt;= 0) </code></pre> <p>is in no way superior to the type safe:</p> <pre><code>inline bool succeeded(int hr) { return hr &gt;= 0; } </code></pre> <p>But macros do have their place, please list the uses you find for macros that you <em>can't</em> do without the preprocessor. </p> <p>Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments.</p>
[ { "answer_id": 96230, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": false, "text": "<p>When you want to change the program flow (<code>return</code>, <code>break</code> and <code>continue</code>) code in a funct...
2008/09/18
[ "https://Stackoverflow.com/questions/96196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
The **C** preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a `#define`. The following macro: ``` #define SUCCEEDED(hr) ((HRESULT)(hr) >= 0) ``` is in no way superior to the type safe: ``` inline bool succeeded(int hr) { return hr >= 0; } ``` But macros do have their place, please list the uses you find for macros that you *can't* do without the preprocessor. Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments.
As wrappers for debug functions, to automatically pass things like `__FILE__`, `__LINE__`, etc: ``` #ifdef ( DEBUG ) #define M_DebugLog( msg ) std::cout << __FILE__ << ":" << __LINE__ << ": " << msg #else #define M_DebugLog( msg ) #endif ``` Since C++20 the magic type [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location) can however be used instead of `__LINE__` and `__FILE__` to implement an analogue as a normal function (template).
96,249
<p>Adding an element to the head of an alist (Associative list) is simple enough:</p> <pre><code>&gt; (cons '(ding . 53) '((foo . 42) (bar . 27))) ((ding . 53) (foo . 42) (bar . 27)) </code></pre> <p>Appending to the tail of an alist is a bit trickier though. After some experimenting, I produced this:</p> <pre><code>&gt; (define (alist-append alist pair) `(,@alist ,pair)) &gt; (alist-append '((foo . 42) (bar . 27)) '(ding . 53)) '((foo . 42) (bar . 27) (ding . 53)) </code></pre> <p>However, it seems to me, that this isn't the idiomatic solution. So how is this usually done in scheme? Or is this in fact the way?</p>
[ { "answer_id": 96477, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>You don't append to an a-list. You cons onto an a-list.</p>\n\n<p>An a-list is logically a set of associations. You don't c...
2008/09/18
[ "https://Stackoverflow.com/questions/96249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18180/" ]
Adding an element to the head of an alist (Associative list) is simple enough: ``` > (cons '(ding . 53) '((foo . 42) (bar . 27))) ((ding . 53) (foo . 42) (bar . 27)) ``` Appending to the tail of an alist is a bit trickier though. After some experimenting, I produced this: ``` > (define (alist-append alist pair) `(,@alist ,pair)) > (alist-append '((foo . 42) (bar . 27)) '(ding . 53)) '((foo . 42) (bar . 27) (ding . 53)) ``` However, it seems to me, that this isn't the idiomatic solution. So how is this usually done in scheme? Or is this in fact the way?
You don't append to an a-list. You cons onto an a-list. An a-list is logically a set of associations. You don't care about the order of elements in a set. All you care about is presence or absence of a particular element. In the case of an a-list, all you care about is whether there exists an association for a given tag (i.e., a pair whose CAR is the specified value), and, given that association, the associated value (i.e., in this implementation, the CDR of the pair).
96,250
<p>My project has both client and server components in the same solution file. I usually have the debugger set to start them together when debugging, but it's often the case where I start the server up outside of the debugger so I can start and stop the client as needed when working on client-side only stuff. (this is much faster). </p> <p>I'm trying to save myself the hassle of poking around in Solution Explorer to start individual projects and would rather just stick a button on the toolbar that calls a macro that starts the debugger for individual projects (while leaving "F5" type debugging alone to start up both processess). </p> <p>I tried recording, but that didn't really result in anything useful. </p> <p>So far all I've managed to do is to locate the project item in the solution explorer: </p> <pre><code> Dim projItem As UIHierarchyItem projItem = DTE.ToolWindows.SolutionExplorer.GetItem("SolutionName\ProjectFolder\ProjectName").Select(vsUISelectionType.vsUISelectionTypeSelect) </code></pre> <p>(This is based loosely on how the macro recorder tried to do it. I'm not sure if navigating the UI object model is the correct approach, or if I should be looking at going through the Solution/Project object model instead). </p>
[ { "answer_id": 96478, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 4, "selected": true, "text": "<p>Ok. This appears to work from most UI (all?) contexts provided the solution is loaded: </p>\n\n<pre><code> Sub DebugTh...
2008/09/18
[ "https://Stackoverflow.com/questions/96250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187/" ]
My project has both client and server components in the same solution file. I usually have the debugger set to start them together when debugging, but it's often the case where I start the server up outside of the debugger so I can start and stop the client as needed when working on client-side only stuff. (this is much faster). I'm trying to save myself the hassle of poking around in Solution Explorer to start individual projects and would rather just stick a button on the toolbar that calls a macro that starts the debugger for individual projects (while leaving "F5" type debugging alone to start up both processess). I tried recording, but that didn't really result in anything useful. So far all I've managed to do is to locate the project item in the solution explorer: ``` Dim projItem As UIHierarchyItem projItem = DTE.ToolWindows.SolutionExplorer.GetItem("SolutionName\ProjectFolder\ProjectName").Select(vsUISelectionType.vsUISelectionTypeSelect) ``` (This is based loosely on how the macro recorder tried to do it. I'm not sure if navigating the UI object model is the correct approach, or if I should be looking at going through the Solution/Project object model instead).
Ok. This appears to work from most UI (all?) contexts provided the solution is loaded: ``` Sub DebugTheServer() DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate() DTE.ActiveWindow.Object.GetItem("Solution\ServerFolder\ServerProject").Select(vsUISelectionType.vsUISelectionTypeSelect) DTE.Windows.Item(Constants.vsWindowKindOutput).Activate() DTE.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance") End Sub ```
96,264
<p>I have two code bases of an application. I need to copy all the files in all the directories with .java from the newer code base, to the older (so I can commit it to svn).</p> <p>How can I write a batch files to do this?</p>
[ { "answer_id": 96270, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 4, "selected": true, "text": "<p>XCOPY /D ?</p>\n\n<pre><code>xcopy c:\\olddir\\*.java c:\\newdir /D /E /Q /Y\n</code></pre>\n" }, { "answer_id": 96...
2008/09/18
[ "https://Stackoverflow.com/questions/96264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
I have two code bases of an application. I need to copy all the files in all the directories with .java from the newer code base, to the older (so I can commit it to svn). How can I write a batch files to do this?
XCOPY /D ? ``` xcopy c:\olddir\*.java c:\newdir /D /E /Q /Y ```
96,265
<p>I am programming a game on the iPhone. I am currently using NSTimer to trigger my game update/render. The problem with this is that (after profiling) I appear to lose a lot of time between updates/renders and this seems to be mostly to do with the time interval that I plug into NSTimer. </p> <p>So my question is what is the best alternative to using NSTimer?</p> <p>One alternative per answer please.</p>
[ { "answer_id": 224791, "author": "Galghamon", "author_id": 26511, "author_profile": "https://Stackoverflow.com/users/26511", "pm_score": 2, "selected": false, "text": "<p>I don't know about the iPhone in particular, but I may still be able to help:\nInstead of simply plugging in a fixed ...
2008/09/18
[ "https://Stackoverflow.com/questions/96265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25868/" ]
I am programming a game on the iPhone. I am currently using NSTimer to trigger my game update/render. The problem with this is that (after profiling) I appear to lose a lot of time between updates/renders and this seems to be mostly to do with the time interval that I plug into NSTimer. So my question is what is the best alternative to using NSTimer? One alternative per answer please.
You can get a better performance with threads, try something like this: ``` - (void) gameLoop { while (running) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self renderFrame]; [pool release]; } } - (void) startLoop { running = YES; #ifdef THREADED_ANIMATION [NSThread detachNewThreadSelector:@selector(gameLoop) toTarget:self withObject:nil]; #else timer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60 target:self selector:@selector(renderFrame) userInfo:nil repeats:YES]; #endif } - (void) stopLoop { [timer invalidate]; running = NO; } ``` In the `renderFrame` method You prepare the framebuffer, draw frame and present the framebuffer on screen. (P.S. There is a great [article](http://dewitters.koonsolo.com/gameloop.html) on various types of game loops and their pros and cons.)
96,285
<p>I'm fresh out of college and have been working in C++ for some time now. I understand all the basics of C++ and use them, but I'm having a hard time grasping more advanced topics like pointers and classes. I've read some books and tutorials and I understand the examples in them, but then when I look at some advanced real life examples I cannot figure them out. This is killing me because I feel like its keeping me from bring my C++ programming to the next level. Did anybody else have this problem? If so, how did you break through it? Does anyone know of any books or tutorials that really describe pointers and class concepts well? or maybe some example code with good descriptive comments using advanced pointers and class techniques? any help would be greatly appreciated.</p>
[ { "answer_id": 96310, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "<p>Pretend a pointer is an array address.</p>\n\n<pre><code>x = 500; // memory address for hello;\nMEMORY[x] = \"hello...
2008/09/18
[ "https://Stackoverflow.com/questions/96285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117494/" ]
I'm fresh out of college and have been working in C++ for some time now. I understand all the basics of C++ and use them, but I'm having a hard time grasping more advanced topics like pointers and classes. I've read some books and tutorials and I understand the examples in them, but then when I look at some advanced real life examples I cannot figure them out. This is killing me because I feel like its keeping me from bring my C++ programming to the next level. Did anybody else have this problem? If so, how did you break through it? Does anyone know of any books or tutorials that really describe pointers and class concepts well? or maybe some example code with good descriptive comments using advanced pointers and class techniques? any help would be greatly appreciated.
Pointers and classes aren't really advanced topics in C++. They are pretty fundamental. For me, pointers solidified when I started drawing boxes with arrows. Draw a box for an int. And int\* is now a separate box with an arrow pointing to the int box. So: ``` int foo = 3; // integer int* bar = &foo; // assigns the address of foo to my pointer bar ``` With my pointer's box (bar) I have the choice of either looking at the address inside the box. (Which is the memory address of foo). Or I can manipulate whatever I have an address to. That manipulation means I'm following that arrow to the integer (foo). ``` *bar = 5; // asterix means "dereference" (follow the arrow), foo is now 5 bar = 0; // I just changed the address that bar points to ``` Classes are another topic entirely. There's some books on object oriented design, but I don't know good ones for beginners of the top of my head. You might have luck with an intro Java book.
96,297
<h2>General</h2> <ul> <li>Follow the same standards for all tests.</li> <li>Be clear about what each test state is.</li> <li>Be specific about the expected behavior.</li> </ul> <h2>Examples</h2> <p>1) MethodName_StateUnderTest_ExpectedBehavior</p> <pre><code>Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown () Public void Sum_simpleValues_Calculated () </code></pre> <p>Source: <a href="http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html" rel="noreferrer">Naming standards for Unit Tests</a></p> <p>2) Separating Each Word By Underscore</p> <pre><code>Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown() Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown () Public void Sum_Simple_Values_Calculated () </code></pre> <h2>Other</h2> <ul> <li>End method names with <em>Test</em></li> <li>Start method names with class name</li> </ul>
[ { "answer_id": 96344, "author": "Munger", "author_id": 17661, "author_profile": "https://Stackoverflow.com/users/17661", "pm_score": -1, "selected": false, "text": "<p>As long as you follow a single practice, it doesn't really matter. Generally, I write a single unit test for a method th...
2008/09/18
[ "https://Stackoverflow.com/questions/96297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18170/" ]
General ------- * Follow the same standards for all tests. * Be clear about what each test state is. * Be specific about the expected behavior. Examples -------- 1) MethodName\_StateUnderTest\_ExpectedBehavior ``` Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown () Public void Sum_simpleValues_Calculated () ``` Source: [Naming standards for Unit Tests](http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html) 2) Separating Each Word By Underscore ``` Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown() Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown () Public void Sum_Simple_Values_Calculated () ``` Other ----- * End method names with *Test* * Start method names with class name
I am pretty much with you on this one man. The naming conventions you have used are: * Clear about what each test state is. * Specific about the expected behaviour. What more do you need from a test name? Contrary to [Ray's answer](https://stackoverflow.com/questions/96297/naming-conventions-for-unit-tests#96476) I don't think the *Test* prefix is necessary. It's test code, we know that. If you need to do this to identify the code, then you have bigger problems, **your test code should not be mixed up with your production code.** As for length and use of underscore, its **test code**, who the hell cares? Only you and your team will see it, so long as it is readable, and clear about what the test is doing, carry on! :) That said, I am still quite new to testing and [blogging my adventures with it](http://cantgrokwontgrok.blogspot.com/2008/09/tdd-getting-started-with-test-driven.html) :)
96,313
<p>I've got a couple large checkouts where the .svn folder has become damaged so I'm getting and error, "Cleanup failed to process the following path.." And I can no longer commit or update files in that directory.</p> <p>I'd just delete and do the checkout again but the whole directory is over a gig.</p> <p>Is there a tool that will restore the .svn folders for specific folders without having to download everything?</p> <p>I understand that it's going to have to download all the files in that one folder so that it can determine if they've been changed..but subdirectories with valid .svn folders should be fine.</p> <p>Oh.. I'm a big fan of TortoiseSVN or the command line for linux.</p> <p>Thoughts?</p>
[ { "answer_id": 96364, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": false, "text": "<p>I've hit this in the past and found no working solution except the \"nuclear option\" (i.e. delete the directory and...
2008/09/18
[ "https://Stackoverflow.com/questions/96313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430/" ]
I've got a couple large checkouts where the .svn folder has become damaged so I'm getting and error, "Cleanup failed to process the following path.." And I can no longer commit or update files in that directory. I'd just delete and do the checkout again but the whole directory is over a gig. Is there a tool that will restore the .svn folders for specific folders without having to download everything? I understand that it's going to have to download all the files in that one folder so that it can determine if they've been changed..but subdirectories with valid .svn folders should be fine. Oh.. I'm a big fan of TortoiseSVN or the command line for linux. Thoughts?
In case you have changes to the files, and cannot delete them, you can use the Subversion 1.5 feature that allows you to 'checkout with obstructions'. Just delete the .svn directory in this directory and: (you don't need to delete inside directories when using --depth files, thanks Eric) In case the broken directory was the top directory of the working copy: ``` svn checkout --depth files --force REPOS WC ``` And if the directory above the broken one is still versioned run: ``` svn update --depth files --force WC ``` in that directory. In both samples REPOS is the url in the repository that matches the broken directory, and WC is the path to the directory. Files that were originally modified will be in the modified state after this.
96,326
<p>I need to attach a file with mailx but at the moment I am not having success.</p> <p><strong>Here's my code:</strong></p> <pre><code>subject="Something happened" to="somebody@somewhere.com" body="Attachment Test" attachment=/path/to/somefile.csv uuencode $attachment | mailx -s "$subject" "$to" &lt;&lt; EOF The message is ready to be sent with the following file or link attachments: somefile.csv Note: To protect against computer viruses, e-mail programs may prevent sending or receiving certain types of file attachments. Check your e-mail security settings to determine how attachments are handled. EOF </code></pre> <p>Any feedback would be highly appreciated.</p> <hr> <p><strong>Update</strong> I have added the attachment var to avoid having to use the path every time.</p>
[ { "answer_id": 96616, "author": "Thomas Kammeyer", "author_id": 4410, "author_profile": "https://Stackoverflow.com/users/4410", "pm_score": 1, "selected": false, "text": "<p>Well, here are the first few problems you've got.</p>\n\n<ol>\n<li><p>You appear to be assuming that a mail client...
2008/09/18
[ "https://Stackoverflow.com/questions/96326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
I need to attach a file with mailx but at the moment I am not having success. **Here's my code:** ``` subject="Something happened" to="somebody@somewhere.com" body="Attachment Test" attachment=/path/to/somefile.csv uuencode $attachment | mailx -s "$subject" "$to" << EOF The message is ready to be sent with the following file or link attachments: somefile.csv Note: To protect against computer viruses, e-mail programs may prevent sending or receiving certain types of file attachments. Check your e-mail security settings to determine how attachments are handled. EOF ``` Any feedback would be highly appreciated. --- **Update** I have added the attachment var to avoid having to use the path every time.
You have to concat both the text of your message and the uuencoded attachment: ``` $ subject="Something happened" $ to="somebody@somewhere.com" $ body="Attachment Test" $ attachment=/path/to/somefile.csv $ $ cat >msg.txt <<EOF > The message is ready to be sent with the following file or link attachments: > > somefile.csv > > Note: To protect against computer viruses, e-mail programs may prevent > sending or receiving certain types of file attachments. Check your > e-mail security settings to determine how attachments are handled. > > EOF $ ( cat msg.txt ; uuencode $attachment somefile.csv) | mailx -s "$subject" "$to" ``` There are different ways to provide the message text, this is just an example that is close to your original question. If the message should be reused it makes sense to just store it in a file and use this file.
96,340
<p>We have a suite of interlinked .Net 3.5 applications. Some are web sites, some are web services, and some are windows applications. Each app currently has its own configuration file (app.config or web.config), and currently there are some duplicate keys across the config files (which at the moment are kept in sync manually) as multiple apps require the same config value. Also, this suite of applications is deployed across various envrionemnts (dev, test, live etc)</p> <p>What is the best approach to managing the configuration of these multiple apps from a single configuration source, so configuration values can be shared between multiple apps if required? We would also like to have separate configs for each environment (so when deploying you don't have to manually change certain config values that are environment specific such as conenction strings), but at the same time don't want to maintain multiple large config files (one for each environment) as keeping this in sync when adding new config keys will prove troublesome.</p>
[ { "answer_id": 96371, "author": "Kevin Pang", "author_id": 1574, "author_profile": "https://Stackoverflow.com/users/1574", "pm_score": 3, "selected": false, "text": "<p>Visual Studio has a relatively obscure feature that lets you add existing items as links, which should accomplish what ...
2008/09/18
[ "https://Stackoverflow.com/questions/96340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17765/" ]
We have a suite of interlinked .Net 3.5 applications. Some are web sites, some are web services, and some are windows applications. Each app currently has its own configuration file (app.config or web.config), and currently there are some duplicate keys across the config files (which at the moment are kept in sync manually) as multiple apps require the same config value. Also, this suite of applications is deployed across various envrionemnts (dev, test, live etc) What is the best approach to managing the configuration of these multiple apps from a single configuration source, so configuration values can be shared between multiple apps if required? We would also like to have separate configs for each environment (so when deploying you don't have to manually change certain config values that are environment specific such as conenction strings), but at the same time don't want to maintain multiple large config files (one for each environment) as keeping this in sync when adding new config keys will prove troublesome.
We use file templates such as MyApp.config.template and MyWeb.config.template with NAnt properties for the bits that are different between environments. So the template file might look a bit like this: ``` <MyAppConfig> <DbConnString>${DbConnString}</DbConnString> <WebServiceUri uri="${WebServiceUri}" /> </MyAppConfig> ``` During a build we generate all the configs for the different environments by just looping through each environment in a NAnt script, changing the value of the NAnt properties ${DbConnString} and ${WebServiceUri} for each environment (in fact these are all set in a single file with sections for each environment), and doing a NAnt copy with the option to expand properties turned on. It took a little while to get set up but it has paid us back at least tenfold in the amount of time saved messing around with different versions of config files.
96,360
<p>I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST. (Non essential xml generating code replaced with "Hello there")</p> <pre><code> StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close(); </code></pre> <p>This is causing a server error, and the second servlet is never invoked.</p>
[ { "answer_id": 96393, "author": "Craig B.", "author_id": 10780, "author_profile": "https://Stackoverflow.com/users/10780", "pm_score": 2, "selected": false, "text": "<p>Don't forget to use: </p>\n\n<pre><code>connection.setDoOutput( true)\n</code></pre>\n\n<p>if you intend on sending out...
2008/09/18
[ "https://Stackoverflow.com/questions/96360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27/" ]
I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST. (Non essential xml generating code replaced with "Hello there") ``` StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close(); ``` This is causing a server error, and the second servlet is never invoked.
This kind of thing is much easier using a library like [HttpClient](http://hc.apache.org/httpclient-3.x/). There's even a [post XML code example](http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/PostXML.java?view=markup): ``` PostMethod post = new PostMethod(url); RequestEntity entity = new FileRequestEntity(inputFile, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); int result = httpclient.executeMethod(post); ```
96,377
<p>I am trying to use Validation in WPF. I created a NotNullOrEmptyValidationRule as shown below: </p> <pre><code>public class NotNullOrEmptyValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (String.IsNullOrEmpty(value as String)) return new ValidationResult(false, "Value cannot be null or empty"); return new ValidationResult(true, null); } } </code></pre> <p>Now, I need to use it in my application. In my App.xaml file I declared the Style for the TextBox. Here is the declaration. </p> <pre><code> &lt;Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}"&gt; &lt;Setter Property="Background" Value="Green"/&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="Validation.HasError" Value="True"&gt; &lt;Setter Property="Background" Value="Red"/&gt; &lt;Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p>Now, I want to use it on my TextBox so I am using the following code: </p> <pre><code> &lt;TextBox Style="{StaticResource textBoxStyle}"&gt; &lt;TextBox.Text&gt; &lt;Binding&gt; &lt;Binding.ValidationRules&gt; &lt;NotNullOrEmptyValidationRule /&gt; &lt;/Binding.ValidationRules&gt; &lt;/Binding&gt; &lt;/TextBox.Text&gt; &lt;/TextBox&gt; </code></pre> <p>The error comes on the Tag NotNullOrEmptyValidationRule. The XAML syntax checker is not able to resolve the NotNullOrEmptyValidationRule. I have even tried putting the namespace but it does not seem to work. </p>
[ { "answer_id": 96432, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "<p>There is a bug in Visual Studio and Expression Blend that causes this problem. What you need to do is make sure that ...
2008/09/18
[ "https://Stackoverflow.com/questions/96377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
I am trying to use Validation in WPF. I created a NotNullOrEmptyValidationRule as shown below: ``` public class NotNullOrEmptyValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (String.IsNullOrEmpty(value as String)) return new ValidationResult(false, "Value cannot be null or empty"); return new ValidationResult(true, null); } } ``` Now, I need to use it in my application. In my App.xaml file I declared the Style for the TextBox. Here is the declaration. ``` <Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}"> <Setter Property="Background" Value="Green"/> <Style.Triggers> <Trigger Property="Validation.HasError" Value="True"> <Setter Property="Background" Value="Red"/> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> ``` Now, I want to use it on my TextBox so I am using the following code: ``` <TextBox Style="{StaticResource textBoxStyle}"> <TextBox.Text> <Binding> <Binding.ValidationRules> <NotNullOrEmptyValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> ``` The error comes on the Tag NotNullOrEmptyValidationRule. The XAML syntax checker is not able to resolve the NotNullOrEmptyValidationRule. I have even tried putting the namespace but it does not seem to work.
i see your binding on the TextBox is set to a path of 'Text' - is that a field on whatever the datacontext of this textbox is? is the textbox actually getting a value put into it? also, if you put a breakpoint in your validation method, is that ever getting fired? you may want to lookup how to log failures in binding and review those as well..
96,390
<p>I have a SQL statement that looks like:</p> <pre><code>SELECT [Phone] FROM [Table] WHERE ( [Phone] LIKE '[A-Z][a-z]' OR [Phone] = 'N/A' OR [Phone] LIKE '[0]' ) </code></pre> <p>The part I'm having trouble with is the where statement with the "LIKEs". I've seen SQL statements where authors used <code>like</code> statements in the way I'm using them above. At first, I thought this might be a version of Regular Expressions but I've since learned. </p> <p>Is anyone familiar with using like statements in such a way. Note: the "N/A" is working fine. </p> <p>What I need to match is phone numbers that have characters. Or phone numbers which contain nothing but zero.</p>
[ { "answer_id": 96445, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 4, "selected": true, "text": "<p>Check <a href=\"http://technet.microsoft.com/en-us/library/aa933232(v=sql.80).aspx\" rel=\"nofollow noreferrer\...
2008/09/18
[ "https://Stackoverflow.com/questions/96390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18196/" ]
I have a SQL statement that looks like: ``` SELECT [Phone] FROM [Table] WHERE ( [Phone] LIKE '[A-Z][a-z]' OR [Phone] = 'N/A' OR [Phone] LIKE '[0]' ) ``` The part I'm having trouble with is the where statement with the "LIKEs". I've seen SQL statements where authors used `like` statements in the way I'm using them above. At first, I thought this might be a version of Regular Expressions but I've since learned. Is anyone familiar with using like statements in such a way. Note: the "N/A" is working fine. What I need to match is phone numbers that have characters. Or phone numbers which contain nothing but zero.
Check [here](http://technet.microsoft.com/en-us/library/aa933232(v=sql.80).aspx). [] matches a range of characters. I think you want something like this: ``` SELECT [Phone] FROM [Table] WHERE ( [Phone] LIKE '%[A-Z]%' OR [Phone] LIKE '%[a-z]%' OR [Phone] = 'N/A' OR [Phone] LIKE '0' ) ```
96,414
<p>I'm experimenting with adding icons to a shell extension. I have this code (sanitized for easy reading), which works:</p> <pre><code>InsertMenu(hmenu, index, MF_POPUP|MF_BYPOSITION, (UINT)hParentMenu, namestring); </code></pre> <p>The next step is this code:</p> <pre><code>HICON hIconLarge, hIconSmall; ICONINFO oIconInfo; ExtractIconEx("c:\\progra~1\\winzip\\winzip32.exe", 0, &amp;hIconLarge, &amp;hIconSmall, 1); GetIconInfo(hIconSmall, &amp;oIconInfo); //??????? SetMenuItemBitmaps(hParentMenu, indexMenu-1, MF_BITMAP | MF_BYPOSITION, hbmp, hbmp); </code></pre> <p>What do I put in to replace the ?'s. Attempts to Google this knowledge have found many tips that I failed to get working. Any advice on getting this to work, especially on older machines (e.g. no .net framework, no vista) is appreciated.</p>
[ { "answer_id": 96429, "author": "Lee H", "author_id": 18201, "author_profile": "https://Stackoverflow.com/users/18201", "pm_score": 2, "selected": false, "text": "<p>Setting up password-less publickey authentication with ssh would allow you to scp your files to any of your servers very q...
2008/09/18
[ "https://Stackoverflow.com/questions/96414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18192/" ]
I'm experimenting with adding icons to a shell extension. I have this code (sanitized for easy reading), which works: ``` InsertMenu(hmenu, index, MF_POPUP|MF_BYPOSITION, (UINT)hParentMenu, namestring); ``` The next step is this code: ``` HICON hIconLarge, hIconSmall; ICONINFO oIconInfo; ExtractIconEx("c:\\progra~1\\winzip\\winzip32.exe", 0, &hIconLarge, &hIconSmall, 1); GetIconInfo(hIconSmall, &oIconInfo); //??????? SetMenuItemBitmaps(hParentMenu, indexMenu-1, MF_BITMAP | MF_BYPOSITION, hbmp, hbmp); ``` What do I put in to replace the ?'s. Attempts to Google this knowledge have found many tips that I failed to get working. Any advice on getting this to work, especially on older machines (e.g. no .net framework, no vista) is appreciated.
[Capistrano](http://capify.org/) is pretty handy for that. There's a few people using it ([1](http://www.simplisticcomplexity.com/2006/8/16/automated-php-deployment-with-capistrano/), [2](http://www.contentwithstyle.co.uk/Blog/178), [3](http://laurentbois.com/2008/08/05/use-capistrano-in-enterprise-for-php-and-ruby-on-rails-applications/)) for deploying PHP code as evidenced by doing a [quick search](http://www.google.com/search?q=capistrano+php+deployment).
96,428
<p>I have this string</p> <pre><code>'john smith~123 Street~Apt 4~New York~NY~12345' </code></pre> <p>Using JavaScript, what is the fastest way to parse this into</p> <pre><code>var name = "john smith"; var street= "123 Street"; //etc... </code></pre>
[ { "answer_id": 96452, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 11, "selected": true, "text": "<p>With JavaScript’s <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" r...
2008/09/18
[ "https://Stackoverflow.com/questions/96428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
I have this string ``` 'john smith~123 Street~Apt 4~New York~NY~12345' ``` Using JavaScript, what is the fastest way to parse this into ``` var name = "john smith"; var street= "123 Street"; //etc... ```
With JavaScript’s [`String.prototype.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) function: ``` var input = 'john smith~123 Street~Apt 4~New York~NY~12345'; var fields = input.split('~'); var name = fields[0]; var street = fields[1]; // etc. ```
96,440
<p>I have a Flex application, which loads a SWF from CS3. The loaded SWF contains a text input called "myText". I can see this in the SWFLoader.content with no problems, but I don't know what type I should be treating it as in my Flex App. I thought the flex docs covered this but I can only find how to interact with another Flex SWF.</p> <p>The Flex debugger tells me it is of type fl.controls.TextInput, which makes sense. But FlexBuilder doesn't seem to know this class. While Flash and Flex both use AS3, Flex has a whole new library of GUI classes. I thought it also had all the Flash classes, but I can't get it to know of ANY fl.*** packages.</p>
[ { "answer_id": 96536, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 0, "selected": false, "text": "<p>Flex and Flash SWFs are essentially the same, just built using different tools. I'm not sure if they share the same compone...
2008/09/18
[ "https://Stackoverflow.com/questions/96440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
I have a Flex application, which loads a SWF from CS3. The loaded SWF contains a text input called "myText". I can see this in the SWFLoader.content with no problems, but I don't know what type I should be treating it as in my Flex App. I thought the flex docs covered this but I can only find how to interact with another Flex SWF. The Flex debugger tells me it is of type fl.controls.TextInput, which makes sense. But FlexBuilder doesn't seem to know this class. While Flash and Flex both use AS3, Flex has a whole new library of GUI classes. I thought it also had all the Flash classes, but I can't get it to know of ANY fl.\*\*\* packages.
The `fl.*` hierarchy of classes is Flash CS3-only. It's the Flash Components 3 library (I believe it's called, I might be wrong). However, you don't need the class to work with the object. As long as you can get a reference to it in your code, which you seem to have, you can assign the reference to an untyped variable and work with it anyway: ``` var textInput : * = getTheTextInput(); // insert your own method here textInput.text = "Lorem ipsum dolor sit amet"; textInput.setSelection(4, 15); ``` There is no need to know the type of an object in order to interact with it. Of course you lose type checking at compile time, but that's really not much of an issue, you just have to be extra careful. If you really, really want to reference the object as its real type, the class in question is located in ``` Adobe Flash CS3/Configuration/Component Source/ActionScript 3.0/User Interface/fl/controls/TextInput.as ``` ...if you have Flash CS3 installed, because it only ships with that application.
96,448
<p>I need to import a large CSV file into an SQL server. I'm using this :</p> <pre><code>BULK INSERT CSVTest FROM 'c:\csvfile.txt' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) GO </code></pre> <p>problem is all my fields are surrounded by quotes (" ") so a row actually looks like :</p> <pre><code>"1","","2","","sometimes with comma , inside", "" </code></pre> <p>Can I somehow bulk import them and tell SQL to use the quotes as field delimiters?</p> <p><strong>Edit</strong>: The problem with using '","' as delimiter, as in the examples suggested is that : What most examples do, is they import the data including the first " in the first column and the last " in the last, then they go ahead and strip that out. Alas my first (and last) column are datetime and will not allow a "20080902 to be imported as datetime.</p> <p>From what I've been reading arround I think FORMATFILE is the way to go, but documentation (including MSDN) is terribly unhelpfull.</p>
[ { "answer_id": 96474, "author": "K Richard", "author_id": 16771, "author_profile": "https://Stackoverflow.com/users/16771", "pm_score": 4, "selected": false, "text": "<p>Try <code>FIELDTERMINATOR='\",\"'</code></p>\n\n<p>Here is a great link to help with the first and last quote...look h...
2008/09/18
[ "https://Stackoverflow.com/questions/96448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
I need to import a large CSV file into an SQL server. I'm using this : ``` BULK INSERT CSVTest FROM 'c:\csvfile.txt' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) GO ``` problem is all my fields are surrounded by quotes (" ") so a row actually looks like : ``` "1","","2","","sometimes with comma , inside", "" ``` Can I somehow bulk import them and tell SQL to use the quotes as field delimiters? **Edit**: The problem with using '","' as delimiter, as in the examples suggested is that : What most examples do, is they import the data including the first " in the first column and the last " in the last, then they go ahead and strip that out. Alas my first (and last) column are datetime and will not allow a "20080902 to be imported as datetime. From what I've been reading arround I think FORMATFILE is the way to go, but documentation (including MSDN) is terribly unhelpfull.
I know this isn't a real solution but I use a dummy table for the import with nvarchar set for everything. Then I do an insert which strips out the " characters and does the conversions. It isn't pretty but it does the job.
96,463
<p>How do you access the response from the Request object in MooTools? I've been looking at the documentation and the MooTorial, but I can't seem to make any headway. Other Ajax stuff I've done with MooTools I haven't had to manipulate the response at all, so I've just been able to inject it straight into the document, but now I need to make some changes to it first. I don't want to alert the response, I'd like to access it so I can make further changes to it. Any help would be greatly appreciated. Thanks.</p> <p>Edit:</p> <p>I'd like to be able to access the response after the request has already been made, preferably outside of the Request object. It's for an RSS reader, so I need to do some parsing and Request is just being used to get the feed from a server file. This function is a method in a class, which should return the response in a string, but it isn't returning anything but undefined:</p> <pre><code> fetch: function(site){ var feed; var req = new Request({ method: this.options.method, url: this.options.rssFetchPath, data: { 'url' : site }, onRequest: function() { if (this.options.targetId) { $ (this.options.targetId).setProperty('html', this.options.onRequestMessage); } }.bind(this), onSuccess: function(responseText) { feed = responseText; } }); req.send(); return feed; } </code></pre>
[ { "answer_id": 96573, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "<p>The response content is returned to the anonymous function defined in onComplete.</p>\n\n<p>It can be accessed from t...
2008/09/18
[ "https://Stackoverflow.com/questions/96463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
How do you access the response from the Request object in MooTools? I've been looking at the documentation and the MooTorial, but I can't seem to make any headway. Other Ajax stuff I've done with MooTools I haven't had to manipulate the response at all, so I've just been able to inject it straight into the document, but now I need to make some changes to it first. I don't want to alert the response, I'd like to access it so I can make further changes to it. Any help would be greatly appreciated. Thanks. Edit: I'd like to be able to access the response after the request has already been made, preferably outside of the Request object. It's for an RSS reader, so I need to do some parsing and Request is just being used to get the feed from a server file. This function is a method in a class, which should return the response in a string, but it isn't returning anything but undefined: ``` fetch: function(site){ var feed; var req = new Request({ method: this.options.method, url: this.options.rssFetchPath, data: { 'url' : site }, onRequest: function() { if (this.options.targetId) { $ (this.options.targetId).setProperty('html', this.options.onRequestMessage); } }.bind(this), onSuccess: function(responseText) { feed = responseText; } }); req.send(); return feed; } ```
I was able to find my answer on the [MooTools Group at Google](http://groups.google.com/group/mootools-users/browse_thread/thread/7ade43ef51c91922).
96,500
<p>Suppose I have the following code:</p> <pre><code>class some_class{}; some_class some_function() { return some_class(); } </code></pre> <p>This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong?</p>
[ { "answer_id": 96530, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 5, "selected": true, "text": "<p>No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the...
2008/09/18
[ "https://Stackoverflow.com/questions/96500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Suppose I have the following code: ``` class some_class{}; some_class some_function() { return some_class(); } ``` This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong?
No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary.
96,541
<p>This isn't legal:</p> <pre><code>public class MyBaseClass { public MyBaseClass() {} public MyBaseClass(object arg) {} } public void ThisIsANoNo&lt;T&gt;() where T : MyBaseClass { T foo = new T("whoops!"); } </code></pre> <p>In order to do this, you have to do some reflection on the type object for T or you have to use Activator.CreateInstance. Both are pretty nasty. Is there a better way?</p>
[ { "answer_id": 96557, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<pre><code>where T : MyBaseClass, new()\n</code></pre>\n\n<p>only works w/ parameterless public constructor. beyond that, bac...
2008/09/18
[ "https://Stackoverflow.com/questions/96541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This isn't legal: ``` public class MyBaseClass { public MyBaseClass() {} public MyBaseClass(object arg) {} } public void ThisIsANoNo<T>() where T : MyBaseClass { T foo = new T("whoops!"); } ``` In order to do this, you have to do some reflection on the type object for T or you have to use Activator.CreateInstance. Both are pretty nasty. Is there a better way?
You can't constrain T to have a particular constructor signature other than an empty constructor, but you can constrain T to have a factory method with the desired signature: ``` public abstract class MyBaseClass { protected MyBaseClass() {} protected abstract MyBaseClass CreateFromObject(object arg); } public void ThisWorksButIsntGreat<T>() where T : MyBaseClass, new() { T foo = new T().CreateFromObject("whoopee!") as T; } ``` However, I would suggest perhaps using a different creational pattern such as Abstract Factory for this scenario.
96,553
<p>Is it particularly bad to have a very, very large SQL query with lots of (potentially redundant) WHERE clauses?</p> <p>For example, here's a query I've generated from my web application with everything turned off, which should be the largest possible query for this program to generate:</p> <pre><code>SELECT * FROM 4e_magic_items INNER JOIN 4e_magic_item_levels ON 4e_magic_items.id = 4e_magic_item_levels.itemid INNER JOIN 4e_monster_sources ON 4e_magic_items.source = 4e_monster_sources.id WHERE (itemlevel BETWEEN 1 AND 30) AND source!=16 AND source!=2 AND source!=5 AND source!=13 AND source!=15 AND source!=3 AND source!=4 AND source!=12 AND source!=7 AND source!=14 AND source!=11 AND source!=10 AND source!=8 AND source!=1 AND source!=6 AND source!=9 AND type!='Arms' AND type!='Feet' AND type!='Hands' AND type!='Head' AND type!='Neck' AND type!='Orb' AND type!='Potion' AND type!='Ring' AND type!='Rod' AND type!='Staff' AND type!='Symbol' AND type!='Waist' AND type!='Wand' AND type!='Wondrous Item' AND type!='Alchemical Item' AND type!='Elixir' AND type!='Reagent' AND type!='Whetstone' AND type!='Other Consumable' AND type!='Companion' AND type!='Mount' AND (type!='Armor' OR (false )) AND (type!='Weapon' OR (false )) ORDER BY type ASC, itemlevel ASC, name ASC </code></pre> <p>It seems to work well enough, but it's also not particularly high traffic (a few hundred hits a day or so), and I wonder if it would be worth the effort to try and optimize the queries to remove redundancies and such.</p>
[ { "answer_id": 96572, "author": "Oskar", "author_id": 5472, "author_profile": "https://Stackoverflow.com/users/5472", "pm_score": 0, "selected": false, "text": "<p>Most databases support stored procedures to avoid this issue. If your code is fast enough to execute and easy to read, you d...
2008/09/18
[ "https://Stackoverflow.com/questions/96553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18210/" ]
Is it particularly bad to have a very, very large SQL query with lots of (potentially redundant) WHERE clauses? For example, here's a query I've generated from my web application with everything turned off, which should be the largest possible query for this program to generate: ``` SELECT * FROM 4e_magic_items INNER JOIN 4e_magic_item_levels ON 4e_magic_items.id = 4e_magic_item_levels.itemid INNER JOIN 4e_monster_sources ON 4e_magic_items.source = 4e_monster_sources.id WHERE (itemlevel BETWEEN 1 AND 30) AND source!=16 AND source!=2 AND source!=5 AND source!=13 AND source!=15 AND source!=3 AND source!=4 AND source!=12 AND source!=7 AND source!=14 AND source!=11 AND source!=10 AND source!=8 AND source!=1 AND source!=6 AND source!=9 AND type!='Arms' AND type!='Feet' AND type!='Hands' AND type!='Head' AND type!='Neck' AND type!='Orb' AND type!='Potion' AND type!='Ring' AND type!='Rod' AND type!='Staff' AND type!='Symbol' AND type!='Waist' AND type!='Wand' AND type!='Wondrous Item' AND type!='Alchemical Item' AND type!='Elixir' AND type!='Reagent' AND type!='Whetstone' AND type!='Other Consumable' AND type!='Companion' AND type!='Mount' AND (type!='Armor' OR (false )) AND (type!='Weapon' OR (false )) ORDER BY type ASC, itemlevel ASC, name ASC ``` It seems to work well enough, but it's also not particularly high traffic (a few hundred hits a day or so), and I wonder if it would be worth the effort to try and optimize the queries to remove redundancies and such.
Reading your query makes me want to play an RPG. This is definitely not too long. As long as they are well formatted, I'd say a practical limit is about 100 lines. After that, you're better off breaking subqueries into views just to keep your eyes from crossing. I've worked with some queries that are 1000+ lines, and that's hard to debug. By the way, may I suggest a reformatted version? This is mostly to demonstrate the importance of formatting; I trust this will be easier to understand. ``` select * from 4e_magic_items mi ,4e_magic_item_levels mil ,4e_monster_sources ms where mi.id = mil.itemid and mi.source = ms.id and itemlevel between 1 and 30 and source not in(16,2,5,13,15,3,4,12,7,14,11,10,8,1,6,9) and type not in( 'Arms' ,'Feet' ,'Hands' ,'Head' ,'Neck' ,'Orb' , 'Potion' ,'Ring' ,'Rod' ,'Staff' ,'Symbol' ,'Waist' , 'Wand' ,'Wondrous Item' ,'Alchemical Item' ,'Elixir' , 'Reagent' ,'Whetstone' ,'Other Consumable' ,'Companion' , 'Mount' ) and ((type != 'Armor') or (false)) and ((type != 'Weapon') or (false)) order by type asc ,itemlevel asc ,name asc /* Some thoughts: ============== 0 - Formatting really matters, in SQL even more than most languages. 1 - consider selecting only the columns you need, not "*" 2 - use of table aliases makes it short & clear ("MI", "MIL" in my example) 3 - joins in the WHERE clause will un-clutter your FROM clause 4 - use NOT IN for long lists 5 - logically, the last two lines can be added to the "type not in" section. I'm not sure why you have the "or false", but I'll assume some good reason and leave them here. */ ```
96,579
<p>I'm writing an inner loop that needs to place <code>struct</code>s in contiguous storage. I don't know how many of these <code>struct</code>s there will be ahead of time. My problem is that STL's <code>vector</code> initializes its values to 0, so no matter what I do, I incur the cost of the initialization plus the cost of setting the <code>struct</code>'s members to their values.</p> <p>Is there any way to prevent the initialization, or is there an STL-like container out there with resizeable contiguous storage and uninitialized elements?</p> <p>(I'm certain that this part of the code needs to be optimized, and I'm certain that the initialization is a significant cost.)</p> <p>Also, see my comments below for a clarification about when the initialization occurs.</p> <p>SOME CODE:</p> <pre><code>void GetsCalledALot(int* data1, int* data2, int count) { int mvSize = memberVector.size() memberVector.resize(mvSize + count); // causes 0-initialization for (int i = 0; i &lt; count; ++i) { memberVector[mvSize + i].d1 = data1[i]; memberVector[mvSize + i].d2 = data2[i]; } } </code></pre>
[ { "answer_id": 96601, "author": "nsanders", "author_id": 1244, "author_profile": "https://Stackoverflow.com/users/1244", "pm_score": 1, "selected": false, "text": "<p>Use the std::vector::reserve() method. It won't resize the vector, but it will allocate the space.</p>\n" }, { "...
2008/09/18
[ "https://Stackoverflow.com/questions/96579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6160/" ]
I'm writing an inner loop that needs to place `struct`s in contiguous storage. I don't know how many of these `struct`s there will be ahead of time. My problem is that STL's `vector` initializes its values to 0, so no matter what I do, I incur the cost of the initialization plus the cost of setting the `struct`'s members to their values. Is there any way to prevent the initialization, or is there an STL-like container out there with resizeable contiguous storage and uninitialized elements? (I'm certain that this part of the code needs to be optimized, and I'm certain that the initialization is a significant cost.) Also, see my comments below for a clarification about when the initialization occurs. SOME CODE: ``` void GetsCalledALot(int* data1, int* data2, int count) { int mvSize = memberVector.size() memberVector.resize(mvSize + count); // causes 0-initialization for (int i = 0; i < count; ++i) { memberVector[mvSize + i].d1 = data1[i]; memberVector[mvSize + i].d2 = data2[i]; } } ```
`std::vector` must initialize the values in the array somehow, which means some constructor (or copy-constructor) must be called. The behavior of `vector` (or any container class) is undefined if you were to access the uninitialized section of the array as if it were initialized. The best way is to use `reserve()` and `push_back()`, so that the copy-constructor is used, avoiding default-construction. Using your example code: ``` struct YourData { int d1; int d2; YourData(int v1, int v2) : d1(v1), d2(v2) {} }; std::vector<YourData> memberVector; void GetsCalledALot(int* data1, int* data2, int count) { int mvSize = memberVector.size(); // Does not initialize the extra elements memberVector.reserve(mvSize + count); // Note: consider using std::generate_n or std::copy instead of this loop. for (int i = 0; i < count; ++i) { // Copy construct using a temporary. memberVector.push_back(YourData(data1[i], data2[i])); } } ``` The only problem with calling `reserve()` (or `resize()`) like this is that you may end up invoking the copy-constructor more often than you need to. If you can make a good prediction as to the final size of the array, it's better to `reserve()` the space once at the beginning. If you don't know the final size though, at least the number of copies will be minimal on average. In the current version of C++, the inner loop is a bit inefficient as a temporary value is constructed on the stack, copy-constructed to the vectors memory, and finally the temporary is destroyed. However the next version of C++ has a feature called R-Value references (`T&&`) which will help. The interface supplied by `std::vector` does not allow for another option, which is to use some factory-like class to construct values other than the default. Here is a rough example of what this pattern would look like implemented in C++: ``` template <typename T> class my_vector_replacement { // ... template <typename F> my_vector::push_back_using_factory(F factory) { // ... check size of array, and resize if needed. // Copy construct using placement new, new(arrayData+end) T(factory()) end += sizeof(T); } char* arrayData; size_t end; // Of initialized data in arrayData }; // One of many possible implementations struct MyFactory { MyFactory(int* p1, int* p2) : d1(p1), d2(p2) {} YourData operator()() const { return YourData(*d1,*d2); } int* d1; int* d2; }; void GetsCalledALot(int* data1, int* data2, int count) { // ... Still will need the same call to a reserve() type function. // Note: consider using std::generate_n or std::copy instead of this loop. for (int i = 0; i < count; ++i) { // Copy construct using a factory memberVector.push_back_using_factory(MyFactory(data1+i, data2+i)); } } ``` Doing this does mean you have to create your own vector class. In this case it also complicates what should have been a simple example. But there may be times where using a factory function like this is better, for instance if the insert is conditional on some other value, and you would have to otherwise unconditionally construct some expensive temporary even if it wasn't actually needed.
96,597
<p>My development server (CentOS 5) is running Subversion 1.4.2, and I wish to upgrade it to 1.5. I have read in various blogs and documents scattered around the web that this may be done by using RPMForge. I have followed the instructions found on <a href="http://wiki.centos.org/AdditionalResources/Repositories/RPMForge?action=show&amp;redirect=Repositories%2FRPMForge" rel="nofollow noreferrer">CentOS Wiki</a>, including installing yum-priorities and setting my priorities as indicated (1 and 2 for core repo sources, and 20 for RPMForge).</p> <p>However, when I attempt to run:</p> <pre><code>$ yum info subversion </code></pre> <p>the version number given to me is still 1.4.2, with a status of Installed. My other option at this point is compiling from source, but I would like to find a package-managed solution for ease of future upgrades.</p> <p>Any thoughts?</p>
[ { "answer_id": 96662, "author": "Peter Stone", "author_id": 1806, "author_profile": "https://Stackoverflow.com/users/1806", "pm_score": 1, "selected": false, "text": "<p>If you install <a href=\"http://wiki.centos.org/AdditionalResources/Repositories/RPMForge\" rel=\"nofollow noreferrer\...
2008/09/18
[ "https://Stackoverflow.com/questions/96597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5570/" ]
My development server (CentOS 5) is running Subversion 1.4.2, and I wish to upgrade it to 1.5. I have read in various blogs and documents scattered around the web that this may be done by using RPMForge. I have followed the instructions found on [CentOS Wiki](http://wiki.centos.org/AdditionalResources/Repositories/RPMForge?action=show&redirect=Repositories%2FRPMForge), including installing yum-priorities and setting my priorities as indicated (1 and 2 for core repo sources, and 20 for RPMForge). However, when I attempt to run: ``` $ yum info subversion ``` the version number given to me is still 1.4.2, with a status of Installed. My other option at this point is compiling from source, but I would like to find a package-managed solution for ease of future upgrades. Any thoughts?
What you are trying to do is to replace a "core" package (one which is contained in the CentOS repository) with a newer package from a "3rd party" repository (RPMForge), which is what the priorities plugin is designed to prevent. The RPMForge repository contains both additional packages not found in CentOS, as well as newer versions of core packages. Unfortunately, `yum` is pretty stupid and will always update a package to the latest version it can find in *any* repository. So running "`yum update`" with RPMforge enabled will update half of your system with the latest (bleeding edge, possibly unstable and less well supported) packages from RPMForge. Therefore, the recommended way to use repos like RPMForge is to use them only together with a yum plugin like "priorites", which prevents packages from "high" priority repos to overwrite those from "low" priority repos (the name of the "priority" parameter is very misleading). This way you can savely install *additional* packages (that are not in core) from RPMForge, which is what most people want. Now to your original question ... If you *want* to replace a core package, things get a little tricky. Basically, you have two options: 1. Uninstall the priority plugin, and *disable* the RPMForge repository by default (set `enabled = 0` in `/etc/yum.repos.d/rpmforge.repo`). You can then selectively enable it on the command line: ``` yum --enablerepo=rpmforge install subversion ``` will install the latest subversion and dependencies from RPMForge. The problem with this approach is that if there is an update to the subversion package in RPMForge, you will not see it when the repo is disabled. To keep subversion up to date, you have to remember to run ``` yum --enablerepo=rpmforge update subversion ``` from time to time. 2. The second possibility is to use the priorites plugin, but manually "mask" the core subversion package (add `exclude=subversion` to the `[base]` and `[update]` sections in `/etc/yum.repos.d/CentOS-Base.repo`). Now yum will behave as if there is no package named "subversion" in the core repository and happily install the latest version from RPMForge. Plus, you will always get the latest subversion updates when running `yum update`.
96,615
<p>So if I'm using branches that are remote (tracked) branches, and I want to get the lastest, I'm still unclear if I should be doing <code>git pull</code> or <code>git rebase</code>. I thought I had read that doing <code>git rebase</code> when working on a branch with other users, it can screw them up when they pull or rebase. Is that true? Should we all be using <code>git pull</code>?</p>
[ { "answer_id": 96666, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p><code>git pull</code> does a merge if you've got commits that aren't in the remote branch. <code>git rebase</code> rewr...
2008/09/18
[ "https://Stackoverflow.com/questions/96615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14873/" ]
So if I'm using branches that are remote (tracked) branches, and I want to get the lastest, I'm still unclear if I should be doing `git pull` or `git rebase`. I thought I had read that doing `git rebase` when working on a branch with other users, it can screw them up when they pull or rebase. Is that true? Should we all be using `git pull`?
Git pull is a combination of 2 commands * git fetch (syncs your local repo with the newest stuff on the remote) * git merge (merges the changes from the distant branch, if any, into your local tracking branch) git rebase is only a rough equivalent to git merge. It doesn't fetch anything remotely. In fact it doesn't do a proper merge either, it replays the commits of the branch you're standing on after the new commits from a second branch. Its purpose is mainly to let you have a cleaner history. It doesn't take many merges by many people before the past history in gitk gets terribly spaghetti-like. The best graphical explanation can be seen in the first 2 graphics [here](http://www.kernel.org/pub/software/scm/git/docs/v1.5.4.3/git-rebase.html). But let me explain here with an example. I have 2 branches: master and mybranch. When standing on mybranch I can run ``` git rebase master ``` and I'll get anything new in master inserted before my most recent commits in mybranch. This is perfect, because if I now merge or rebase the stuff from mybranch in master, my new commits are added linearly right after the most recent commits. The problem you refer to happens if I rebase in the "wrong" direction. If I just got the most recent master (with new changes) and from master I rebase like this (before syncing my branch): ``` git rebase mybranch ``` Now what I just did is that I inserted my new changes somewhere in master's past. The main line of commits has changed. And due to the way git works with commit ids, all the commits (from master) that were just replayed over my new changes have new ids. Well, it's a bit hard to explain just in words... Hope this makes a bit of sense :-) Anyway, my own workflow is this: * 'git pull' new changes from remote * switch to mybranch * 'git rebase master' to bring master's new changes in my commit history * switch back to master * 'git merge mybranch', which only fast-forwards when everything in master is also in mybranch (thus avoiding the commit reordering problem on a public branch) * 'git push' One last word. I strongly recommend using rebase when the differences are trivial (e.g. people working on different files or at least different lines). It has the gotcha I tried to explain just up there, but it makes for a much cleaner history. As soon as there may be significant conflicts (e.g. a coworker has renamed something in a bunch of files), I strongly recommend merge. In this case, you'll be asked to resolve the conflict and then commit the resolution. On the plus side, a merge is much easier to resolve when there are conflicts. The down side is that your history may become hard to follow if a lot of people do merges all the time :-) Good luck!
96,618
<p>Let's say I have data structures that're something like this:</p> <pre><code>Public Class AttendenceRecord Public CourseDate As Date Public StudentsInAttendence As Integer End Class Public Class Course Public Name As String Public CourseID As String Public Attendance As List(Of AttendenceRecord) End Class </code></pre> <p>And I want a table that looks something like this:</p> <pre> | Course Name | Course ID | [Attendence(0).CourseDate] | [Attendence(1).CourseDate]| ... | Intro to CS | CS-1000 | 23 | 24 | ... | Data Struct | CS-2103 | 15 | 14 | ... </pre> <p>How would I, in the general case, get everything to the right of Course ID to be horizontally scrollable, while holding Course Name and Course ID in place? Ideally using a table, listview, or datagrid inside ASP.NET and/or WinForms.</p>
[ { "answer_id": 96642, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": "<p>In pure .Net I don't know of anything. There are <a href=\"http://www.imaputz.com/cssStuff/bigFourVersion.html\" rel=\...
2008/09/18
[ "https://Stackoverflow.com/questions/96618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18224/" ]
Let's say I have data structures that're something like this: ``` Public Class AttendenceRecord Public CourseDate As Date Public StudentsInAttendence As Integer End Class Public Class Course Public Name As String Public CourseID As String Public Attendance As List(Of AttendenceRecord) End Class ``` And I want a table that looks something like this: ``` | Course Name | Course ID | [Attendence(0).CourseDate] | [Attendence(1).CourseDate]| ... | Intro to CS | CS-1000 | 23 | 24 | ... | Data Struct | CS-2103 | 15 | 14 | ... ``` How would I, in the general case, get everything to the right of Course ID to be horizontally scrollable, while holding Course Name and Course ID in place? Ideally using a table, listview, or datagrid inside ASP.NET and/or WinForms.
You can get this functionality from the System.Windows.Forms.DataGridView control. When you create columns you can set them to be [frozen](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.frozen.aspx) which will then only scroll those columns to the right of the frozen column(s).
96,624
<p>I have an assembly which should <strong>not</strong> be used by any application other than the designated executable. Please give me some instructions to do so.</p>
[ { "answer_id": 96647, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 1, "selected": false, "text": "<p>You might be able to set this in the Code Access Security policies on the assembly.</p>\n" }, { "answer_id"...
2008/09/18
[ "https://Stackoverflow.com/questions/96624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18198/" ]
I have an assembly which should **not** be used by any application other than the designated executable. Please give me some instructions to do so.
You can sign the assembly and the executable with the same key and then put a check in the constructor of the classes you want to protect: ``` public class NotForAnyoneElse { public NotForAnyoneElse() { if (typeof(NotForAnyoneElse).Assembly.GetName().GetPublicKeyToken() != Assembly.GetEntryAssembly().GetName().GetPublicKeyToken()) { throw new SomeException(...); } } } ```
96,661
<p>I have a query that I would like to filter in different ways at different times. The way I have done this right now by placing parameters in the criteria field of the relevant query fields, however there are many cases in which I do not want to filter on a given field but only on the other fields. Is there any way in which a wildcard of some sort can be passed to the criteria parameter so that I can bypass the filtering for that particular call of the query?</p>
[ { "answer_id": 96782, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 0, "selected": false, "text": "<p>I don't think you can. How are you running the query? </p>\n\n<p>I'd say if you need a query that has that many open variable...
2008/09/18
[ "https://Stackoverflow.com/questions/96661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I have a query that I would like to filter in different ways at different times. The way I have done this right now by placing parameters in the criteria field of the relevant query fields, however there are many cases in which I do not want to filter on a given field but only on the other fields. Is there any way in which a wildcard of some sort can be passed to the criteria parameter so that I can bypass the filtering for that particular call of the query?
If you construct your query like so: ``` PARAMETERS ParamA Text ( 255 ); SELECT t.id, t.topic_id FROM SomeTable t WHERE t.id Like IIf(IsNull([ParamA]),"*",[ParamA]) ``` All records will be selected if the parameter is not filled in.
96,671
<p>I have a flash app (SWF) running Flash 8 embedded in an HTML page. How do I get flash to reload the parent HTML page it is embedded in? I've tried using ExternalInterface to call a JavaScript function to reload the page but that doesn't seem to work. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 96717, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": 2, "selected": false, "text": "<p>Try something like this:</p>\n\n<p><code>getURL(\"javascript:location.reload(true)\");</code></p>\n" }, { "ans...
2008/09/18
[ "https://Stackoverflow.com/questions/96671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a flash app (SWF) running Flash 8 embedded in an HTML page. How do I get flash to reload the parent HTML page it is embedded in? I've tried using ExternalInterface to call a JavaScript function to reload the page but that doesn't seem to work. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Check the [ExternalInterface](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html) in Action Script. Using this you can call any JavaScript function in your code: ``` if (ExternalInterface.available) { var result = ExternalInterface.call("reload"); } ``` In the Embedding HTML code enter a JavaScript function: ``` function reload() { document.location.reload(true); return true; } ``` This has the advantage that you can also check, if the function call succeeded and act accordingly. getUrl along with a call to JavaScript should not be used today anymore. It's an old hack.
96,718
<p>How do you organize your Extension Methods? Say if I had extensions for the object class and string class I'm tempted to separate these extension methods into classes IE:</p> <pre><code>public class ObjectExtensions { ... } public class StringExtensions { ... } </code></pre> <p>am I making this too complicated or does this make sense?</p>
[ { "answer_id": 96771, "author": "Geir-Tore Lindsve", "author_id": 4582, "author_profile": "https://Stackoverflow.com/users/4582", "pm_score": 2, "selected": false, "text": "<p>There are two ways that I organize the extension methods which I use,</p>\n\n<p>1) If the extension is specific ...
2008/09/18
[ "https://Stackoverflow.com/questions/96718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1980/" ]
How do you organize your Extension Methods? Say if I had extensions for the object class and string class I'm tempted to separate these extension methods into classes IE: ``` public class ObjectExtensions { ... } public class StringExtensions { ... } ``` am I making this too complicated or does this make sense?
I organize extension methods using a combination of namespace and class name, and it's similar to the way you describe in the question. Generally I have some sort of "primary assembly" in my solution that provides the majority of the shared functionality (like extension methods). We'll call this assembly "Framework" for the sake of discussion. Within the Framework assembly, I try to mimic the namespaces of the things for which I have extension methods. For example, if I'm extending System.Web.HttpApplication, I'd have a "Framework.Web" namespace. Classes like "String" and "Object," being in the "System" namespace, translate to the root "Framework" namespace in that assembly. Finally, naming goes along the lines you've specified in the question - the type name with "Extensions" as a suffix. This yields a class hierarchy like this: * Framework (namespace) + Framework.ObjectExtensions (class) + Framework.StringExtensions (class) + Framework.Web (namespace) - Framework.Web.HttpApplicationExtensions (class) The benefit is that, from a maintenance perspective, it's really easy later to go find the extension methods for a given type.
96,732
<p>I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible.</p> <p>This with is C# and .NET 3.5.</p> <p>The way I would like to do this is by storing the third party DLL as an embedded resource which I then place in the appropriate place during execution of the first DLL.</p> <p>The way I originally planned to do this is by writing code to put the third party DLL in the location specified by <code>System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()</code> minus the last <code>/nameOfMyAssembly.dll</code>. I can successfully save the third party <code>.DLL</code> in this location (which ends up being </p> <blockquote> <p>C:\Documents and Settings\myUserName\Local Settings\Application Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb_fe18c901 </p> </blockquote> <p>), but when I get to the part of my code requiring this DLL, it can't find it.</p> <p>Does anybody have any idea as to what I need to be doing differently?</p>
[ { "answer_id": 96791, "author": "Fostah", "author_id": 16524, "author_profile": "https://Stackoverflow.com/users/16524", "pm_score": 4, "selected": false, "text": "<p>There's a tool called IlMerge that can accomplish this: <a href=\"http://research.microsoft.com/~mbarnett/ILMerge.aspx\" ...
2008/09/18
[ "https://Stackoverflow.com/questions/96732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible. This with is C# and .NET 3.5. The way I would like to do this is by storing the third party DLL as an embedded resource which I then place in the appropriate place during execution of the first DLL. The way I originally planned to do this is by writing code to put the third party DLL in the location specified by `System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()` minus the last `/nameOfMyAssembly.dll`. I can successfully save the third party `.DLL` in this location (which ends up being > > C:\Documents and Settings\myUserName\Local Settings\Application > Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb\_fe18c901 > > > ), but when I get to the part of my code requiring this DLL, it can't find it. Does anybody have any idea as to what I need to be doing differently?
Once you've embedded the third-party assembly as a resource, add code to subscribe to the [`AppDomain.AssemblyResolve`](http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx) event of the current domain during application start-up. This event fires whenever the Fusion sub-system of the CLR fails to locate an assembly according to the probing (policies) in effect. In the event handler for `AppDomain.AssemblyResolve`, load the resource using [`Assembly.GetManifestResourceStream`](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx) and feed its content as a byte array into the corresponding [`Assembly.Load`](http://msdn.microsoft.com/en-us/library/h538bck7.aspx) overload. Below is how one such implementation could look like in C#: ``` AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { var resName = args.Name + ".dll"; var thisAssembly = Assembly.GetExecutingAssembly(); using (var input = thisAssembly.GetManifestResourceStream(resName)) { return input != null ? Assembly.Load(StreamToBytes(input)) : null; } }; ``` where `StreamToBytes` could be defined as: ``` static byte[] StreamToBytes(Stream input) { var capacity = input.CanSeek ? (int) input.Length : 0; using (var output = new MemoryStream(capacity)) { int readLength; var buffer = new byte[4096]; do { readLength = input.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, readLength); } while (readLength != 0); return output.ToArray(); } } ``` Finally, as a few have already mentioned, [ILMerge](http://research.microsoft.com/~mbarnett/ILMerge.aspx) may be another option to consider, albeit somewhat more involved.
96,759
<p>I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file.</p> <pre><code>function f_parse_csv($file, $longest, $delimiter) { $mdarray = array(); $file = fopen($file, "r"); while ($line = fgetcsv($file, $longest, $delimiter)) { array_push($mdarray, $line); } fclose($file); return $mdarray; } </code></pre> <p>I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of <code>Y-m-d H:i:s</code> and I would like to be able to sort with the most recent date being the first row.</p>
[ { "answer_id": 96812, "author": "Jan Hančič", "author_id": 185527, "author_profile": "https://Stackoverflow.com/users/185527", "pm_score": 0, "selected": false, "text": "<p>The \"Usort\" function is your answer.<br>\n<a href=\"http://php.net/usort\" rel=\"nofollow noreferrer\">http://php...
2008/09/18
[ "https://Stackoverflow.com/questions/96759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536217/" ]
I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file. ``` function f_parse_csv($file, $longest, $delimiter) { $mdarray = array(); $file = fopen($file, "r"); while ($line = fgetcsv($file, $longest, $delimiter)) { array_push($mdarray, $line); } fclose($file); return $mdarray; } ``` I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of `Y-m-d H:i:s` and I would like to be able to sort with the most recent date being the first row.
You can use [array\_multisort()](http://php.net/manual/en/function.array-multisort.php) Try something like this: ``` foreach ($mdarray as $key => $row) { // replace 0 with the field's index/key $dates[$key] = $row[0]; } array_multisort($dates, SORT_DESC, $mdarray); ``` For PHP >= 5.5.0 just extract the column to sort by. No need for the loop: ``` array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray); ```
96,826
<p>Pretty basic question, I'm trying to write a regex in Vim to match any phrase starting with <code>"abc "</code> directly followed by anything other than <code>"defg"</code>. </p> <p>I've used <code>"[^defg]"</code> to match any single character other than d, e, f or g.</p> <p>My first instinct was to try <code>/abc [^\(defg\)]</code> or <code>/abc [^\&lt;defg\&gt;]</code> but neither one of those works.</p>
[ { "answer_id": 96946, "author": "Lee H", "author_id": 18201, "author_profile": "https://Stackoverflow.com/users/18201", "pm_score": 1, "selected": false, "text": "<p>Here we go, this is a hairy one:</p>\n\n<pre><code>/\\%(\\%(.\\{-}\\)\\@&lt;=XXXXXX\\zs\\)*\n</code></pre>\n\n<p>(replace ...
2008/09/18
[ "https://Stackoverflow.com/questions/96826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5379/" ]
Pretty basic question, I'm trying to write a regex in Vim to match any phrase starting with `"abc "` directly followed by anything other than `"defg"`. I've used `"[^defg]"` to match any single character other than d, e, f or g. My first instinct was to try `/abc [^\(defg\)]` or `/abc [^\<defg\>]` but neither one of those works.
Here's the search string. ``` /abc \(defg\)\@! ``` The concept you're looking for is called a negative look-ahead assertion. Try this in vim for more info: ``` :help \@! ```
96,837
<p>This is a good candidate for the <a href="http://www.codinghorror.com/blog/archives/000818.html" rel="nofollow noreferrer">"Works on My Machine Certification Program"</a>.</p> <p>I have the following code for a LinkButton...</p> <pre><code>&lt;cc1:PopupDialog ID="pdFamilyPrompt" runat="server" CloseLink="false" Display="true"&gt; &lt;p&gt;Do you wish to upgrade?&lt;/p&gt; &lt;asp:HyperLink ID="hlYes" runat="server" Text="Yes" CssClass="button"&gt;&lt;/asp:HyperLink&gt; &lt;asp:LinkButton ID="lnkbtnNo" runat="server" Text="No" CssClass="button"&gt;&lt;/asp:LinkButton&gt; &lt;/cc1:PopupDialog&gt; </code></pre> <p>It uses a custom control that simply adds code before and after the content to format it as a popup dialog. The <strong>Yes</strong> button is a HyperLink because it executes javascript to hide the dialog and show a different one. The <strong>No</strong> button is a LinkButton because it needs to PostBack to process this value.</p> <p>I do not have an onClick event registered with the LinkButton because I simply check if IsPostBack is true. When executed locally, the PostBack works fine and all goes well. When published to our Development server, the <strong>No</strong> button does nothing when clicked on. I am using the same browser when testing locally versus on the development server. </p> <p>My initial thought is that perhaps a Validator is preventing the PostBack from firing. I do use a couple of Validators on another section of the page, but they are all assigned to a specific Validation Group which the <strong>No</strong> LinkButton is not assigned to. However the problem is why it would work locally on not on the development server.</p> <p>Any ideas?</p>
[ { "answer_id": 96881, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": true, "text": "<p>Check the html that is emitted on production and make sure that it has the __doPostback() and that there are no ...
2008/09/18
[ "https://Stackoverflow.com/questions/96837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4624/" ]
This is a good candidate for the ["Works on My Machine Certification Program"](http://www.codinghorror.com/blog/archives/000818.html). I have the following code for a LinkButton... ``` <cc1:PopupDialog ID="pdFamilyPrompt" runat="server" CloseLink="false" Display="true"> <p>Do you wish to upgrade?</p> <asp:HyperLink ID="hlYes" runat="server" Text="Yes" CssClass="button"></asp:HyperLink> <asp:LinkButton ID="lnkbtnNo" runat="server" Text="No" CssClass="button"></asp:LinkButton> </cc1:PopupDialog> ``` It uses a custom control that simply adds code before and after the content to format it as a popup dialog. The **Yes** button is a HyperLink because it executes javascript to hide the dialog and show a different one. The **No** button is a LinkButton because it needs to PostBack to process this value. I do not have an onClick event registered with the LinkButton because I simply check if IsPostBack is true. When executed locally, the PostBack works fine and all goes well. When published to our Development server, the **No** button does nothing when clicked on. I am using the same browser when testing locally versus on the development server. My initial thought is that perhaps a Validator is preventing the PostBack from firing. I do use a couple of Validators on another section of the page, but they are all assigned to a specific Validation Group which the **No** LinkButton is not assigned to. However the problem is why it would work locally on not on the development server. Any ideas?
Check the html that is emitted on production and make sure that it has the \_\_doPostback() and that there are no global methods watching click and canceling the event. Other than that if you think it could be related to validation you could try adding CausesValidation or whatever to false and see if that helps. Otherwise a "works on my machine" error is kind of hard to debug without being present and knowing the configurations of DEV vs PROD.
96,848
<p>Is there any way to use a constant as a hash key?</p> <p>For example:</p> <pre><code>use constant X =&gt; 1; my %x = (X =&gt; 'X'); </code></pre> <p>The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.</p>
[ { "answer_id": 96869, "author": "nohat", "author_id": 3101, "author_profile": "https://Stackoverflow.com/users/3101", "pm_score": 7, "selected": true, "text": "<p><code>use constant</code> actually makes constant subroutines.</p>\n\n<p>To do what you want, you need to explicitly call the...
2008/09/18
[ "https://Stackoverflow.com/questions/96848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4406/" ]
Is there any way to use a constant as a hash key? For example: ``` use constant X => 1; my %x = (X => 'X'); ``` The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.
`use constant` actually makes constant subroutines. To do what you want, you need to explicitly call the sub: ``` use constant X => 1; my %x = ( &X => 'X'); ``` or ``` use constant X => 1; my %x = ( X() => 'X'); ```
96,871
<p>I'd like to make status icons for a C# WinForms TreeList control. The statuses are combinations of other statuses (eg. a user node might be inactive or banned or inactive and banned), and the status icon is comprised of non-overlapping, smaller glyphs. </p> <p>I'd really like to avoid having to hand-generate all the possibly permutations of status icons if I can avoid it. </p> <p>Is it possible to create an image list (or just a bunch of bitmap resources or something) that I can use to generate the ImageList programmatically?</p> <p>I'm poking around the System.Drawing classes and nothing's jumping out at me. Also, I'm stuck with .Net 2.0.</p>
[ { "answer_id": 96907, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": true, "text": "<pre><code>Bitmap image1 = ...\nBitmap image2 = ...\n\nBitmap combined = new Bitmap(image1.Width, image1.Height);\nusing (G...
2008/09/18
[ "https://Stackoverflow.com/questions/96871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5062/" ]
I'd like to make status icons for a C# WinForms TreeList control. The statuses are combinations of other statuses (eg. a user node might be inactive or banned or inactive and banned), and the status icon is comprised of non-overlapping, smaller glyphs. I'd really like to avoid having to hand-generate all the possibly permutations of status icons if I can avoid it. Is it possible to create an image list (or just a bunch of bitmap resources or something) that I can use to generate the ImageList programmatically? I'm poking around the System.Drawing classes and nothing's jumping out at me. Also, I'm stuck with .Net 2.0.
``` Bitmap image1 = ... Bitmap image2 = ... Bitmap combined = new Bitmap(image1.Width, image1.Height); using (Graphics g = Graphics.FromImage(combined)) { g.DrawImage(image1, new Point(0, 0)); g.DrawImage(image2, new Point(0, 0); } imageList.Add(combined); ```
96,882
<p>I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image.</p> <p>I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately). </p> <p>I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap.</p>
[ { "answer_id": 97025, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 5, "selected": false, "text": "<p>Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many soluti...
2008/09/18
[ "https://Stackoverflow.com/questions/96882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16909/" ]
I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image. I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately). I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap.
After lots of research, I've come up with this answer, and I'm hereby putting it here as an answer for my own question, for reference: 1. Make sure that "Enable access for assistive devices" is checked in System Preferences>>Universal Access. It is required for the AppleScript to work. You may have to reboot after this change (it doesn't work otherwise on Mac OS X Server 10.4). 2. Create a R/W DMG. It must be larger than the result will be. In this example, the bash variable "size" contains the size in Kb and the contents of the folder in the "source" bash variable will be copied into the DMG: ``` hdiutil create -srcfolder "${source}" -volname "${title}" -fs HFS+ \ -fsargs "-c c=64,a=16,e=16" -format UDRW -size ${size}k pack.temp.dmg ``` 3. Mount the disk image, and store the device name (you might want to use sleep for a few seconds after this operation): ``` device=$(hdiutil attach -readwrite -noverify -noautoopen "pack.temp.dmg" | \ egrep '^/dev/' | sed 1q | awk '{print $1}') ``` 4. Store the background picture (in PNG format) in a folder called ".background" in the DMG, and store its name in the "backgroundPictureName" variable. 5. Use AppleScript to set the visual styles (name of .app must be in bash variable "applicationName", use variables for the other properties as needed): ``` echo ' tell application "Finder" tell disk "'${title}'" open set current view of container window to icon view set toolbar visible of container window to false set statusbar visible of container window to false set the bounds of container window to {400, 100, 885, 430} set theViewOptions to the icon view options of container window set arrangement of theViewOptions to not arranged set icon size of theViewOptions to 72 set background picture of theViewOptions to file ".background:'${backgroundPictureName}'" make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"} set position of item "'${applicationName}'" of container window to {100, 100} set position of item "Applications" of container window to {375, 100} update without registering applications delay 5 close end tell end tell ' | osascript ``` 6. Finialize the DMG by setting permissions properly, compressing and releasing it: ``` chmod -Rf go-w /Volumes/"${title}" sync sync hdiutil detach ${device} hdiutil convert "/pack.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "${finalDMGName}" rm -f /pack.temp.dmg ``` On Snow Leopard, the above applescript will not set the icon position correctly - it seems to be a Snow Leopard bug. One workaround is to simply call close/open after setting the icons, i.e.: ``` .. set position of item "'${applicationName}'" of container window to {100, 100} set position of item "Applications" of container window to {375, 100} close open ```
96,922
<p>The standard answer is that it's useful when you only need to write a few lines of code ...</p> <p>I have both languages integrated inside of Eclipse. Because Eclipse handles the compiling, interpreting, running etc. both "run" exactly the same.</p> <p>The Eclipse IDE for both is similar - instant "compilation", intellisense etc. Both allow the use of the Debug perspective.</p> <p>If I want to test a few lines of Java, I don't have to create a whole new Java project - I just use the <a href="http://www.eclipsezone.com/eclipse/forums/t61137.html" rel="noreferrer">Scrapbook</a> feature inside Eclipse which which allows me to <em>"execute Java expressions without having to create a new Java program. This is a neat way to quickly test an existing class or evaluate a code snippet"</em>. </p> <p>Jython allows the use of the Java libraries - but then so (by definition) does Java!</p> <p>So what other benefits does Jython offer?</p>
[ { "answer_id": 96934, "author": "Lucas S.", "author_id": 7363, "author_profile": "https://Stackoverflow.com/users/7363", "pm_score": 0, "selected": false, "text": "<p>Syntax sugar.</p>\n" }, { "answer_id": 96935, "author": "Ben Hoffstein", "author_id": 4482, "author_p...
2008/09/18
[ "https://Stackoverflow.com/questions/96922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9922/" ]
The standard answer is that it's useful when you only need to write a few lines of code ... I have both languages integrated inside of Eclipse. Because Eclipse handles the compiling, interpreting, running etc. both "run" exactly the same. The Eclipse IDE for both is similar - instant "compilation", intellisense etc. Both allow the use of the Debug perspective. If I want to test a few lines of Java, I don't have to create a whole new Java project - I just use the [Scrapbook](http://www.eclipsezone.com/eclipse/forums/t61137.html) feature inside Eclipse which which allows me to *"execute Java expressions without having to create a new Java program. This is a neat way to quickly test an existing class or evaluate a code snippet"*. Jython allows the use of the Java libraries - but then so (by definition) does Java! So what other benefits does Jython offer?
A quick example (from <http://coreygoldberg.blogspot.com/2008/09/python-vs-java-http-get-request.html>) : You have a back end in Java, and you need to perform HTTP GET resquests. Natively : ``` import java.net.*; import java.io.*; public class JGet { public static void main (String[] args) throws IOException { try { URL url = new URL("http://www.google.com"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (MalformedURLException e) {} catch (IOException e) {} } } ``` In Python : ``` import urllib print urllib.urlopen('http://www.google.com').read() ``` Jython allows you to use the java robustness and when needed, the Python clarity. What else ? As Georges would say...
96,923
<p>What's the name of the circled UI element here? And how do I access it using keyboard shortcuts? Sometimes it's nearly impossible to get the mouse to focus on it.</p> <pre><code>catch (ItemNotFoundException e) { } </code></pre>
[ { "answer_id": 96937, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 4, "selected": true, "text": "<p>I don't know the name, but the shortcuts are CTRL-period (.) and ALT-SHIFT-F10. Handy to know :)</p>\n" }, { ...
2008/09/18
[ "https://Stackoverflow.com/questions/96923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15050/" ]
What's the name of the circled UI element here? And how do I access it using keyboard shortcuts? Sometimes it's nearly impossible to get the mouse to focus on it. ``` catch (ItemNotFoundException e) { } ```
I don't know the name, but the shortcuts are CTRL-period (.) and ALT-SHIFT-F10. Handy to know :)
96,945
<p>I am using Oracle 9 and JDBC and would like to encyrpt a clob as it is inserted into the DB. Ideally I'd like to be able to just insert the plaintext and have it encrypted by a stored procedure:</p> <pre><code>String SQL = "INSERT INTO table (ID, VALUE) values (?, encrypt(?))"; PreparedStatement ps = connection.prepareStatement(SQL); ps.setInt(id); ps.setString(plaintext); ps.executeUpdate(); </code></pre> <p>The plaintext is not expected to exceed 4000 characters but encrypting makes text longer. Our current approach to encryption uses dbms_obfuscation_toolkit.DESEncrypt() but we only process varchars. Will the following work?</p> <pre><code>FUNCTION encrypt(p_clob IN CLOB) RETURN CLOB IS encrypted_string CLOB; v_string CLOB; BEGIN dbms_lob.createtemporary(encrypted_string, TRUE); v_string := p_clob; dbms_obfuscation_toolkit.DESEncrypt( input_string =&gt; v_string, key_string =&gt; key_string, encrypted_string =&gt; encrypted_string ); RETURN UTL_RAW.CAST_TO_RAW(encrypted_string); END; </code></pre> <p>I'm confused about the temporary clob; do I need to close it? Or am I totally off-track?</p> <p>Edit: The purpose of the obfuscation is to prevent trivial access to the data. My other purpose is to obfuscate clobs in the same way that we are already obfuscating the varchar columns. The oracle sample code does not deal with clobs which is where my specific problem lies; encrypting varchars (smaller than 2000 chars) is straightforward.</p>
[ { "answer_id": 97469, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 2, "selected": false, "text": "<p>There is an example in Oracle Documentation:</p>\n\n<p><a href=\"http://download.oracle.com/docs/cd/B10501_01/appdev.920/...
2008/09/18
[ "https://Stackoverflow.com/questions/96945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867/" ]
I am using Oracle 9 and JDBC and would like to encyrpt a clob as it is inserted into the DB. Ideally I'd like to be able to just insert the plaintext and have it encrypted by a stored procedure: ``` String SQL = "INSERT INTO table (ID, VALUE) values (?, encrypt(?))"; PreparedStatement ps = connection.prepareStatement(SQL); ps.setInt(id); ps.setString(plaintext); ps.executeUpdate(); ``` The plaintext is not expected to exceed 4000 characters but encrypting makes text longer. Our current approach to encryption uses dbms\_obfuscation\_toolkit.DESEncrypt() but we only process varchars. Will the following work? ``` FUNCTION encrypt(p_clob IN CLOB) RETURN CLOB IS encrypted_string CLOB; v_string CLOB; BEGIN dbms_lob.createtemporary(encrypted_string, TRUE); v_string := p_clob; dbms_obfuscation_toolkit.DESEncrypt( input_string => v_string, key_string => key_string, encrypted_string => encrypted_string ); RETURN UTL_RAW.CAST_TO_RAW(encrypted_string); END; ``` I'm confused about the temporary clob; do I need to close it? Or am I totally off-track? Edit: The purpose of the obfuscation is to prevent trivial access to the data. My other purpose is to obfuscate clobs in the same way that we are already obfuscating the varchar columns. The oracle sample code does not deal with clobs which is where my specific problem lies; encrypting varchars (smaller than 2000 chars) is straightforward.
I note you are on Oracle 9, but just for the record in Oracle 10g+ the dbms\_obfuscation\_toolkit was deprecated in favour of dbms\_crypto. [dbms\_crypto](http://68.142.116.68/docs/cd/B28359_01/appdev.111/b28419/d_crypto.htm#i1005082) does include CLOB support: ``` DBMS_CRYPTO.ENCRYPT( dst IN OUT NOCOPY BLOB, src IN CLOB CHARACTER SET ANY_CS, typ IN PLS_INTEGER, key IN RAW, iv IN RAW DEFAULT NULL); DBMS_CRYPT.DECRYPT( dst IN OUT NOCOPY CLOB CHARACTER SET ANY_CS, src IN BLOB, typ IN PLS_INTEGER, key IN RAW, iv IN RAW DEFAULT NULL); ```
96,952
<p>What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field? </p> <p>Field with value "00345ABC" would need to return "345ABC".</p>
[ { "answer_id": 96971, "author": "Chris Bartow", "author_id": 497, "author_profile": "https://Stackoverflow.com/users/497", "pm_score": 8, "selected": true, "text": "<p>You are looking for the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim\" rel=\"nor...
2008/09/18
[ "https://Stackoverflow.com/questions/96952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5446/" ]
What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field? Field with value "00345ABC" would need to return "345ABC".
You are looking for the [trim() function](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim). Alright, here is your example ``` SELECT TRIM(LEADING '0' FROM myfield) FROM table ```
97,013
<p>Does anyone know is there a way to open a project in Eclipse in read-only mode? If there is a lot of similar projects open it is easy to make changes to a wrong one.</p>
[ { "answer_id": 97047, "author": "Martin OConnor", "author_id": 18233, "author_profile": "https://Stackoverflow.com/users/18233", "pm_score": 2, "selected": false, "text": "<p>One sub-optimal solution is to make the project directory read-only in the file system in the underlying OS. I'm ...
2008/09/18
[ "https://Stackoverflow.com/questions/97013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
Does anyone know is there a way to open a project in Eclipse in read-only mode? If there is a lot of similar projects open it is easy to make changes to a wrong one.
Putting project in read-only mode is really useful, when you make another instance from the previous project. So you copy all files from old project, then make changes in the new instance. It's really simple to edit files from old project by mistake (they have the same names)! Serg if you use linux, I suggest to put all files in read only mode with chmod in terminal: ``` sudo chmod 444 -R /path/to/your/project ``` After this operation Eclipse will tell you that file you are trying to edit is in read-only mode. I think that's enough to make the previous project safe :)
97,050
<p>Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted?</p>
[ { "answer_id": 97076, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 3, "selected": false, "text": "<p>There will be barely any difference in speed between the 2, find will return an iterator, insert does the same and will...
2008/09/18
[ "https://Stackoverflow.com/questions/97050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16496/" ]
Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted?
The answer is you do neither. Instead you want to do something suggested by Item 24 of [Effective STL](https://rads.stackoverflow.com/amzn/click/com/0201749629) by [Scott Meyers](http://www.aristeia.com/): ``` typedef map<int, int> MapType; // Your map type may vary, just change the typedef MapType mymap; // Add elements to map here int k = 4; // assume we're searching for keys equal to 4 int v = 0; // assume we want the value 0 associated with the key of 4 MapType::iterator lb = mymap.lower_bound(k); if(lb != mymap.end() && !(mymap.key_comp()(k, lb->first))) { // key already exists // update lb->second if you care to } else { // the key does not exist in the map // add it to the map mymap.insert(lb, MapType::value_type(k, v)); // Use lb as a hint to insert, // so it can avoid another lookup } ```
97,081
<p>Someone told me about a C++ style difference in their team. I have my own viewpoint on the subject, but I would be interested by <em>pros</em> and <em>cons</em> coming from everyone.</p> <p>So, in case you have a class property you want to expose via two getters, one read/write, and the other, readonly (i.e. there is no set method). There are at least two ways of doing it:</p> <pre><code>class T ; class MethodA { public : const T &amp; get() const ; T &amp; get() ; // etc. } ; class MethodB { public : const T &amp; getAsConst() const ; T &amp; get() ; // etc. } ; </code></pre> <p>What would be the pros and the cons of each method?</p> <p>I am interested more by C++ technical/semantic reasons, but style reasons are welcome, too.</p> <p>Note that <code>MethodB</code> has one major technical drawback (hint: in generic code).</p>
[ { "answer_id": 97117, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "<p>While it appears your question only addresses one method, I'd be happy to give my input on style. Personally, for...
2008/09/18
[ "https://Stackoverflow.com/questions/97081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
Someone told me about a C++ style difference in their team. I have my own viewpoint on the subject, but I would be interested by *pros* and *cons* coming from everyone. So, in case you have a class property you want to expose via two getters, one read/write, and the other, readonly (i.e. there is no set method). There are at least two ways of doing it: ``` class T ; class MethodA { public : const T & get() const ; T & get() ; // etc. } ; class MethodB { public : const T & getAsConst() const ; T & get() ; // etc. } ; ``` What would be the pros and the cons of each method? I am interested more by C++ technical/semantic reasons, but style reasons are welcome, too. Note that `MethodB` has one major technical drawback (hint: in generic code).
Well, for one thing, getAsConst *must* be called when the 'this' pointer is const -- not when you want to receive a const object. So, alongside any other issues, it's subtly misnamed. (You can still call it when 'this' is non-const, but that's neither here nor there.) Ignoring that, getAsConst earns you nothing, and puts an undue burden on the developer using the interface. Instead of just calling "get" and knowing he's getting what he needs, now he has to ascertain whether or not he's currently using a const variable, and if the new object he's grabbing needs to be const. And later, if both objects become non-const due to some refactoring, he's got to switch out his call.
97,092
<p>What I am trying to achieve is a form that has a button on it that causes the Form to 'drop-down' and become larger, displaying more information. My current attempt is this:</p> <pre><code>private void btnExpand_Click(object sender, EventArgs e) { if (btnExpand.Text == "&gt;") { btnExpand.Text = "&lt;"; _expanded = true; this.MinimumSize = new Size(1, 300); this.MaximumSize = new Size(int.MaxValue, 300); } else { btnExpand.Text = "&gt;"; _expanded = false; this.MinimumSize = new Size(1, 104); this.MaximumSize = new Size(int.MaxValue, 104); } } </code></pre> <p>Which works great! Except for one small detail... Note that the width values are supposed to be able to go from 1 to int.MaxValue? Well, in practice, they go from this.Width to int.MaxValue, ie. you can make the form larger, but never smaller again. I'm at a loss for why this would occur. Anyone have any ideas?</p> <p>For the record: I've also tried a Form.Resize handler that set the Height of the form to the same value depending on whatever the boolean _expanded was set to, but I ended up with the same side effect.</p> <p>PS: I'm using .NET 3.5 in Visual Studio 2008. Other solutions are welcome, but this was my thoughts on how it "should" be done and how I attempted to do it.</p> <p>Edit: Seems the code works, as per the accepted answers response. If anyone else has troubles with this particular problem, check the AutoSize property of your form, it should be FALSE, not TRUE. (This is the default, but I'd switched it on as I was using the form and a label with autosize also on for displaying debugging info earlier)</p>
[ { "answer_id": 97689, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 2, "selected": true, "text": "<p>As per the docs, use 0 to denote no maximum or minimum size. Tho, I just tried it and it didn't like 0 at all. So I used i...
2008/09/18
[ "https://Stackoverflow.com/questions/97092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
What I am trying to achieve is a form that has a button on it that causes the Form to 'drop-down' and become larger, displaying more information. My current attempt is this: ``` private void btnExpand_Click(object sender, EventArgs e) { if (btnExpand.Text == ">") { btnExpand.Text = "<"; _expanded = true; this.MinimumSize = new Size(1, 300); this.MaximumSize = new Size(int.MaxValue, 300); } else { btnExpand.Text = ">"; _expanded = false; this.MinimumSize = new Size(1, 104); this.MaximumSize = new Size(int.MaxValue, 104); } } ``` Which works great! Except for one small detail... Note that the width values are supposed to be able to go from 1 to int.MaxValue? Well, in practice, they go from this.Width to int.MaxValue, ie. you can make the form larger, but never smaller again. I'm at a loss for why this would occur. Anyone have any ideas? For the record: I've also tried a Form.Resize handler that set the Height of the form to the same value depending on whatever the boolean \_expanded was set to, but I ended up with the same side effect. PS: I'm using .NET 3.5 in Visual Studio 2008. Other solutions are welcome, but this was my thoughts on how it "should" be done and how I attempted to do it. Edit: Seems the code works, as per the accepted answers response. If anyone else has troubles with this particular problem, check the AutoSize property of your form, it should be FALSE, not TRUE. (This is the default, but I'd switched it on as I was using the form and a label with autosize also on for displaying debugging info earlier)
As per the docs, use 0 to denote no maximum or minimum size. Tho, I just tried it and it didn't like 0 at all. So I used int.MaxValue like you did and it worked. What version of the the framework you using?
97,097
<p>What is the C# version of VB.net's InputBox?</p>
[ { "answer_id": 97119, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": -1, "selected": false, "text": "<p>There is no such thing: I recommend to write it for yourself and use it whenever you need.</p>\n" }, { "answer_i...
2008/09/18
[ "https://Stackoverflow.com/questions/97097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
What is the C# version of VB.net's InputBox?
Add a reference to `Microsoft.VisualBasic`, `InputBox` is in the `Microsoft.VisualBasic.Interaction` namespace: ``` using Microsoft.VisualBasic; string input = Interaction.InputBox("Prompt", "Title", "Default", x_coordinate, y_coordinate); ``` Only the first argument for `prompt` is mandatory
97,113
<p>I have the following string:</p> <pre><code>cn=abcd,cn=groups,dc=domain,dc=com </code></pre> <p>Can a regular expression be used here to extract the string after the first <code>cn=</code> and before the first <code>,</code>? In the example above the answer should be <code>abcd</code>. </p>
[ { "answer_id": 97125, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>Yeah, using perl/java syntax <code>cn=([^,]*),</code>. You'd then get the 1st group.</p>\n" }, { "answer_id": 9712...
2008/09/18
[ "https://Stackoverflow.com/questions/97113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17273/" ]
I have the following string: ``` cn=abcd,cn=groups,dc=domain,dc=com ``` Can a regular expression be used here to extract the string after the first `cn=` and before the first `,`? In the example above the answer should be `abcd`.
``` /cn=([^,]+),/ ``` most languages will extract the match as $1 or matches[1] If you can't for some reason wield subscripts, ``` $x =~ s/^cn=// $x =~ s/,.*$// ``` Thats a way to do it in 2 steps. If you were parsing it out of a log with sed ``` sed -n -r '/cn=/s/^cn=([^,]+),.*$/\1/p' < logfile > dumpfile ``` will get you what you want. ( Extra commands added to only print matching lines )
97,114
<p>In a recent question on stubbing, many answers suggested C# interfaces or delegates for implementing stubs, but <a href="https://stackoverflow.com/questions/43711/whats-a-good-way-to-overwrite-datetimenow-during-testing#43718">one answer</a> suggested using conditional compilation, retaining static binding in the production code. This answer was modded -2 at the time of reading, so at least 2 people really thought this was a <em>wrong</em> answer. Perhaps misuse of DEBUG was the reason, or perhaps use of fixed value instead of more extensive validation. But I can't help wondering:</p> <p>Is the use of conditional compilation an inappropriate technique for implementing unit test stubs? Sometimes? Always?</p> <p>Thanks.</p> <p><strong>Edit-add:</strong> I'd like to add an example as a though experiment:</p> <pre><code>class Foo { public Foo() { .. } private DateTime Now { get { #if UNITTEST_Foo return Stub_DateTime.Now; #else return DateTime.Now; #endif } } // .. rest of Foo members } </code></pre> <p>comparing to</p> <pre><code>interface IDateTimeStrategy { DateTime Now { get; } } class ProductionDateTimeStrategy : IDateTimeStrategy { public DateTime Now { get { return DateTime.Now; } } } class Foo { public Foo() : Foo(new ProductionDateTimeStrategy()) {} public Foo(IDateTimeStrategy s) { datetimeStrategy = s; .. } private IDateTime_Strategy datetimeStrategy; private DateTime Now { get { return datetimeStrategy.Now; } } } </code></pre> <p>Which allows the outgoing dependency on "DateTime.Now" to be stubbed through a C# interface. However, we've now added a dynamic dispatch call where static would suffice, the object is larger even in the production version, and we've added a new failure path for Foo's constructor (allocation can fail). </p> <p>Am I worrying about nothing here? Thanks for the feedback so far!</p>
[ { "answer_id": 97174, "author": "plyawn", "author_id": 5964, "author_profile": "https://Stackoverflow.com/users/5964", "pm_score": 2, "selected": false, "text": "<p>I think it lessens the clarity for people reviewing the code. You shouldn't have to remember that there's a conditional tag...
2008/09/18
[ "https://Stackoverflow.com/questions/97114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14153/" ]
In a recent question on stubbing, many answers suggested C# interfaces or delegates for implementing stubs, but [one answer](https://stackoverflow.com/questions/43711/whats-a-good-way-to-overwrite-datetimenow-during-testing#43718) suggested using conditional compilation, retaining static binding in the production code. This answer was modded -2 at the time of reading, so at least 2 people really thought this was a *wrong* answer. Perhaps misuse of DEBUG was the reason, or perhaps use of fixed value instead of more extensive validation. But I can't help wondering: Is the use of conditional compilation an inappropriate technique for implementing unit test stubs? Sometimes? Always? Thanks. **Edit-add:** I'd like to add an example as a though experiment: ``` class Foo { public Foo() { .. } private DateTime Now { get { #if UNITTEST_Foo return Stub_DateTime.Now; #else return DateTime.Now; #endif } } // .. rest of Foo members } ``` comparing to ``` interface IDateTimeStrategy { DateTime Now { get; } } class ProductionDateTimeStrategy : IDateTimeStrategy { public DateTime Now { get { return DateTime.Now; } } } class Foo { public Foo() : Foo(new ProductionDateTimeStrategy()) {} public Foo(IDateTimeStrategy s) { datetimeStrategy = s; .. } private IDateTime_Strategy datetimeStrategy; private DateTime Now { get { return datetimeStrategy.Now; } } } ``` Which allows the outgoing dependency on "DateTime.Now" to be stubbed through a C# interface. However, we've now added a dynamic dispatch call where static would suffice, the object is larger even in the production version, and we've added a new failure path for Foo's constructor (allocation can fail). Am I worrying about nothing here? Thanks for the feedback so far!
Try to keep production code separate from test code. Maintain different folder hierarchies.. different solutions/projects. **Unless**.. you're in the world of legacy C++ Code. Here anything goes.. if conditional blocks help you get some of the code testable and you see a benefit.. By all means do it. But try to not let it get messier than the initial state. Clearly comment and demarcate conditional blocks. Proceed with caution. It is a valid technique for getting legacy code under a test harness.
97,173
<p>I'm using freemarker, SiteMesh and Spring framework. For the pages I use ${requestContext.getMessage()} to get the message from message.properties. But for the decorators this doesn't work. How should I do to get the internationalization working for sitemesh?</p>
[ { "answer_id": 105142, "author": "mathd", "author_id": 16309, "author_profile": "https://Stackoverflow.com/users/16309", "pm_score": 2, "selected": false, "text": "<p>You have to use the <strong><em>fmt</em></strong> taglib.</p>\n\n<p>First, add the taglib for sitemesh and fmt on the fis...
2008/09/18
[ "https://Stackoverflow.com/questions/97173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8041/" ]
I'm using freemarker, SiteMesh and Spring framework. For the pages I use ${requestContext.getMessage()} to get the message from message.properties. But for the decorators this doesn't work. How should I do to get the internationalization working for sitemesh?
You have to use the ***fmt*** taglib. First, add the taglib for sitemesh and fmt on the fisrt line of the decorator. ``` <%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator"%> <%@ taglib prefix="page" uri="http://www.opensymphony.com/sitemesh/page"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%> <fmt:setBundle basename="messages" /> ``` In my example, the i18n file is messages.properties. Then you need to use the fmt tag to use the mesages. ``` <fmt:message key="key_of_message" /> ```
97,193
<p>Is there a way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself?</p> <p>For example, something along these lines</p> <pre><code>class A { public void DoSomething() { StaticClass.ExecuteMethod(); } } class B { public void DoSomething() { SomeOtherClass.ExecuteMethod(); } } public class SomeOtherClass { public static void ExecuteMethod() { // Returns an instance of A if called from class A // or an instance of B if called from class B. object caller = getCallingInstance(); } } </code></pre> <p>I can get the type using <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframes.aspx" rel="noreferrer">System.Diagnostics.StackTrace.GetFrames</a>, but is there a way to get a reference to the actual instance?</p> <p>I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason of this question is I was curious if it was doable; we are currently passing the instance in.</p> <pre><code>ExecuteMethod(instance) </code></pre> <p>And I just wondered if this was possible and still being able to access the instance.</p> <pre><code>ExecuteMethod() </code></pre> <hr> <p>@Steve Cooper: I hadn't considered extension methods. Some variation of that might work.</p>
[ { "answer_id": 97267, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 1, "selected": false, "text": "<p>Just have ExecuteMethod take an object. Then you have the instance no matter what.</p>\n" }, { "answer_id": 9...
2008/09/18
[ "https://Stackoverflow.com/questions/97193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4299/" ]
Is there a way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself? For example, something along these lines ``` class A { public void DoSomething() { StaticClass.ExecuteMethod(); } } class B { public void DoSomething() { SomeOtherClass.ExecuteMethod(); } } public class SomeOtherClass { public static void ExecuteMethod() { // Returns an instance of A if called from class A // or an instance of B if called from class B. object caller = getCallingInstance(); } } ``` I can get the type using [System.Diagnostics.StackTrace.GetFrames](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframes.aspx), but is there a way to get a reference to the actual instance? I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason of this question is I was curious if it was doable; we are currently passing the instance in. ``` ExecuteMethod(instance) ``` And I just wondered if this was possible and still being able to access the instance. ``` ExecuteMethod() ``` --- @Steve Cooper: I hadn't considered extension methods. Some variation of that might work.
I do not believe you can. Even the StackTrace and StackFrame classes just give you naming information, not access to instances. I'm not sure exactly why you'd want to do this, but know that even if you could do it it would likely be very slow. A better solution would be to push the instance to a thread local context before calling ExecuteMethod that you can retrieve within it or just pass the instance.
97,197
<p>The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world.</p> <p>Does anybody have a more detailed explanation of the problem?</p>
[ { "answer_id": 97223, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 5, "selected": false, "text": "<p>Suppose you have COMPANY and EMPLOYEE. COMPANY has many EMPLOYEES (i.e. EMPLOYEE has a field COMPANY_ID).</p>\n\n<p>I...
2008/09/18
[ "https://Stackoverflow.com/questions/97197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6120/" ]
The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world. Does anybody have a more detailed explanation of the problem?
Let's say you have a collection of `Car` objects (database rows), and each `Car` has a collection of `Wheel` objects (also rows). In other words, `Car` → `Wheel` is a 1-to-many relationship. Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following: ``` SELECT * FROM Cars; ``` And then **for each `Car`:** ``` SELECT * FROM Wheel WHERE CarId = ? ``` In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars. Alternatively, one could get all wheels and perform the lookups in memory: ``` SELECT * FROM Wheel; ``` This reduces the number of round-trips to the database from N+1 to 2. Most ORM tools give you several ways to prevent N+1 selects. Reference: *[Java Persistence with Hibernate](http://www.manning.com/bauer2/)*, chapter 13.
97,228
<p>Ok, here's the breakdown of my project: I have a web project with a "Scripts" subfolder. That folder contains a few javascript files and a copy of JSMin.exe along with a batch file that runs the JSMin.exe on a few of the files. I tried to set up a post build step of 'call "$(ProjectDir)Scripts\jsmin.bat"'. When I perform the build, the batch file is always "exited with code 1." This happens going through Visual Studio or through the msbuild command line. I can run the batch file manually from the Scripts folder and it seems to work as expected, so I'm not sure what the issue here is. The $(ProjectDir)Scripts\jsmin.bat call is in quotes because $(ProjectDir) could have spaces (and in fact does on my machine). I'm not sure what to do at this point. I've tried removing the contents of the batch file as the post build step but that doesn't seem to work either.</p> <p>Ideally I would like to solve this problem through the post or pre-build steps so that the build manager won't have to go through an extra step when deploying code.</p> <p>Thanks!</p>
[ { "answer_id": 97284, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": true, "text": "<p>If you have something in your custom build step that returns an error code, you can add:</p>\n\n<pre><code>exit 0\n</cod...
2008/09/18
[ "https://Stackoverflow.com/questions/97228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16149/" ]
Ok, here's the breakdown of my project: I have a web project with a "Scripts" subfolder. That folder contains a few javascript files and a copy of JSMin.exe along with a batch file that runs the JSMin.exe on a few of the files. I tried to set up a post build step of 'call "$(ProjectDir)Scripts\jsmin.bat"'. When I perform the build, the batch file is always "exited with code 1." This happens going through Visual Studio or through the msbuild command line. I can run the batch file manually from the Scripts folder and it seems to work as expected, so I'm not sure what the issue here is. The $(ProjectDir)Scripts\jsmin.bat call is in quotes because $(ProjectDir) could have spaces (and in fact does on my machine). I'm not sure what to do at this point. I've tried removing the contents of the batch file as the post build step but that doesn't seem to work either. Ideally I would like to solve this problem through the post or pre-build steps so that the build manager won't have to go through an extra step when deploying code. Thanks!
If you have something in your custom build step that returns an error code, you can add: ``` exit 0 ``` as the last line of your build step. This will stop the build from failing.
97,276
<p>If I've got a time_t value from <code>gettimeofday()</code> or compatible in a Unix environment (e.g., Linux, BSD), is there a compact algorithm available that would be able to tell me the corresponding week number within the month?</p> <p>Ideally the return value would work in similar to the way <code>%W</code> behaves in <code>strftime()</code> , except giving the week within the month rather than the week within the year.</p> <p>I think Java has a <code>W</code> formatting token that does something more or less like what I'm asking.</p> <hr> <p>[Everything below written after answers were posted by David Nehme, Branan, and Sparr.]</p> <p>I realized that to return this result in a similar way to <code>%W</code>, we want to count the number of Mondays that have occurred in the month so far. If that number is zero, then 0 should be returned.</p> <p>Thanks to David Nehme and Branan in particular for their solutions which started things on the right track. The bit of code returning [using Branan's variable names] <code>((ts-&gt;mday - 1) / 7)</code> tells the number of complete weeks that have occurred before the current day.</p> <p>However, if we're counting the number of Mondays that have occurred so far, then we want to count the number of integral weeks, including today, then consider if the fractional week left over also contains any Mondays.</p> <p>To figure out whether the fractional week left after taking out the whole weeks contains a Monday, we need to consider <code>ts-&gt;mday % 7</code> and compare it to the day of the week, <code>ts-&gt;wday</code>. This is easy to see if you write out the combinations, but if we insure the day is not Sunday (<code>wday &gt; 0</code>), then anytime <code>ts-&gt;wday &lt;= (ts-&gt;mday % 7)</code> we need to increment the count of Mondays by 1. This comes from considering the number of days since the start of the month, and whether, based on the current day of the week within the the first fractional week, the fractional week contains a Monday.</p> <p>So I would rewrite Branan's return statement as follows:</p> <p><code>return (ts-&gt;tm_mday / 7) + ((ts-&gt;tm_wday &gt; 0) &amp;&amp; (ts-&gt;tm_wday &lt;= (ts-&gt;tm_mday % 7)));</code></p>
[ { "answer_id": 97377, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 1, "selected": false, "text": "<p>Assuming your first week is week 1:</p>\n\n<pre><code>int getWeekOfMonth()\n{\n time_t my_time;\n struct tm *ts;\n\n m...
2008/09/18
[ "https://Stackoverflow.com/questions/97276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I've got a time\_t value from `gettimeofday()` or compatible in a Unix environment (e.g., Linux, BSD), is there a compact algorithm available that would be able to tell me the corresponding week number within the month? Ideally the return value would work in similar to the way `%W` behaves in `strftime()` , except giving the week within the month rather than the week within the year. I think Java has a `W` formatting token that does something more or less like what I'm asking. --- [Everything below written after answers were posted by David Nehme, Branan, and Sparr.] I realized that to return this result in a similar way to `%W`, we want to count the number of Mondays that have occurred in the month so far. If that number is zero, then 0 should be returned. Thanks to David Nehme and Branan in particular for their solutions which started things on the right track. The bit of code returning [using Branan's variable names] `((ts->mday - 1) / 7)` tells the number of complete weeks that have occurred before the current day. However, if we're counting the number of Mondays that have occurred so far, then we want to count the number of integral weeks, including today, then consider if the fractional week left over also contains any Mondays. To figure out whether the fractional week left after taking out the whole weeks contains a Monday, we need to consider `ts->mday % 7` and compare it to the day of the week, `ts->wday`. This is easy to see if you write out the combinations, but if we insure the day is not Sunday (`wday > 0`), then anytime `ts->wday <= (ts->mday % 7)` we need to increment the count of Mondays by 1. This comes from considering the number of days since the start of the month, and whether, based on the current day of the week within the the first fractional week, the fractional week contains a Monday. So I would rewrite Branan's return statement as follows: `return (ts->tm_mday / 7) + ((ts->tm_wday > 0) && (ts->tm_wday <= (ts->tm_mday % 7)));`
Assuming your first week is week 1: ``` int getWeekOfMonth() { time_t my_time; struct tm *ts; my_time = time(NULL); ts = localtime(&my_time); return ((ts->tm_mday -1) / 7) + 1; } ``` For 0-index, drop the `+1` in the return statement.
97,283
<p>For example if the user is currently running VS2008 then I want the value VS2008.</p>
[ { "answer_id": 97517, "author": "Ozgur Ozcitak", "author_id": 976, "author_profile": "https://Stackoverflow.com/users/976", "pm_score": 5, "selected": true, "text": "<p>I am assuming you want to get the name of the process owning the currently focused window. With some P/Invoke:</p>\n\n<...
2008/09/18
[ "https://Stackoverflow.com/questions/97283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
For example if the user is currently running VS2008 then I want the value VS2008.
I am assuming you want to get the name of the process owning the currently focused window. With some P/Invoke: ``` // The GetForegroundWindow function returns a handle to the foreground window // (the window with which the user is currently working). [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); // The GetWindowThreadProcessId function retrieves the identifier of the thread // that created the specified window and, optionally, the identifier of the // process that created the window. [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); // Returns the name of the process owning the foreground window. private string GetForegroundProcessName() { IntPtr hwnd = GetForegroundWindow(); // The foreground window can be NULL in certain circumstances, // such as when a window is losing activation. if (hwnd == null) return "Unknown"; uint pid; GetWindowThreadProcessId(hwnd, out pid); foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) { if (p.Id == pid) return p.ProcessName; } return "Unknown"; } ```
97,312
<p>How do I find out what directory my console app is running in with C#?</p>
[ { "answer_id": 97330, "author": "Jakub Kotrla", "author_id": 16943, "author_profile": "https://Stackoverflow.com/users/16943", "pm_score": 1, "selected": false, "text": "<p>On windows (not sure about Unix etc.) it is the first argument in commandline.</p>\n\n<p>In C/C++ firts item in arg...
2008/09/18
[ "https://Stackoverflow.com/questions/97312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
How do I find out what directory my console app is running in with C#?
To get the directory where the .exe file is: ``` AppDomain.CurrentDomain.BaseDirectory ``` To get the current directory: ``` Environment.CurrentDirectory ```
97,324
<p>I'm writing a WCF service for the first time. The service and all of its clients (at least for now) are written in C#. The service has to do a lot of input validation on the data it gets passed, so I need to have some way to indicate invalid data back to the client. I've been reading a lot about faults and exceptions, wrapping exceptions in faults, and a lot of conflicting articles that are just confusing me further. What is the proper way to handle this case? </p> <p>Should I avoid exceptions altogether and package a Results return message? Should I create a special Fault, or a special Exception, or just throw ArgumentExceptions like I would for a non-WCF validation function?</p> <p>The code I have right now (influenced by <a href="http://msdn.microsoft.com/en-us/library/ms733841.aspx" rel="noreferrer">MSDN</a>) is:</p> <pre><code>[DataContract] public class ValidationFault { [DataMember] public Dictionary&lt;string, string&gt; Errors { get; private set; } [DataMember] public bool Fatal { get; private set; } [DataMember] public Guid SeriesIdentifier { get; private set; } public ValidationFault(Guid id, string argument, string error, bool fatal) { SeriesIdentifier = id; Errors = new Dictionary&lt;string, string&gt; {{argument, error}}; Fatal = fatal; } public void AddError(string argument, string error, bool fatal) { Errors.Add(argument, error); Fatal |= fatal; } } </code></pre> <p>And on the method there's [FaultContract(typeof(ValidationFault))]. So is this the "right" way to approach this?</p>
[ { "answer_id": 97676, "author": "Brennan", "author_id": 10366, "author_profile": "https://Stackoverflow.com/users/10366", "pm_score": 3, "selected": true, "text": "<p>If you are doing validation on the client and should have valid values once they are passed into the method (the web serv...
2008/09/18
[ "https://Stackoverflow.com/questions/97324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17697/" ]
I'm writing a WCF service for the first time. The service and all of its clients (at least for now) are written in C#. The service has to do a lot of input validation on the data it gets passed, so I need to have some way to indicate invalid data back to the client. I've been reading a lot about faults and exceptions, wrapping exceptions in faults, and a lot of conflicting articles that are just confusing me further. What is the proper way to handle this case? Should I avoid exceptions altogether and package a Results return message? Should I create a special Fault, or a special Exception, or just throw ArgumentExceptions like I would for a non-WCF validation function? The code I have right now (influenced by [MSDN](http://msdn.microsoft.com/en-us/library/ms733841.aspx)) is: ``` [DataContract] public class ValidationFault { [DataMember] public Dictionary<string, string> Errors { get; private set; } [DataMember] public bool Fatal { get; private set; } [DataMember] public Guid SeriesIdentifier { get; private set; } public ValidationFault(Guid id, string argument, string error, bool fatal) { SeriesIdentifier = id; Errors = new Dictionary<string, string> {{argument, error}}; Fatal = fatal; } public void AddError(string argument, string error, bool fatal) { Errors.Add(argument, error); Fatal |= fatal; } } ``` And on the method there's [FaultContract(typeof(ValidationFault))]. So is this the "right" way to approach this?
If you are doing validation on the client and should have valid values once they are passed into the method (the web service call) then I would throw an exception. It could be an exception indicating that a parameters is invalid with the name of the parameter. (see: ArgumentException) But you may not want to rely on the client to properly validate the data and that leaves you with the assumption that data could be invalid coming into the web service. In that case it is not truly an exceptional case and should not be an exception. In that case you could return an enum or a Result object that has a Status property set to an enum (OK, Invalid, Incomplete) and a Message property set with specifics, like the name of the parameter. I would ensure that these sorts of errors are found and fixed during development. Your QA process should carefully test valid and invalid uses of the client and you do not want to relay these technical messages back to the client. What you want to do instead is update your validation system to prevent invalid data from getting to the service call. My assumption for any WCF service is that there will be more than one UI. One could be a web UI now, but later I may add another using WinForms, WinCE or even a native iPhone/Android mobile application that does not conform to what you expect from .NET clients.
97,329
<p>Suppose I have a collection (be it an array, generic List, or whatever is the <strong>fastest</strong> solution to this problem) of a certain class, let's call it <code>ClassFoo</code>:</p> <pre><code>class ClassFoo { public string word; public float score; //... etc ... } </code></pre> <p>Assume there's going to be like 50.000 items in the collection, all in memory. Now I want to obtain as fast as possible all the instances in the collection that obey a condition on its bar member, for example like this:</p> <pre><code>List&lt;ClassFoo&gt; result = new List&lt;ClassFoo&gt;(); foreach (ClassFoo cf in collection) { if (cf.word.StartsWith(query) || cf.word.EndsWith(query)) result.Add(cf); } </code></pre> <p>How do I get the results as fast as possible? Should I consider some advanced indexing techniques and datastructures?</p> <p>The application domain for this problem is an autocompleter, that gets a query and gives a collection of suggestions as a result. Assume that the condition doesn't get any more complex than this. Assume also that there's going to be a lot of searches.</p>
[ { "answer_id": 97347, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>var Answers = myList.Where(item => item.bar.StartsWith(query) || item.bar.EndsWith(query));</p>\n\n<p>that's th...
2008/09/18
[ "https://Stackoverflow.com/questions/97329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]
Suppose I have a collection (be it an array, generic List, or whatever is the **fastest** solution to this problem) of a certain class, let's call it `ClassFoo`: ``` class ClassFoo { public string word; public float score; //... etc ... } ``` Assume there's going to be like 50.000 items in the collection, all in memory. Now I want to obtain as fast as possible all the instances in the collection that obey a condition on its bar member, for example like this: ``` List<ClassFoo> result = new List<ClassFoo>(); foreach (ClassFoo cf in collection) { if (cf.word.StartsWith(query) || cf.word.EndsWith(query)) result.Add(cf); } ``` How do I get the results as fast as possible? Should I consider some advanced indexing techniques and datastructures? The application domain for this problem is an autocompleter, that gets a query and gives a collection of suggestions as a result. Assume that the condition doesn't get any more complex than this. Assume also that there's going to be a lot of searches.
With the constraint that the condition clause can be "anything", then you're limited to scanning the entire list and applying the condition. If there are limitations on the condition clause, then you can look at organizing the data to more efficiently handle the queries. For example, the code sample with the "byFirstLetter" dictionary doesn't help at all with an "endsWith" query. So, it really comes down to what queries you want to do against that data. In Databases, this problem is the burden of the "query optimizer". In a typical database, if you have a database with no indexes, obviously every query is going to be a table scan. As you add indexes to the table, the optimizer can use that data to make more sophisticated query plans to better get to the data. That's essentially the problem you're describing. Once you have a more concrete subset of the types of queries then you can make a better decision as to what structure is best. Also, you need to consider the amount of data. If you have a list of 10 elements each less than 100 byte, a scan of everything may well be the fastest thing you can do since you have such a small amount of data. Obviously that doesn't scale to a 1M elements, but even clever access techniques carry a cost in setup, maintenance (like index maintenance), and memory. **EDIT**, based on the comment If it's an auto completer, if the data is static, then sort it and use a binary search. You're really not going to get faster than that. If the data is dynamic, then store it in a balanced tree, and search that. That's effectively a binary search, and it lets you keep add the data randomly. Anything else is some specialization on these concepts.
97,338
<p>I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me?</p> <pre><code>gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) &gt;&gt;$(DEP) </code></pre>
[ { "answer_id": 97374, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 0, "selected": false, "text": "<p>If there is an argument to GCC to do this, I don't know what it is. We end up piping the dependency output through <a href...
2008/09/18
[ "https://Stackoverflow.com/questions/97338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me? ``` gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) >>$(DEP) ```
The answer is in the [GCC manual](http://gcc.gnu.org/onlinedocs/gcc-4.3.2/cpp/Invocation.html): use the `-MT` flag. > > `-MT target` > > > Change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as `.c`, and appends the platform's usual object suffix. The result is the target. > > > An `-MT` option will set the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to `-MT`, or use multiple `-MT` options. > > > For example, `-MT '$(objpfx)foo.o'` might give > > > > ``` > $(objpfx)foo.o: foo.c > > ``` > >
97,349
<p>We want to store our overridden build targets in an external file and include that targets file in the TFSBuild.proj. We have a core set steps that happens and would like to get those additional steps by simply adding the import line to the TFSBuild.proj created by the wizard. </p> <pre><code>&lt;Import Project="$(SolutionRoot)/libs/my.team.build/my.team.build.targets"/&gt; </code></pre> <p>We cannot have an import on any file in the <code>$(SolutionRoot)</code> because at the time the Import statement is validated, the source has not be fetched from the repository. It looks like TFS is pulling down the <code>TFSBuild.proj</code> first without any other files.</p> <p>Even if we add a conditional import, the version in source control will not be imported if present. The previous version, already present on disk will be imported. </p> <p>We can give up storing those build targets with our source, but it is the first dependency to move out of our source tree so we are reluctant to do it.</p> <p>Is there a way to either:</p> <ol> <li>Tell Team Build to pull down a few more files so those <code>Import</code> statements evaluate correctly?</li> <li>Override those Team Build targets like <code>AfterCompile</code> in a manner besides the <code>Import</code>?</li> <li>Ultimately run build targets in Team Build that are kept under the source it's trying to build?</li> </ol>
[ { "answer_id": 97486, "author": "Gregg", "author_id": 18266, "author_profile": "https://Stackoverflow.com/users/18266", "pm_score": 1, "selected": false, "text": "<p>If the targets should only be run when TFS is running the build and not on your local development machines, you can put yo...
2008/09/18
[ "https://Stackoverflow.com/questions/97349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18264/" ]
We want to store our overridden build targets in an external file and include that targets file in the TFSBuild.proj. We have a core set steps that happens and would like to get those additional steps by simply adding the import line to the TFSBuild.proj created by the wizard. ``` <Import Project="$(SolutionRoot)/libs/my.team.build/my.team.build.targets"/> ``` We cannot have an import on any file in the `$(SolutionRoot)` because at the time the Import statement is validated, the source has not be fetched from the repository. It looks like TFS is pulling down the `TFSBuild.proj` first without any other files. Even if we add a conditional import, the version in source control will not be imported if present. The previous version, already present on disk will be imported. We can give up storing those build targets with our source, but it is the first dependency to move out of our source tree so we are reluctant to do it. Is there a way to either: 1. Tell Team Build to pull down a few more files so those `Import` statements evaluate correctly? 2. Override those Team Build targets like `AfterCompile` in a manner besides the `Import`? 3. Ultimately run build targets in Team Build that are kept under the source it's trying to build?
The Team Build has a "bootstrap" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj. If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e. ``` <Import Project="myTeamBuild.targets"/> ``` If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path. Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this: ``` $/TeamProject/main/MySolution/TeamBuild ``` Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\Visual Studio 9.0\Common7\IDE\PrivateAssemblies) ``` <add key="ConfigurationFolderRecursionType" value="Full" /> ``` Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can. Good luck, Martin.
97,370
<p>I have a macro which refreshes all fields in a document (the equivalent of doing an <kbd>F9</kbd> on the fields). I'd like to fire this macro automatically when the user saves the document.</p> <p>Under options I can select "update fields when document is printed", but that's not what I want. In the VBA editor I only seem to find events for the <code>Document_Open()</code> event, not the <code>Document_Save()</code> event.</p> <p>Is it possible to get the macro to fire when the user saves the document?</p> <p>Please note:</p> <ol> <li>This is Word 97. I know it is possible in later versions of Word</li> <li>I don't want to replace the standard Save button on the toolbar with a button to run my custom macro. Replacing the button on the toolbar applies to all documents and I only want it to affect this one document.</li> </ol> <p>To understand why I need this, the document contains a "SaveDate" field and I'd like this field to update on the screen when the user clicks Save. So if you can suggest another way to achieve this, then that would be just as good.</p>
[ { "answer_id": 97486, "author": "Gregg", "author_id": 18266, "author_profile": "https://Stackoverflow.com/users/18266", "pm_score": 1, "selected": false, "text": "<p>If the targets should only be run when TFS is running the build and not on your local development machines, you can put yo...
2008/09/18
[ "https://Stackoverflow.com/questions/97370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
I have a macro which refreshes all fields in a document (the equivalent of doing an `F9` on the fields). I'd like to fire this macro automatically when the user saves the document. Under options I can select "update fields when document is printed", but that's not what I want. In the VBA editor I only seem to find events for the `Document_Open()` event, not the `Document_Save()` event. Is it possible to get the macro to fire when the user saves the document? Please note: 1. This is Word 97. I know it is possible in later versions of Word 2. I don't want to replace the standard Save button on the toolbar with a button to run my custom macro. Replacing the button on the toolbar applies to all documents and I only want it to affect this one document. To understand why I need this, the document contains a "SaveDate" field and I'd like this field to update on the screen when the user clicks Save. So if you can suggest another way to achieve this, then that would be just as good.
The Team Build has a "bootstrap" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj. If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e. ``` <Import Project="myTeamBuild.targets"/> ``` If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path. Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this: ``` $/TeamProject/main/MySolution/TeamBuild ``` Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\Visual Studio 9.0\Common7\IDE\PrivateAssemblies) ``` <add key="ConfigurationFolderRecursionType" value="Full" /> ``` Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can. Good luck, Martin.
97,371
<p>I need to copy the newest file in a directory to a new location. So far I've found resources on the <a href="http://www.ss64.com/nt/forfiles.html" rel="noreferrer">forfiles</a> command, a <a href="https://stackoverflow.com/q/51837">date-related question</a> here, and another <a href="https://stackoverflow.com/q/50902">related question</a>. I'm just having a bit of trouble putting the pieces together! How do I copy the newest file in that directory to a new place?</p>
[ { "answer_id": 97414, "author": "Robert Swisher", "author_id": 1852, "author_profile": "https://Stackoverflow.com/users/1852", "pm_score": 2, "selected": false, "text": "<p>I know you asked for Windows but thought I'd add this anyway,in Unix/Linux you could do:</p>\n\n<pre><code>cp `ls -...
2008/09/18
[ "https://Stackoverflow.com/questions/97371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5269/" ]
I need to copy the newest file in a directory to a new location. So far I've found resources on the [forfiles](http://www.ss64.com/nt/forfiles.html) command, a [date-related question](https://stackoverflow.com/q/51837) here, and another [related question](https://stackoverflow.com/q/50902). I'm just having a bit of trouble putting the pieces together! How do I copy the newest file in that directory to a new place?
Windows shell, one liner: ``` FOR /F "delims=" %%I IN ('DIR *.* /A-D /B /O:-D') DO COPY "%%I" <<NewDir>> & EXIT ```
97,391
<p>I have the following enum declared:</p> <pre><code> public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' } </code></pre> <p>How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ?</p> <p>Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" so it doesn't cut the mustard.</p>
[ { "answer_id": 97395, "author": "Andy", "author_id": 13505, "author_profile": "https://Stackoverflow.com/users/13505", "pm_score": 1, "selected": false, "text": "<p>I believe Enum.GetValues() is what you're looking for.</p>\n" }, { "answer_id": 97397, "author": "J D OConal", ...
2008/09/18
[ "https://Stackoverflow.com/questions/97391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have the following enum declared: ``` public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' } ``` How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ? Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" so it doesn't cut the mustard.
Marking this as not correct, but I can't delete it. Try this: ``` string value = (string)TransactionTypeCode.Shipment; ```
97,402
<p>I've been trying to install PDT in Eclipse 3.4 for a few hours now and I'm not having any success.</p> <p>I have a previous installation of the Eclipse for Java EE developers (my main deal) distro and I just want to add the PDT to my install so I can also work on some of my websites in Eclipse. </p> <p>I've done my best to follow <a href="http://wiki.eclipse.org/PDT/Installation" rel="nofollow noreferrer">the instructions</a> at the PDT Wiki and I'm just not having any success. The specific message that it barks at me when I attempt to select the <strong>PDT Features</strong> option in the PDT Update Site section of the available software dialog is thus: </p> <pre><code>Cannot complete the request. See the details. Cannot find a solution satisfying the following requirements Match[requiredCapability: org.eclipse.equinox.p2.iu/org.eclipse.wst.web_ui.feature.feature.group/ [3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF, 3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF]]. </code></pre> <p>What is the solution?</p>
[ { "answer_id": 198709, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": 1, "selected": false, "text": "<p>If you have a list of all the plugins that you already have it may be faster and easier to go to <a href=\"http:/...
2008/09/18
[ "https://Stackoverflow.com/questions/97402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I've been trying to install PDT in Eclipse 3.4 for a few hours now and I'm not having any success. I have a previous installation of the Eclipse for Java EE developers (my main deal) distro and I just want to add the PDT to my install so I can also work on some of my websites in Eclipse. I've done my best to follow [the instructions](http://wiki.eclipse.org/PDT/Installation) at the PDT Wiki and I'm just not having any success. The specific message that it barks at me when I attempt to select the **PDT Features** option in the PDT Update Site section of the available software dialog is thus: ``` Cannot complete the request. See the details. Cannot find a solution satisfying the following requirements Match[requiredCapability: org.eclipse.equinox.p2.iu/org.eclipse.wst.web_ui.feature.feature.group/ [3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF, 3.0.1.v200807220139-7R0ELZE8Ks-y8HYiQrw5ftEC3UBF]]. ``` What is the solution?
If you have a list of all the plugins that you already have it may be faster and easier to go to [YOXOS](http://www.yoxos.com/ondemand/) and download a new copy of eclipse with all the plugins already loaded. just remember to change your workspace if you do this.
97,435
<p>Suppose you have the following string:</p> <pre><code>white sand, tall waves, warm sun </code></pre> <p>It's easy to write a regular expression that will match the delimiters, which the Java String.split() method can use to give you an array containing the tokens "white sand", "tall waves" and "warm sun":</p> <pre><code>\s*,\s* </code></pre> <p>Now say you have this string:</p> <pre><code>white sand and tall waves and warm sun </code></pre> <p>Again, the regex to split the tokens is easy (ensuring you don't get the "and" inside the word "sand"):</p> <pre><code>\s+and\s+ </code></pre> <p>Now, consider this string:</p> <pre><code>white sand, tall waves and warm sun </code></pre> <p>Can a regex be written that will match the delimiters correctly, allowing you to split the string into the same tokens as in the previous two cases? Alternatively, can a regex be written that will match the tokens themselves and omit the delimiters? (Any amount of white space on either side of a comma or the word "and" should be considered part of the delimiter.)</p> <p>Edit: As has been pointed out in the comments, the correct answer should robustly handle delimiters at the beginning or end of the input string. The <em>ideal</em> answer should be able to take a string like ",white sand, tall waves and warm sun and " and provide these exact three tokens:</p> <pre><code>[ "white sand", "tall waves", "warm sun" ] </code></pre> <p>...without <del>extra empty tokens or</del> extra white space at the start or end of any token.</p> <p>Edit: It's been pointed out that extra empty tokens are unavoidable with String.split(), so that's been removed as a criterion for the "perfect" regex.</p> <hr> <p>Thanks everyone for your responses! I've tried to make sure I upvoted everyone who contributed a workable regex that wasn't essentially a duplicate. Dan's answer was the most robust (it even handles ",white sand, tall waves,and warm sun and " reasonably, with that odd comma placement after the word "waves"), so I've marked his as the accepted answer. The regex provided by nsayer was a close second.</p>
[ { "answer_id": 97457, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 2, "selected": false, "text": "<p>This should catch both 'and' or ','</p>\n\n<pre><code>(?:\\sand|,)\\s\n</code></pre>\n" }, { "answer_id": 97458, ...
2008/09/18
[ "https://Stackoverflow.com/questions/97435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4287/" ]
Suppose you have the following string: ``` white sand, tall waves, warm sun ``` It's easy to write a regular expression that will match the delimiters, which the Java String.split() method can use to give you an array containing the tokens "white sand", "tall waves" and "warm sun": ``` \s*,\s* ``` Now say you have this string: ``` white sand and tall waves and warm sun ``` Again, the regex to split the tokens is easy (ensuring you don't get the "and" inside the word "sand"): ``` \s+and\s+ ``` Now, consider this string: ``` white sand, tall waves and warm sun ``` Can a regex be written that will match the delimiters correctly, allowing you to split the string into the same tokens as in the previous two cases? Alternatively, can a regex be written that will match the tokens themselves and omit the delimiters? (Any amount of white space on either side of a comma or the word "and" should be considered part of the delimiter.) Edit: As has been pointed out in the comments, the correct answer should robustly handle delimiters at the beginning or end of the input string. The *ideal* answer should be able to take a string like ",white sand, tall waves and warm sun and " and provide these exact three tokens: ``` [ "white sand", "tall waves", "warm sun" ] ``` ...without ~~extra empty tokens or~~ extra white space at the start or end of any token. Edit: It's been pointed out that extra empty tokens are unavoidable with String.split(), so that's been removed as a criterion for the "perfect" regex. --- Thanks everyone for your responses! I've tried to make sure I upvoted everyone who contributed a workable regex that wasn't essentially a duplicate. Dan's answer was the most robust (it even handles ",white sand, tall waves,and warm sun and " reasonably, with that odd comma placement after the word "waves"), so I've marked his as the accepted answer. The regex provided by nsayer was a close second.
This should be pretty resilient, and handle stuff like delimiters at the end of the string ("foo and bar and ", for example) ``` \s*(?:\band\b|,)\s* ```
97,447
<p>If I am writing a library and I have a function that needs to return a sequence of values, I could do something like:</p> <pre><code>std::vector&lt;int&gt; get_sequence(); </code></pre> <p>However, this requires the library user to use the std::vector&lt;> container rather than allowing them to use whatever container they want to use. In addition, it can add an extra copy of the returned array (depending on whether the compiler could optimize this or not) that might have a negative impact on performance.</p> <p>You could theoretically enable the use of arbitrary containers (and avoid the unnecessary extra copying) by making a templated function that takes a start and an end iter:</p> <pre><code>template&lt;class T_iter&gt; void get_sequence(T_iter begin, T_iter end); </code></pre> <p>The function would then store the sequence values in the range given by the iterators. But the problem with this is that it requires you to know the size of the sequence so you have enough elements between <code>begin</code> and <code>end</code> to store all of the values in the sequence.</p> <p>I thought about an interface such as:</p> <pre><code>template&lt;T_insertIter&gt; get_sequence(T_insertIter inserter); </code></pre> <p>which requires that the T_insertIter be an insert iterator (e.g. created with <code>std::back_inserter(my_vector)</code>), but this seems way too easy to misuse since the compiler would happily accept a non-insert iterator but would behave incorrectly at run-time.</p> <p>So is there a best practice for designing generic interfaces that return sequences of arbitrary length?</p>
[ { "answer_id": 97519, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 0, "selected": false, "text": "<p><code>std::list&lt;int&gt;</code> is slightly nicer, IMO. Note that this would not require an extra copy of the d...
2008/09/18
[ "https://Stackoverflow.com/questions/97447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78437/" ]
If I am writing a library and I have a function that needs to return a sequence of values, I could do something like: ``` std::vector<int> get_sequence(); ``` However, this requires the library user to use the std::vector<> container rather than allowing them to use whatever container they want to use. In addition, it can add an extra copy of the returned array (depending on whether the compiler could optimize this or not) that might have a negative impact on performance. You could theoretically enable the use of arbitrary containers (and avoid the unnecessary extra copying) by making a templated function that takes a start and an end iter: ``` template<class T_iter> void get_sequence(T_iter begin, T_iter end); ``` The function would then store the sequence values in the range given by the iterators. But the problem with this is that it requires you to know the size of the sequence so you have enough elements between `begin` and `end` to store all of the values in the sequence. I thought about an interface such as: ``` template<T_insertIter> get_sequence(T_insertIter inserter); ``` which requires that the T\_insertIter be an insert iterator (e.g. created with `std::back_inserter(my_vector)`), but this seems way too easy to misuse since the compiler would happily accept a non-insert iterator but would behave incorrectly at run-time. So is there a best practice for designing generic interfaces that return sequences of arbitrary length?
Have get\_sequence return a (custom) `forward_iterator` class that generates the sequence on-demand. (It could also be a more advanced iterator type like `bidirectional_iterator` if that's practical for your sequence.) Then the user can copy the sequence into whatever container type they want. Or, they can just loop directly on your iterator and skip the container entirely. You will need some sort of end iterator. Without knowing exactly how you're generating the sequence, it's hard to say exactly how you should implement that. One way would be for your iterator class to have a static member function that returned an end iterator, like: ``` static const my_itr& end() { static const my_itr e(...); return e; }; ``` where `...` represents whatever parameters you need to create the end iterator (which might use a private constructor). Then your loop would look like: ``` for (my_itr i = get_sequence(); i != my_itr::end(); ++i) { ... } ``` Here's a trivial example of a forward iterator class that generates a sequence of consecutive integers. Obviously, this could easily be turned into a bidirectional or random access iterator, but I wanted to keep the example small. ``` #include <iterator> class integer_sequence_itr : public std::iterator<std::forward_iterator_tag, int> { private: int i; public: explicit integer_sequence_itr(int start) : i(start) {}; const int& operator*() const { return i; }; const int* operator->() const { return &i; }; integer_sequence_itr& operator++() { ++i; return *this; }; integer_sequence_itr operator++(int) { integer_sequence_itr copy(*this); ++i; return copy; }; inline bool operator==(const integer_sequence_itr& rhs) const { return i == rhs.i; }; inline bool operator!=(const integer_sequence_itr& rhs) const { return i != rhs.i; }; }; // end integer_sequence_itr //Example: Print the integers from 1 to 10. #include <iostream> int main() { const integer_sequence_itr stop(11); for (integer_sequence_itr i(1); i != stop; ++i) std::cout << *i << std::endl; return 0; } // end main ```
97,459
<p>When a C# WinForms textbox receives focus, I want it to behave like your browser's address bar.</p> <p>To see what I mean, click in your web browser's address bar. You'll notice the following behavior: </p> <ol> <li>Clicking in the textbox should select all the text if the textbox wasn't previously focused.</li> <li>Mouse down and drag in the textbox should select only the text I've highlighted with the mouse.</li> <li>If the textbox is already focused, clicking does not select all text.</li> <li>Focusing the textbox programmatically or via keyboard tabbing should select all text.</li> </ol> <p>I want to do exactly this in WinForms.</p> <p><strong>FASTEST GUN ALERT: please read the following before answering!</strong> Thanks guys. :-)</p> <blockquote> <p><strong>Calling .SelectAll() during the .Enter or .GotFocus events won't work</strong> because if the user clicked the textbox, the caret will be placed where he clicked, thus deselecting all text.</p> <p><strong>Calling .SelectAll() during the .Click event won't work</strong> because the user won't be able to select any text with the mouse; the .SelectAll() call will keep overwriting the user's text selection.</p> <p><strong>Calling BeginInvoke((Action)textbox.SelectAll) on focus/enter event enter doesn't work</strong> because it breaks rule #2 above, it will keep overriding the user's selection on focus.</p> </blockquote>
[ { "answer_id": 97499, "author": "Jakub Kotrla", "author_id": 16943, "author_profile": "https://Stackoverflow.com/users/16943", "pm_score": 2, "selected": false, "text": "<p>Click event of textbox? Or even MouseCaptureChanged event works for me. - OK. doesn't work.</p>\n\n<p>So you have t...
2008/09/18
[ "https://Stackoverflow.com/questions/97459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ]
When a C# WinForms textbox receives focus, I want it to behave like your browser's address bar. To see what I mean, click in your web browser's address bar. You'll notice the following behavior: 1. Clicking in the textbox should select all the text if the textbox wasn't previously focused. 2. Mouse down and drag in the textbox should select only the text I've highlighted with the mouse. 3. If the textbox is already focused, clicking does not select all text. 4. Focusing the textbox programmatically or via keyboard tabbing should select all text. I want to do exactly this in WinForms. **FASTEST GUN ALERT: please read the following before answering!** Thanks guys. :-) > > **Calling .SelectAll() during > the .Enter or .GotFocus events won't > work** because if the user clicked the > textbox, the caret will be placed > where he clicked, thus deselecting all > text. > > > **Calling .SelectAll() during the .Click event won't work** because the user won't be able to select any text with the mouse; the .SelectAll() call will keep overwriting the user's text selection. > > > **Calling BeginInvoke((Action)textbox.SelectAll) on focus/enter event enter doesn't work** because it breaks rule #2 above, it will keep overriding the user's selection on focus. > > >
First of all, thanks for answers! 9 total answers. Thank you. Bad news: all of the answers had some quirks or didn't work quite right (or at all). I've added a comment to each of your posts. Good news: I've found a way to make it work. This solution is pretty straightforward and seems to work in all the scenarios (mousing down, selecting text, tabbing focus, etc.) ``` bool alreadyFocused; ... textBox1.GotFocus += textBox1_GotFocus; textBox1.MouseUp += textBox1_MouseUp; textBox1.Leave += textBox1_Leave; ... void textBox1_Leave(object sender, EventArgs e) { alreadyFocused = false; } void textBox1_GotFocus(object sender, EventArgs e) { // Select all text only if the mouse isn't down. // This makes tabbing to the textbox give focus. if (MouseButtons == MouseButtons.None) { this.textBox1.SelectAll(); alreadyFocused = true; } } void textBox1_MouseUp(object sender, MouseEventArgs e) { // Web browsers like Google Chrome select the text on mouse up. // They only do it if the textbox isn't already focused, // and if the user hasn't selected all text. if (!alreadyFocused && this.textBox1.SelectionLength == 0) { alreadyFocused = true; this.textBox1.SelectAll(); } } ``` As far as I can tell, this causes a textbox to behave exactly like a web browser's address bar. Hopefully this helps the next guy who tries to solve this deceptively simple problem. Thanks again, guys, for all your answers that helped lead me towards the correct path.
97,465
<p>Has anyone figured out how to use Crystal Reports with Linq to SQL?</p>
[ { "answer_id": 99193, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 1, "selected": false, "text": "<p>Altough I haven't tried it myself it seems to be possible by using a combination of DataContext.LoadOptions to make...
2008/09/18
[ "https://Stackoverflow.com/questions/97465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11063/" ]
Has anyone figured out how to use Crystal Reports with Linq to SQL?
You can convert your LINQ result set to a `List`, you need not strictly use a `DataSet` as the reports `SetDataSource`, you can supply a Crystal Reports data with an `IEnumerable`. Since `List` inherits from `IEnumerable` you can set your reports' Data Source to a List, you just have to call the `.ToList()` method on your LINQ result set. Basically: ``` CrystalReport1 cr1 = new CrystalReport1(); var results = (from obj in context.tSamples where obj.ID == 112 select new { obj.Name, obj.Model, obj.Producer }).ToList(); cr1.SetDataSource(results); crystalReportsViewer1.ReportSource = cr1; ```
97,468
<p><a href="http://github.com/rails/ssl_requirement/tree/master/lib/ssl_requirement.rb" rel="nofollow noreferrer">Take a look at the ssl_requirement plugin.</a></p> <p>Shouldn't it check to see if you're in production mode? We're seeing a redirect to https in development mode, which seems odd. Or is that the normal behavior for the plugin? I thought it behaved differently in the past.</p>
[ { "answer_id": 98697, "author": "Nathan de Vries", "author_id": 11109, "author_profile": "https://Stackoverflow.com/users/11109", "pm_score": 4, "selected": true, "text": "<p>I guess they believe that you should probably be using HTTPS (perhaps with a self-signed certificate) in developm...
2008/09/18
[ "https://Stackoverflow.com/questions/97468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17076/" ]
[Take a look at the ssl\_requirement plugin.](http://github.com/rails/ssl_requirement/tree/master/lib/ssl_requirement.rb) Shouldn't it check to see if you're in production mode? We're seeing a redirect to https in development mode, which seems odd. Or is that the normal behavior for the plugin? I thought it behaved differently in the past.
I guess they believe that you should probably be using HTTPS (perhaps with a self-signed certificate) in development mode. If that's not the desired behaviour, there's nothing stopping you from special casing SSL behaviour in the development environment yourself: ``` class YourController < ApplicationController ssl_required :update unless Rails.env.development? end ```
97,474
<p>I need to get the value of the 'test' attribute in the xsl:when tag, and the 'name' attribute in the xsl:call-template tag. This xpath gets me pretty close: </p> <pre><code>..../xsl:template/xsl:choose/xsl:when </code></pre> <p>But that just returns the 'when' elements, not the exact attribute values I need.</p> <p>Here is a snippet of my XML:</p> <pre><code>&lt;xsl:template match="field"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="@name='First Name'"&gt; &lt;xsl:call-template name="handleColumn_1" /&gt; &lt;/xsl:when&gt; &lt;/xsl:choose&gt; </code></pre>
[ { "answer_id": 97500, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 2, "selected": false, "text": "<p>do you want <code>.../xsl:template/xsl:choose/xsl:when/@test</code></p>\n\n<p>If you want to actually get the value '...
2008/09/18
[ "https://Stackoverflow.com/questions/97474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10876/" ]
I need to get the value of the 'test' attribute in the xsl:when tag, and the 'name' attribute in the xsl:call-template tag. This xpath gets me pretty close: ``` ..../xsl:template/xsl:choose/xsl:when ``` But that just returns the 'when' elements, not the exact attribute values I need. Here is a snippet of my XML: ``` <xsl:template match="field"> <xsl:choose> <xsl:when test="@name='First Name'"> <xsl:call-template name="handleColumn_1" /> </xsl:when> </xsl:choose> ```
Steve Cooper answered the first part. For the second part, you can use: ``` .../xsl:template/xsl:choose/xsl:when[@test="@name='First Name'"]/xsl:call-template/@name ``` Which will match specifically the xsl:when in your above snippet. If you want it to match generally, then you can use: ``` .../xsl:template/xsl:choose/xsl:when/xsl:call-template/@name ```
97,480
<p>I have a Progress database that I'm performing an ETL from. One of the tables that I'm reading from does not have a unique key on it, so I need to access the ROWID to be able to uniquely identify the row. What is the syntax for accessing the ROWID in Progress?</p> <p>I understand there are problems with using ROWID for row identification, but it's all I have right now.</p>
[ { "answer_id": 97579, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": -1, "selected": false, "text": "<p>A quick google search turns up this: \n<a href=\"http://bytes.com/forum/thread174440.html\" rel=\"nofollow noreferrer...
2008/09/18
[ "https://Stackoverflow.com/questions/97480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8739/" ]
I have a Progress database that I'm performing an ETL from. One of the tables that I'm reading from does not have a unique key on it, so I need to access the ROWID to be able to uniquely identify the row. What is the syntax for accessing the ROWID in Progress? I understand there are problems with using ROWID for row identification, but it's all I have right now.
A quick caveat for my answer - it's nearly 10 years since I worked with [Progress](http://www.progress.com/) so my knowledge is probably more than a little out of date. Checking the [Progress Language Reference](http://www.psdn.com/library/servlet/KbServlet/download/1078-102-885/langref.pdf) [PDF] seems to show the two functions I remember are still there: `ROWID` and `RECID`. The `ROWID` function is newer and is preferred. In Progress 4GL you'd use it something like this: ``` FIND customer WHERE cust-num = 123. crowid = ROWID(customer). ``` or: ``` FIND customer WHERE ROWID(customer) = crowid EXCLUSIVE-LOCK. ``` Checking the [Progress SQL Reference](http://www.psdn.com/library/servlet/KbServlet/download/1223-102-1092/s92.pdf) [PDF] shows `ROWID` is also available in SQL as a Progress extension. You'd use it like so: ``` SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123 ``` **Edit:** Edited following Stefan's feedback.
97,505
<p>Working on a somewhat complex page for configuring customers at work. The setup is that there's a main page, which contains various "panels" for various groups of settings. </p> <p>In one case, there's an email address field on the main table and an "export" configuration that controls how emails are sent out. I created a main panel that selects the company, and binds to a FormView. The FormView contains a Web User Control that handles the display/configuration of the export details.</p> <p>The Web User Control Contains a property to define which Config it should be handling, and it gets the value from the FormView using Bind().</p> <p>Basically the control is used like this:</p> <pre><code>&lt;syn:ExportInfo ID="eiConfigDetails" ExportInfoID='&lt;%# Bind("ExportInfoID" ) %&gt;' runat="server" /&gt; </code></pre> <p>The property being bound is declared like this in CodeBehind:</p> <pre><code>public int ExportInfoID { get { return Convert.ToInt32(hfID.Value); } set { try { hfID.Value = value.ToString(); } catch(Exception) { hfID.Value="-1"; } } } </code></pre> <p>Whenever the <code>ExportInfoID</code> is null I get a null reference exception, but the kicker is that it happens BEFORE it actually tries to set the property (or it would be caught in this version.)</p> <p>Anyone know what's going on or, more importantly, how to fix it...?</p>
[ { "answer_id": 97579, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": -1, "selected": false, "text": "<p>A quick google search turns up this: \n<a href=\"http://bytes.com/forum/thread174440.html\" rel=\"nofollow noreferrer...
2008/09/18
[ "https://Stackoverflow.com/questions/97505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ]
Working on a somewhat complex page for configuring customers at work. The setup is that there's a main page, which contains various "panels" for various groups of settings. In one case, there's an email address field on the main table and an "export" configuration that controls how emails are sent out. I created a main panel that selects the company, and binds to a FormView. The FormView contains a Web User Control that handles the display/configuration of the export details. The Web User Control Contains a property to define which Config it should be handling, and it gets the value from the FormView using Bind(). Basically the control is used like this: ``` <syn:ExportInfo ID="eiConfigDetails" ExportInfoID='<%# Bind("ExportInfoID" ) %>' runat="server" /> ``` The property being bound is declared like this in CodeBehind: ``` public int ExportInfoID { get { return Convert.ToInt32(hfID.Value); } set { try { hfID.Value = value.ToString(); } catch(Exception) { hfID.Value="-1"; } } } ``` Whenever the `ExportInfoID` is null I get a null reference exception, but the kicker is that it happens BEFORE it actually tries to set the property (or it would be caught in this version.) Anyone know what's going on or, more importantly, how to fix it...?
A quick caveat for my answer - it's nearly 10 years since I worked with [Progress](http://www.progress.com/) so my knowledge is probably more than a little out of date. Checking the [Progress Language Reference](http://www.psdn.com/library/servlet/KbServlet/download/1078-102-885/langref.pdf) [PDF] seems to show the two functions I remember are still there: `ROWID` and `RECID`. The `ROWID` function is newer and is preferred. In Progress 4GL you'd use it something like this: ``` FIND customer WHERE cust-num = 123. crowid = ROWID(customer). ``` or: ``` FIND customer WHERE ROWID(customer) = crowid EXCLUSIVE-LOCK. ``` Checking the [Progress SQL Reference](http://www.psdn.com/library/servlet/KbServlet/download/1223-102-1092/s92.pdf) [PDF] shows `ROWID` is also available in SQL as a Progress extension. You'd use it like so: ``` SELECT ROWID, FirstName, LastName FROM customer WHERE cust-num = 123 ``` **Edit:** Edited following Stefan's feedback.
97,506
<p><strong>This isn't a holy war, this isn't a question of "which is better".</strong></p> <p>What are the pros of using the following format for single statement if blocks.</p> <pre><code>if (x) print "x is true"; if(x) print "x is true"; </code></pre> <p>As opposed to</p> <pre><code>if (x) { print "x is true"; } if(x) { print "x is true"; } </code></pre> <p><strong>If you format your single statement ifs without brackets</strong> or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you.</p> <p><strong>Update</strong>: As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros.</p> <ol> <li>Compactness</li> <li>More readable to some</li> <li>Brackets invoke scope, which has a theoretical overhead in some cases</li> </ol>
[ { "answer_id": 97516, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 6, "selected": false, "text": "<p><strong>I strongly dislike any style that places the if's test and body on the same line.</strong></p>\n\n<p>This is...
2008/09/18
[ "https://Stackoverflow.com/questions/97506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
**This isn't a holy war, this isn't a question of "which is better".** What are the pros of using the following format for single statement if blocks. ``` if (x) print "x is true"; if(x) print "x is true"; ``` As opposed to ``` if (x) { print "x is true"; } if(x) { print "x is true"; } ``` **If you format your single statement ifs without brackets** or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you. **Update**: As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros. 1. Compactness 2. More readable to some 3. Brackets invoke scope, which has a theoretical overhead in some cases
I find this: ``` if( true ) { DoSomething(); } else { DoSomethingElse(); } ``` better than this: ``` if( true ) DoSomething(); else DoSomethingElse(); ``` This way, if I (or someone else) comes back to this code later to add more code to one of the branches, I won't have to worry about forgetting to surround the code in braces. Our eyes will visually see the indenting as clues to what we're trying to do, but most languages won't.
97,522
<p>What are all the valid self-closing elements (e.g. &lt;br/&gt;) in XHTML (as implemented by the major browsers)?</p> <p>I know that XHTML technically allows any element to be self-closed, but I'm looking for a list of those elements supported by all major browsers. See <a href="http://dusan.fora.si/blog/self-closing-tags" rel="noreferrer">http://dusan.fora.si/blog/self-closing-tags</a> for examples of some problems caused by self-closing elements such as &lt;div /&gt;.</p>
[ { "answer_id": 97543, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": -1, "selected": false, "text": "<p>&lt;hr /&gt; is another</p>\n" }, { "answer_id": 97575, "author": "e-satis", "author_id": 9951, "auth...
2008/09/18
[ "https://Stackoverflow.com/questions/97522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1335/" ]
What are all the valid self-closing elements (e.g. <br/>) in XHTML (as implemented by the major browsers)? I know that XHTML technically allows any element to be self-closed, but I'm looking for a list of those elements supported by all major browsers. See <http://dusan.fora.si/blog/self-closing-tags> for examples of some problems caused by self-closing elements such as <div />.
Every browser that supports XHTML (Firefox, Opera, Safari, [IE9](https://learn.microsoft.com/en-us/archive/blogs/ie/xhtml-in-ie9)) supports self-closing syntax on **every element**. `<div/>`, `<script/>`, `<br></br>` all should work just fine. If they don't, then you have *HTML* with inappropriately added XHTML DOCTYPE. **DOCTYPE does not change how document is interpreted. [Only MIME type does](http://www.webdevout.net/articles/beware-of-xhtml#content_type)**. [W3C decision about ignoring DOCTYPE](https://lists.w3.org/Archives/Public/www-html/2000Sep/0024.html): > > The HTML WG has discussed this issue: the intention was to allow old > (HTML-only) browsers to accept XHTML 1.0 documents by following the > guidelines, and serving them as text/html. Therefore, documents served as > text/html should be treated as HTML and not as XHTML. > > > It's a very common pitfall, because W3C Validator largely ignores that rule, but browsers follow it religiously. Read [Understanding HTML, XML and XHTML](https://webkit.org/blog/68/understanding-html-xml-and-xhtml/) from WebKit blog: > > In fact, the vast majority of supposedly XHTML documents on the internet are served as `text/html`. Which means they are not XHTML at all, but actually invalid HTML that’s getting by on the error handling of HTML parsers. All those “Valid XHTML 1.0!” links on the web are really saying “Invalid HTML 4.01!”. > > > --- To test whether you have real XHTML or invalid HTML with XHTML's DOCTYPE, put this in your document: ``` <span style="color:green"><span style="color:red"/> If it's red, it's HTML. Green is XHTML. </span> ``` It validates, and in real XHTML it works perfectly (see: [1](https://kornel.ski/1) vs [2](https://kornel.ski/2)). If you can't believe your eyes (or don't know how to set MIME types), open your page via [XHTML proxy](https://schneegans.de/xp/). Another way to check is view source in Firefox. It will highlight slashes in red when they're invalid. In HTML5/XHTML5 this hasn't changed, and the distinction is even clearer, because you don't even have additional `DOCTYPE`. `Content-Type` is the king. --- For the record, the XHTML spec allows any element to be self-closing by making XHTML an [XML application](https://www.w3.org/TR/REC-xml/#sec-starttags): [emphasis mine] > > Empty-element tags may be used for **any element which has no content**, whether or not it is declared using the keyword EMPTY. > > > It's also explicitly shown in the [XHTML spec](https://www.w3.org/TR/xhtml1/#h-4.6): > > Empty elements must **either** have an end tag or the start tag must end with `/>`. For instance, `<br/>` or `<hr></hr>` > > >
97,565
<p>C# question (.net 3.5). I have a class, ImageData, that has a field ushort[,] pixels. I am dealing with proprietary image formats. The ImageData class takes a file location in the constructor, then switches on file extension to determine how to decode. In several of the image files, there is a "bit depth" field in the header. After I decode the header I read the pixel values into the "pixels" array. So far I have not had more than 16bpp, so I'm okay. But what if I have 32bpp?</p> <p>What I want to do is have the type of pixels be determined at runtime. I want to do this after I read the bit depth out of the header and before I copy the pixel data into memory. Any ideas?</p>
[ { "answer_id": 97626, "author": "Colin Mackay", "author_id": 8152, "author_profile": "https://Stackoverflow.com/users/8152", "pm_score": 2, "selected": false, "text": "<p>I would say not to do that work in the construtor - A constructor should not do so much work, in my opinion. Use a fa...
2008/09/18
[ "https://Stackoverflow.com/questions/97565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1812999/" ]
C# question (.net 3.5). I have a class, ImageData, that has a field ushort[,] pixels. I am dealing with proprietary image formats. The ImageData class takes a file location in the constructor, then switches on file extension to determine how to decode. In several of the image files, there is a "bit depth" field in the header. After I decode the header I read the pixel values into the "pixels" array. So far I have not had more than 16bpp, so I'm okay. But what if I have 32bpp? What I want to do is have the type of pixels be determined at runtime. I want to do this after I read the bit depth out of the header and before I copy the pixel data into memory. Any ideas?
To boil down your problem, you want to be able to have a class that has a **ushort[,] pixels** field (16-bits per pixel) sometimes and a **uint32[,] pixels** field (32-bits per pixel) some other times. There are a couple different ways to achieve this. You could create replacements for ushort / uint32 by making a Pixel class with 32-bit and 16-bit sub-classes, overriding various operators up the wazoo, but this incurs a lot of overhead, is tricky to get right and even trickier to determine if its right. Alternately you could create proxy classes for your pixel data (which would contain the ushort[,] or uint32[,] arrays and would have all the necessary accessors to be useful). The downside there is that you would likely end up with a lot of special case code in the ImageData class which executed one way or the other depending on some 16-bit/32-bit mode flag. The better solution, I think, would be to sub-class ImageData into 16-bit and 32-bit classes, and use a factory method to create instances. E.g. ImageData is the base class, ImageData16bpp and ImageData32bpp are sub-classes, static method ImageData.Create(string imageFilename) is the factory method which creates either ImageData16bpp or ImageData32bpp depending on the header data. For example: ``` public static ImageData Create(string imageFilename) { // ... ImageDataHeader imageHeader = ParseHeader(imageFilename); ImageData newImageData; if (imageHeader.bpp == 32) { newImageData = new ImageData32(imageFilename, imageHeader); } else { newImageData = new ImageData16(imageFilename, imageHeader); } // ... return newImageData; } ```
97,578
<p>Maybe I'm just thinking about this too hard, but I'm having a problem figuring out what escaping to use on a string in some JavaScript code inside a link's onClick handler. Example:</p> <pre><code>&lt;a href="#" onclick="SelectSurveyItem('&lt;%itemid%&gt;', '&lt;%itemname%&gt;'); return false;"&gt;Select&lt;/a&gt; </code></pre> <p>The <code>&lt;%itemid%&gt;</code> and <code>&lt;%itemname%&gt;</code> are where template substitution occurs. My problem is that the item name can contain any character, including single and double quotes. Currently, if it contains single quotes it breaks the JavaScript code.</p> <p>My first thought was to use the template language's function to JavaScript-escape the item name, which just escapes the quotes. That will not fix the case of the string containing double quotes which breaks the HTML of the link. How is this problem normally addressed? Do I need to HTML-escape the entire onClick handler?</p> <p>If so, that would look really strange since the template language's escape function for that would also HTMLify the parentheses, quotes, and semicolons...</p> <p>This link is being generated for every result in a search results page, so creating a separate method inside a JavaScript tag is not possible, because I'd need to generate one per result.</p> <p>Also, I'm using a templating engine that was home-grown at the company I work for, so toolkit-specific solutions will be of no use to me.</p>
[ { "answer_id": 97591, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 1, "selected": false, "text": "<p>Declare separate functions in the &lt;head&gt; section and invoke those in your onClick method. If you have lots you ...
2008/09/18
[ "https://Stackoverflow.com/questions/97578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10861/" ]
Maybe I'm just thinking about this too hard, but I'm having a problem figuring out what escaping to use on a string in some JavaScript code inside a link's onClick handler. Example: ``` <a href="#" onclick="SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;">Select</a> ``` The `<%itemid%>` and `<%itemname%>` are where template substitution occurs. My problem is that the item name can contain any character, including single and double quotes. Currently, if it contains single quotes it breaks the JavaScript code. My first thought was to use the template language's function to JavaScript-escape the item name, which just escapes the quotes. That will not fix the case of the string containing double quotes which breaks the HTML of the link. How is this problem normally addressed? Do I need to HTML-escape the entire onClick handler? If so, that would look really strange since the template language's escape function for that would also HTMLify the parentheses, quotes, and semicolons... This link is being generated for every result in a search results page, so creating a separate method inside a JavaScript tag is not possible, because I'd need to generate one per result. Also, I'm using a templating engine that was home-grown at the company I work for, so toolkit-specific solutions will be of no use to me.
In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string. \xXX is for chars < 127, and \uXXXX for [Unicode](http://en.wikipedia.org/wiki/Unicode), so armed with this knowledge you can create a robust *JSEncode* function for all characters that are out of the usual whitelist. For example, ``` <a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a> ```
97,586
<p>My boss loves VB (we work in a Java shop) because he thinks it's easy to learn and maintain. We want to replace some of the VB with java equivalents using the Eclipse SWT editor, because we think it is almost as easy to maintain. To sell this, we'd like to use an aerith style L&amp;F.</p> <p>Can anyone provide an example of an SWT application still being able to edit the GUI in eclipse, but having the Aerith L&amp;F?</p>
[ { "answer_id": 97591, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 1, "selected": false, "text": "<p>Declare separate functions in the &lt;head&gt; section and invoke those in your onClick method. If you have lots you ...
2008/09/18
[ "https://Stackoverflow.com/questions/97586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15441/" ]
My boss loves VB (we work in a Java shop) because he thinks it's easy to learn and maintain. We want to replace some of the VB with java equivalents using the Eclipse SWT editor, because we think it is almost as easy to maintain. To sell this, we'd like to use an aerith style L&F. Can anyone provide an example of an SWT application still being able to edit the GUI in eclipse, but having the Aerith L&F?
In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string. \xXX is for chars < 127, and \uXXXX for [Unicode](http://en.wikipedia.org/wiki/Unicode), so armed with this knowledge you can create a robust *JSEncode* function for all characters that are out of the usual whitelist. For example, ``` <a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a> ```
97,637
<p>Anyone got a good explanation of "combinators" (Y-combinators etc. and <strong>NOT</strong> <a href="https://en.wikipedia.org/wiki/Y_Combinator_(company)" rel="noreferrer">the company</a>)?</p> <p>I'm looking for one for the practical programmer who understands recursion and higher-order functions, but doesn't have a strong theory or math background.</p> <p>(Note: that I'm talking about <a href="https://en.wikipedia.org/wiki/Fixed-point_combinator#Fixed_point_combinators_in_lambda_calculus" rel="noreferrer">these things</a>)</p>
[ { "answer_id": 97771, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 2, "selected": false, "text": "<p>This is a good <a href=\"https://web.archive.org/web/20160913141703/http://www.dreamsongs.com/NewFiles/WhyOfY.pd...
2008/09/18
[ "https://Stackoverflow.com/questions/97637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8482/" ]
Anyone got a good explanation of "combinators" (Y-combinators etc. and **NOT** [the company](https://en.wikipedia.org/wiki/Y_Combinator_(company)))? I'm looking for one for the practical programmer who understands recursion and higher-order functions, but doesn't have a strong theory or math background. (Note: that I'm talking about [these things](https://en.wikipedia.org/wiki/Fixed-point_combinator#Fixed_point_combinators_in_lambda_calculus))
Unless you're deeply into theory, you can regard the Y combinator as a neat trick with functions, like monads. Monads allow you to chain actions, the Y combinator allows you to define self-recursive functions. Python has built-in support for self-recursive functions, so you can define them without Y: ``` > def fun(): > print "bla" > fun() > fun() bla bla bla ... ``` `fun` is accessible inside `fun` itself, so we can easily call it. *But what if Python were different, and `fun` weren't accessible inside `fun`?* ``` > def fun(): > print "bla" > # what to do here? (cannot call fun!) ``` The solution is to pass `fun` itself as an argument to `fun`: ``` > def fun(arg): # fun receives itself as argument > print "bla" > arg(arg) # to recur, fun calls itself, and passes itself along ``` And Y makes that possible: ``` > def Y(f): > f(f) > Y(fun) bla bla bla ... ``` All it does it call a function with itself as argument. (I don't know if this definition of Y is 100% correct, but I think it's the general idea.)
97,640
<p>How do I get my project's runtime dependencies copied into the <code>target/lib</code> folder? </p> <p>As it is right now, after <code>mvn clean install</code> the <code>target</code> folder contains only my project's jar, but none of the runtime dependencies.</p>
[ { "answer_id": 97748, "author": "Eduard Wirch", "author_id": 17428, "author_profile": "https://Stackoverflow.com/users/17428", "pm_score": 2, "selected": false, "text": "<p>If you make your project a war or ear type maven will copy the dependencies.</p>\n" }, { "answer_id": 97837...
2008/09/18
[ "https://Stackoverflow.com/questions/97640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18320/" ]
How do I get my project's runtime dependencies copied into the `target/lib` folder? As it is right now, after `mvn clean install` the `target` folder contains only my project's jar, but none of the runtime dependencies.
This works for me: ```xml <project> ... <profiles> <profile> <id>qa</id> <build> <plugins> <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <phase>install</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project> ```
97,663
<p>Programming PHP in Eclipse PDT is predominately a joy: code completion, templates, method jumping, etc.</p> <p>However, one thing that drives me crazy is that I can't get my lines in PHP files to word wrap so on long lines I'm typing out indefinitely to the right.</p> <p>I click on Windows|Preferences and type in "wrap" and get:</p> <pre><code>- Java | Code Style | Formatter - Java | Editor | Typing - Web and XML | CSS Files | Source </code></pre> <p>I've tried changing the "wrap automatically" that I found there and the "Line width" to 72 but they had no effect.</p> <p>How can I get word wrap to work in Eclipse PDT for PHP files?</p>
[ { "answer_id": 97691, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 3, "selected": false, "text": "<p>It's a known enhancement request. <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=35779\" rel=\"noreferrer\">Bug...
2008/09/18
[ "https://Stackoverflow.com/questions/97663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
Programming PHP in Eclipse PDT is predominately a joy: code completion, templates, method jumping, etc. However, one thing that drives me crazy is that I can't get my lines in PHP files to word wrap so on long lines I'm typing out indefinitely to the right. I click on Windows|Preferences and type in "wrap" and get: ``` - Java | Code Style | Formatter - Java | Editor | Typing - Web and XML | CSS Files | Source ``` I've tried changing the "wrap automatically" that I found there and the "Line width" to 72 but they had no effect. How can I get word wrap to work in Eclipse PDT for PHP files?
This has really been one of the most desired features in Eclipse. It's not just missing in PHP files-- it's missing in the IDE. Fortunately, from Google Summer of Code, we get this plug-in [Eclipse Word-Wrap](http://ahtik.com/blog/projects/eclipse-word-wrap/) To install it, add the following update site in Eclipse: [AhtiK Eclipse WordWrap 0.0.5 Update Site](http://ahtik.com/eclipse-update/)
97,683
<p>Here is a snippet of CSS that I need explained:</p> <pre class="lang-css prettyprint-override"><code>#section { width: 860px; background: url(/blah.png); position: absolute; top: 0; left: 50%; margin-left: -445px; } </code></pre> <p>Ok so it's absolute positioning of an image, obviously.</p> <ol> <li>top is like padding from the top, right?</li> <li>what does left 50% do?</li> <li>why is the left margin at -445px? </li> </ol> <p><b>Update:</b> width is 860px. The actual image is 100x100 if that makes a difference??</p>
[ { "answer_id": 97702, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "<p>When position is absolute, top is vertical distance from the parent (probably the body tag, so 0 is the top edge of t...
2008/09/18
[ "https://Stackoverflow.com/questions/97683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
Here is a snippet of CSS that I need explained: ```css #section { width: 860px; background: url(/blah.png); position: absolute; top: 0; left: 50%; margin-left: -445px; } ``` Ok so it's absolute positioning of an image, obviously. 1. top is like padding from the top, right? 2. what does left 50% do? 3. why is the left margin at -445px? **Update:** width is 860px. The actual image is 100x100 if that makes a difference??
1. Top is the distance from the top of the html element or, if this is within another element with absolute position, from the top of that. 2. & 3. It depends on the width of the image but it might be for centering the image horizontally (if the width of the image is 890px). There are other ways to center an image horizontally though. More commonly, this is used to center a block of known height vertically (this is the easiest way to center something of known height vertically): ```css top: 50% margin-top: -(height/2)px; ```
97,694
<p>I've been somewhat spoiled using Eclipse and java. I started using vim to do C coding in a linux environment, is there a way to have vim automatically do the proper spacing for blocks? </p> <p>So after typing a { the next line will have 2 spaces indented in, and a return on that line will keep it at the same indentation, and a } will shift back 2 spaces?</p>
[ { "answer_id": 97720, "author": "Craig B.", "author_id": 10780, "author_profile": "https://Stackoverflow.com/users/10780", "pm_score": -1, "selected": false, "text": "<p>Try:</p>\n\n<p>set sw=2</p>\n\n<p>set ts=2</p>\n\n<p>set smartindent</p>\n" }, { "answer_id": 97723, "auth...
2008/09/18
[ "https://Stackoverflow.com/questions/97694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
I've been somewhat spoiled using Eclipse and java. I started using vim to do C coding in a linux environment, is there a way to have vim automatically do the proper spacing for blocks? So after typing a { the next line will have 2 spaces indented in, and a return on that line will keep it at the same indentation, and a } will shift back 2 spaces?
These two commands should do it: ``` :set autoindent :set cindent ``` For bonus points put them in a file named .vimrc located in your home directory on linux
97,733
<p>I'm working with PostSharp to intercept method calls to objects I don't own, but my aspect code doesn't appear to be getting called. The documentation seems pretty lax in the Silverlight area, so I'd appreciate any help you guys can offer :)</p> <p>I have an attribute that looks like:</p> <pre><code>public class LogAttribute : OnMethodInvocationAspect { public override void OnInvocation(MethodInvocationEventArgs eventArgs) { // Logging code goes here... } } </code></pre> <p>And an entry in my AssemblyInfo that looks like:</p> <pre><code>[assembly: Log(AttributeTargetAssemblies = "System.Windows", AttributeTargetTypes = "System.Windows.Controls.*")] </code></pre> <p>So, my question to you is... what am I missing? Method calls under matching attribute targets don't appear to function.</p>
[ { "answer_id": 97773, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p>I believe if you change AttributeTargetAssemblies to \"PresentationFramework\", it might work. (Don't have PostSharp dow...
2008/09/18
[ "https://Stackoverflow.com/questions/97733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473493/" ]
I'm working with PostSharp to intercept method calls to objects I don't own, but my aspect code doesn't appear to be getting called. The documentation seems pretty lax in the Silverlight area, so I'd appreciate any help you guys can offer :) I have an attribute that looks like: ``` public class LogAttribute : OnMethodInvocationAspect { public override void OnInvocation(MethodInvocationEventArgs eventArgs) { // Logging code goes here... } } ``` And an entry in my AssemblyInfo that looks like: ``` [assembly: Log(AttributeTargetAssemblies = "System.Windows", AttributeTargetTypes = "System.Windows.Controls.*")] ``` So, my question to you is... what am I missing? Method calls under matching attribute targets don't appear to function.
**This is not possible with the present version of PostSharp.** PostSharp works by transforming assemblies prior to being loaded by the CLR. Right now, in order to do that, two things have to happen: * The assembly must be about to be loaded into the CLR; you only get one shot, and you have to take it at this point. * After the transformation stage has finished, you can't make any additional modifications. That means you can't modify the assembly at runtime. The newest version, 1.5 CTP 3, [removes the first of these two limitations](http://www.postsharp.org/blog/announcing-postsharp-1.5-ctp-3), but it is the second that's really the problem. This is, however, [a heavily requested feature](http://www.postsharp.org/blog/using-postsharp-at-runtime), so keep your eyes peeled: > > Users often ask if it is possible to use PostSharp at runtime, so aspects don't have to be known at compile time. Changing aspects after deployment is indeed a great advantage, since it allow support staff to enable/disable tracing or performance monitoring for individual parts of the software. **One of the cool things it would enable is to apply aspects on third-party assemblies.** > > > If you ask whether it is possible, the short answer is yes! **Unfortunately, the long answer is more complex.** > > > ### Runtime/third-party aspect gotchas The author also proceeds to outline some of the problems that happen if you allow modification at runtime: > > So now, what are the gotchas? > > > * **Plugging the bootstrapper.** If your code is hosted (for instance in > ASP.NET or in a COM server), you > cannot plug the bootstrapper. So any > runtime weaving technology is bound to > the limitation that you should host > the application yourself. > * **Be Before the CLR.** If the CLR finds the untransformed assembly by its own, > it will not ask for the transformed > one. So you may need to create a new > application domain for the transformed > application, and put transformed > assemblies in its binary path. It's > maybe not a big problem. > * **Strong names.** Ough. If you modify an assembly at runtime, you will have to > remove its strong name. Will it work? > Yes, mostly. Of course, you have to > remove the strong names from all > references to this assembly. That's > not a problem; PostSharp supports it > out-of-the-box. But there is something > PostSharp cannot help with: if there > are some strongly named references in > strings or files (for instance in > app.config), we can hardly find them > and transform them. So here we have a > real limitation: there cannot be > "loose references" to strongly named > assemblies: we are only able to > transform real references. > * **LoadFrom.** If any assembly uses Assembly.LoadFrom, Assembly.LoadFile > or Assembly.LoadBytes, our > bootstrapper is skipped. > > >
97,762
<p>I have a collection of non-overlapping rectangles that cover an enclosing rectangle. What is the best way to find the containing rectangle for a mouse click?</p> <p>The obvious answer is to have an array of rectangles and to search them in sequence, making the search O(n). Is there some way to order them by position so that the algorithm is less than O(n), say, O(log n) or O(sqrt(n))?</p>
[ { "answer_id": 97783, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 0, "selected": false, "text": "<p>Shove them in a <a href=\"http://en.wikipedia.org/wiki/Quadtree\" rel=\"nofollow noreferrer\">quadtree</a>.</p>\n" ...
2008/09/18
[ "https://Stackoverflow.com/questions/97762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10293/" ]
I have a collection of non-overlapping rectangles that cover an enclosing rectangle. What is the best way to find the containing rectangle for a mouse click? The obvious answer is to have an array of rectangles and to search them in sequence, making the search O(n). Is there some way to order them by position so that the algorithm is less than O(n), say, O(log n) or O(sqrt(n))?
You can organize your rectangles in a quad or kd-tree. That gives you O(log n). That's the mainstream method. Another interesting data-structure for this problem are R-trees. These can be very efficient if you have to deal with lots of rectangles. <http://en.wikipedia.org/wiki/R-tree> And then there is the O(1) method of simply generating a bitmap at the same size as your screen, fill it with a place-holder for "no rectangle" and draw the hit-rectangle indices into that bitmap. A lookup becomes as simple as: ``` int id = bitmap_getpixel (mouse.x, mouse.y) if (id != -1) { hit_rectange (id); } else { no_hit(); } ``` Obviously that method only works well if your rectangles don't change that often and if you can spare the memory for the bitmap.
97,781
<p>Part of a new product I have been assigned to work on involves server-side conversion of the 'common' video formats to something that Flash can play.</p> <p>As far as I know, my only option is to convert to FLV. I have been giving ffmpeg a go around, but I'm finding a few WMV files that come out with garbled sound (I've tried playing with the audio rates).</p> <p>Are there any other 'good' CLI converters for Linux? Or are there other video formats that Flash can play?</p>
[ { "answer_id": 97799, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 5, "selected": true, "text": "<p>Flash can play the following formats:</p>\n\n<pre><code>FLV with AAC or MP3 audio, and FLV1 (Sorenson Spark H.263), ...
2008/09/18
[ "https://Stackoverflow.com/questions/97781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2192/" ]
Part of a new product I have been assigned to work on involves server-side conversion of the 'common' video formats to something that Flash can play. As far as I know, my only option is to convert to FLV. I have been giving ffmpeg a go around, but I'm finding a few WMV files that come out with garbled sound (I've tried playing with the audio rates). Are there any other 'good' CLI converters for Linux? Or are there other video formats that Flash can play?
Flash can play the following formats: ``` FLV with AAC or MP3 audio, and FLV1 (Sorenson Spark H.263), VP6, or H.264 video. MP4 with AAC or MP3 audio, and H.264 video (mp4s must be hinted with qt-faststart or mp4box). ``` ffmpeg is an overall good conversion utility; mencoder works better with obscure and proprietary formats (due to the w32codecs binary decoder package) but its muxing is rather suboptimal (read: often totally broken). One solution might be to encode H.264 with x264 through mencoder, and then mux separately with mp4box. As a developer of x264 (and avid user of flash for online video playback), I've had quite a bit of experience in this kind of stuff, so if you want more assistance I'm also available on Freenode IRC on #x264, #ffmpeg, and #mplayer.
97,840
<p>I'm trying to configure a dedicated server that runs ASP.NET to send mail through the local IIS SMTP server but mail is getting stuck in the Queue folder and doesn't get delivered.</p> <p>I'm using this code in an .aspx page to test:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" %&gt; &lt;% new System.Net.Mail.SmtpClient("localhost").Send("info@thedomain.com", "jcarrascal@gmail.com", "testing...", "Hello, world.com"); %&gt; </code></pre> <p>Then, I added the following to the Web.config file:</p> <pre><code>&lt;system.net&gt; &lt;mailSettings&gt; &lt;smtp&gt; &lt;network host="localhost"/&gt; &lt;/smtp&gt; &lt;/mailSettings&gt; &lt;/system.net&gt; </code></pre> <p>In the IIS Manager I've changed the following in the properties of the "Default SMTP Virtual Server".</p> <pre><code>General: [X] Enable Logging Access / Authentication: [X] Windows Integrated Authentication Access / Relay Restrictions: (o) Only the list below, Granted 127.0.0.1 Delivery / Advanced: Fully qualified domain name = thedomain.com </code></pre> <p>Finally, I run the SMTPDiag.exe tool like this:</p> <pre><code>C:\&gt;smtpdiag.exe info@thedomain.com jcarrascal@gmail.com Searching for Exchange external DNS settings. Computer name is THEDOMAIN. Failed to connect to the domain controller. Error: 8007054b Checking SOA for gmail.com. Checking external DNS servers. Checking internal DNS servers. SOA serial number match: Passed. Checking local domain records. Checking MX records using TCP: thedomain.com. Checking MX records using UDP: thedomain.com. Both TCP and UDP queries succeeded. Local DNS test passed. Checking remote domain records. Checking MX records using TCP: gmail.com. Checking MX records using UDP: gmail.com. Both TCP and UDP queries succeeded. Remote DNS test passed. Checking MX servers listed for jcarrascal@gmail.com. Connecting to gmail-smtp-in.l.google.com [209.85.199.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gmail-smtp-in.l.google.com. Connecting to gmail-smtp-in.l.google.com [209.85.199.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt1.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt1.gmail-smtp-in.l.google.com. Connecting to gsmtp183.google.com [64.233.183.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gsmtp183.google.com. Connecting to gsmtp147.google.com [209.85.147.27] on port 25. Connecting to the server failed. Error: 10051 Failed to submit mail to gsmtp147.google.com. </code></pre> <p>I'm using ASP.NET 2.0, Windows 2003 Server and the IIS that comes with it.</p> <p>Can you tell me what else to change to fix the problem?</p> <p>Thanks</p> <hr> <p>@mattlant</p> <p>This is a dedicated server that's why I'm installing the SMTP manually.</p> <blockquote> <p>EDIT: I use exchange so its a little different, but its called a smart host in exchange, but in plain SMTP service config i think its called something else. Cant remember exactly the setting name.</p> </blockquote> <p>Thank you for pointing me at the Smart host field. Mail is getting delivered now.</p> <p>In the Default SMTP Virtual Server properties, the Delivery tab, click Advanced and fill the "Smart host" field with the address that your provider gives you. In my case (GoDaddy) it was k2smtpout.secureserver.net.</p> <p>More info here: <a href="http://help.godaddy.com/article/1283" rel="nofollow noreferrer">http://help.godaddy.com/article/1283</a></p>
[ { "answer_id": 97854, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 3, "selected": true, "text": "<p>I find the best thing usually depending on how much email there is, is to just forward the mail through your ISP's SMTP ...
2008/09/18
[ "https://Stackoverflow.com/questions/97840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148/" ]
I'm trying to configure a dedicated server that runs ASP.NET to send mail through the local IIS SMTP server but mail is getting stuck in the Queue folder and doesn't get delivered. I'm using this code in an .aspx page to test: ``` <%@ Page Language="C#" AutoEventWireup="true" %> <% new System.Net.Mail.SmtpClient("localhost").Send("info@thedomain.com", "jcarrascal@gmail.com", "testing...", "Hello, world.com"); %> ``` Then, I added the following to the Web.config file: ``` <system.net> <mailSettings> <smtp> <network host="localhost"/> </smtp> </mailSettings> </system.net> ``` In the IIS Manager I've changed the following in the properties of the "Default SMTP Virtual Server". ``` General: [X] Enable Logging Access / Authentication: [X] Windows Integrated Authentication Access / Relay Restrictions: (o) Only the list below, Granted 127.0.0.1 Delivery / Advanced: Fully qualified domain name = thedomain.com ``` Finally, I run the SMTPDiag.exe tool like this: ``` C:\>smtpdiag.exe info@thedomain.com jcarrascal@gmail.com Searching for Exchange external DNS settings. Computer name is THEDOMAIN. Failed to connect to the domain controller. Error: 8007054b Checking SOA for gmail.com. Checking external DNS servers. Checking internal DNS servers. SOA serial number match: Passed. Checking local domain records. Checking MX records using TCP: thedomain.com. Checking MX records using UDP: thedomain.com. Both TCP and UDP queries succeeded. Local DNS test passed. Checking remote domain records. Checking MX records using TCP: gmail.com. Checking MX records using UDP: gmail.com. Both TCP and UDP queries succeeded. Remote DNS test passed. Checking MX servers listed for jcarrascal@gmail.com. Connecting to gmail-smtp-in.l.google.com [209.85.199.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gmail-smtp-in.l.google.com. Connecting to gmail-smtp-in.l.google.com [209.85.199.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [209.85.135.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt1.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt2.gmail-smtp-in.l.google.com [74.125.79.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt2.gmail-smtp-in.l.google.com. Connecting to alt1.gmail-smtp-in.l.google.com [209.85.133.114] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to alt1.gmail-smtp-in.l.google.com. Connecting to gsmtp183.google.com [64.233.183.27] on port 25. Connecting to the server failed. Error: 10060 Failed to submit mail to gsmtp183.google.com. Connecting to gsmtp147.google.com [209.85.147.27] on port 25. Connecting to the server failed. Error: 10051 Failed to submit mail to gsmtp147.google.com. ``` I'm using ASP.NET 2.0, Windows 2003 Server and the IIS that comes with it. Can you tell me what else to change to fix the problem? Thanks --- @mattlant This is a dedicated server that's why I'm installing the SMTP manually. > > EDIT: I use exchange so its a little > different, but its called a smart host > in exchange, but in plain SMTP service > config i think its called something > else. Cant remember exactly the > setting name. > > > Thank you for pointing me at the Smart host field. Mail is getting delivered now. In the Default SMTP Virtual Server properties, the Delivery tab, click Advanced and fill the "Smart host" field with the address that your provider gives you. In my case (GoDaddy) it was k2smtpout.secureserver.net. More info here: <http://help.godaddy.com/article/1283>
I find the best thing usually depending on how much email there is, is to just forward the mail through your ISP's SMTP server. Less headaches. Looks like that's where you are having issues, from your SMTP to external servers, not asp.net to your SMTP. Just have your SMTP server set to send it to your ISP, or you can configure asp.net to send to it. EDIT: I use exchange so it's a little different, but it's called a smart host in exchange, but in plain SMTP service config I think it's called something else. I can't remember exactly the setting name.
97,857
<p>Suppose I have a stored procedure that manages its own transaction</p> <pre><code>CREATE PROCEDURE theProc AS BEGIN BEGIN TRANSACTION -- do some stuff IF @ThereIsAProblem ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION END </code></pre> <p>If I call this proc from an existing transaction, the proc can ROLLBACK the external transaction.</p> <pre><code>BEGIN TRANSACTION EXEC theProc COMMIT TRANSACTION </code></pre> <p>How do I properly scope the transaction within the stored procedure, so that the stored procedure does not rollback external transactions?</p>
[ { "answer_id": 97931, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 1, "selected": false, "text": "<p>use @@trancount to see if you're already in a transaction when entering</p>\n" }, { "answer_id": 97944, "aut...
2008/09/18
[ "https://Stackoverflow.com/questions/97857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8155/" ]
Suppose I have a stored procedure that manages its own transaction ``` CREATE PROCEDURE theProc AS BEGIN BEGIN TRANSACTION -- do some stuff IF @ThereIsAProblem ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION END ``` If I call this proc from an existing transaction, the proc can ROLLBACK the external transaction. ``` BEGIN TRANSACTION EXEC theProc COMMIT TRANSACTION ``` How do I properly scope the transaction within the stored procedure, so that the stored procedure does not rollback external transactions?
The syntax to do this probably varies by database. But in Transact-SQL what you do is check @@TRANCOUNT to see if you are in a transaction. If you are then you want to create a savepoint, and at the end you can just pass through the end of the function (believing a commit or rollback will happen later) or else rollback to your savepoint. See Microsoft's documentation on [savepoints](http://msdn.microsoft.com/en-us/library/ms188378.aspx) for more. Support for savepoints is fairly widespread, but I think the mechanism (assuming there is one) for finding out that you're currently in a transaction will vary quite a bit.
97,875
<p>I need a way to recursively delete a folder and its children.</p> <p>Is there a prebuilt tool for this, or do I need to write one?</p> <p><code>DEL /S</code> doesn't delete directories.</p> <p><code>DELTREE</code> was removed from Windows 2000+</p>
[ { "answer_id": 97891, "author": "Brian Mitchell", "author_id": 13716, "author_profile": "https://Stackoverflow.com/users/13716", "pm_score": 2, "selected": false, "text": "<p>rmdir /s dirname</p>\n" }, { "answer_id": 97895, "author": "Paige Ruten", "author_id": 813, "...
2008/09/18
[ "https://Stackoverflow.com/questions/97875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I need a way to recursively delete a folder and its children. Is there a prebuilt tool for this, or do I need to write one? `DEL /S` doesn't delete directories. `DELTREE` was removed from Windows 2000+
RMDIR or RD if you are using the classic Command Prompt (cmd.exe): ``` rd /s /q "path" ``` > > RMDIR [/S] [/Q] [drive:]path > > > RD [/S] [/Q] [drive:]path > > > /S Removes all directories and files in the specified directory in addition to the directory itself. **Used to remove a directory tree.** > > > /Q Quiet mode, do not ask if ok to remove a directory tree with /S > > > If you are using PowerShell you can use `Remove-Item` (which is aliased to `del`, `erase`, `rd`, `ri`, `rm` and `rmdir`) and takes a `-Recurse` argument that can be shorted to `-r` ``` rd -r "path" ```
97,962
<p>A poorly-written back-end system we interface with is having trouble with handling the load we're producing. While they fix their load problems, we're trying to reduce any additional load we're generating, one of which is that the back-end system continues to try and service a form submission even if another submission has come from the same user.</p> <p>One thing we've noticed is users double-clicking the form submission button. I need to de-bounce these clicks, and prevent a second form submission.<br> My approach (using Prototype) places an <code>onSubmit</code> on the form that calls the following function which hides the form submission button and displays a "loading..." <code>div</code>.</p> <pre><code>function disableSubmit(id1, id2) { $(id1).style.display = 'none'; $(id2).style.display = 'inline'; } </code></pre> <p>The problem I've found with this approach is that if I use an animated gif in the "loading..." <code>div</code>, it loads fine but doesn't animate while the form is submitting.</p> <p>Is there a better way to do this de-bouncing and continue to show animation on the page while waiting for the form result to (finally) load? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 97995, "author": "Jason Wadsworth", "author_id": 11078, "author_profile": "https://Stackoverflow.com/users/11078", "pm_score": 1, "selected": false, "text": "<p>You could try setting the \"disabled\" flag on the input (type=submit) element, rather than just changing the st...
2008/09/18
[ "https://Stackoverflow.com/questions/97962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10788/" ]
A poorly-written back-end system we interface with is having trouble with handling the load we're producing. While they fix their load problems, we're trying to reduce any additional load we're generating, one of which is that the back-end system continues to try and service a form submission even if another submission has come from the same user. One thing we've noticed is users double-clicking the form submission button. I need to de-bounce these clicks, and prevent a second form submission. My approach (using Prototype) places an `onSubmit` on the form that calls the following function which hides the form submission button and displays a "loading..." `div`. ``` function disableSubmit(id1, id2) { $(id1).style.display = 'none'; $(id2).style.display = 'inline'; } ``` The problem I've found with this approach is that if I use an animated gif in the "loading..." `div`, it loads fine but doesn't animate while the form is submitting. Is there a better way to do this de-bouncing and continue to show animation on the page while waiting for the form result to (finally) load? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
If you've got jQuery handy, attach a click() event that disables the button after the initial submission - ``` $('input[type="submit"]').click(function(event){ event.preventDefault(); this.click(null); }); ``` that sort of thing.
97,971
<p>Having programmed through emacs and vi for years and years at this point, I have heard that using an IDE is a very good way of becoming more efficient.</p> <p>To that end, I have decided to try using Eclipse for a lot of coding and seeing how I get on.</p> <p>Are there any suggestions for easing the transition over to an IDE. Obviously, some will think none of this is worth the bother, but I think with Eclipse allowing emacs-style key bindings and having code completion and in-built debugging, I reckon it is well worth trying to move over to a more feature-rich environment for the bulk of my development worth.</p> <p>So what suggestions do you have for easing the transition?</p>
[ { "answer_id": 97985, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 2, "selected": false, "text": "<p>If you've been using emacs/vi for years (although you listed both, so it seems like you may not be adapted fully ...
2008/09/18
[ "https://Stackoverflow.com/questions/97971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
Having programmed through emacs and vi for years and years at this point, I have heard that using an IDE is a very good way of becoming more efficient. To that end, I have decided to try using Eclipse for a lot of coding and seeing how I get on. Are there any suggestions for easing the transition over to an IDE. Obviously, some will think none of this is worth the bother, but I think with Eclipse allowing emacs-style key bindings and having code completion and in-built debugging, I reckon it is well worth trying to move over to a more feature-rich environment for the bulk of my development worth. So what suggestions do you have for easing the transition?
Eclipse is the best IDE I've used, even considering its quite large footprint and sluggishness on slow computers (like my work machine... Pentium III!). Rather than trying to 'ease the transition', I think it's better to jump right in and let yourself be overwhelmed by the bells and whistles and truly useful refactorings etc. Here are some of the most useful things I would consciously use as soon as possible: * ctrl-shift-t finds and opens a class via incremental search on the name * ctrl-shift-o automatically generates import statements (and deletes redundant ones) * F3 on an identifier to jump to its definition, and alt-left/right like in web browsers to go back/forward in navigation history * The "Quick fix" tool, which has a large amount of context-sensitive refactorings and such. Some examples: ``` String messageXml = in.read(); Message response = messageParser.parse(messageXml); return response; ``` If you put the text cursor on the argument to parse(...) and press ctrl+1, Eclipse will suggest "Inline local variable". If you do that, then repeat with the cursor over the return variable 'response', the end result will be: ``` return messageParser.parse(in.read()); ``` There are many, many little rules like this which the quick fix tool will suggest and apply to help refactor your code (including the exact opposite, "extract to local variable/field/constant", which can be invaluable). You can write code that calls a method you haven't written yet - going to the line which now displays an error and using quick fix will offer to create a method matching the parameters inferred from your usage. Similarly so for variables. All these small refactorings and shortcuts save a lot of time and are much more quickly picked up than you'd expect. Whenever you're about to rearrange code, experiment with quick fix to see if it suggests something useful. There's also a nice bag of tricks directly available in the menus, like generating getters/setters, extracting interfaces and the like. Jump in and try everything out!
97,976
<p>I have a datagridview that accepts a list(of myObject) as a datasource. I want to add a new row to the datagrid to add to the database. I get this done by getting the list... adding a blank myObject to the list and then reseting the datasource. I now want to set the focus to the second cell in the new row.</p> <p>To CLARIFY i am trying to set the focus</p>
[ { "answer_id": 97986, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 0, "selected": false, "text": "<p>In WinForms, you should be able to set the </p>\n\n<pre><code>Me.dataEvidence.SelectedRows\n</code></pre>\n\n<p>property to th...
2008/09/18
[ "https://Stackoverflow.com/questions/97976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16820/" ]
I have a datagridview that accepts a list(of myObject) as a datasource. I want to add a new row to the datagrid to add to the database. I get this done by getting the list... adding a blank myObject to the list and then reseting the datasource. I now want to set the focus to the second cell in the new row. To CLARIFY i am trying to set the focus
You can set the focus to a specific cell in a row but only if the SelectionMode on the DataGridView is set to CellSelect. If it is, simply do the following: ``` dataGridView.Rows[rowNumber].Cells[columnNumber].Selected = true; ```
97,987
<p>What's the best practice for using a <code>switch</code> statement vs using an <code>if</code> statement for 30 <code>unsigned</code> enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conventions.</p> <p><code>switch</code> statement:</p> <pre><code>// numError is an error enumeration type, with 0 being the non-error case // fire_special_event() is a stub method for the shared processing switch (numError) { case ERROR_01 : // intentional fall-through case ERROR_07 : // intentional fall-through case ERROR_0A : // intentional fall-through case ERROR_10 : // intentional fall-through case ERROR_15 : // intentional fall-through case ERROR_16 : // intentional fall-through case ERROR_20 : { fire_special_event(); } break; default: { // error codes that require no additional action } break; } </code></pre> <p><code>if</code> statement:</p> <pre><code>if ((ERROR_01 == numError) || (ERROR_07 == numError) || (ERROR_0A == numError) || (ERROR_10 == numError) || (ERROR_15 == numError) || (ERROR_16 == numError) || (ERROR_20 == numError)) { fire_special_event(); } </code></pre>
[ { "answer_id": 98004, "author": "Alexandra Franks", "author_id": 16203, "author_profile": "https://Stackoverflow.com/users/16203", "pm_score": 4, "selected": false, "text": "<p>Compiler will optimise it anyway - go for the switch as it's the most readable.</p>\n" }, { "answer_id"...
2008/09/18
[ "https://Stackoverflow.com/questions/97987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8883/" ]
What's the best practice for using a `switch` statement vs using an `if` statement for 30 `unsigned` enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conventions. `switch` statement: ``` // numError is an error enumeration type, with 0 being the non-error case // fire_special_event() is a stub method for the shared processing switch (numError) { case ERROR_01 : // intentional fall-through case ERROR_07 : // intentional fall-through case ERROR_0A : // intentional fall-through case ERROR_10 : // intentional fall-through case ERROR_15 : // intentional fall-through case ERROR_16 : // intentional fall-through case ERROR_20 : { fire_special_event(); } break; default: { // error codes that require no additional action } break; } ``` `if` statement: ``` if ((ERROR_01 == numError) || (ERROR_07 == numError) || (ERROR_0A == numError) || (ERROR_10 == numError) || (ERROR_15 == numError) || (ERROR_16 == numError) || (ERROR_20 == numError)) { fire_special_event(); } ```
Use switch. In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement. In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).
98,033
<p>Several Linq.Enumerable functions take an <code>IEqualityComparer&lt;T&gt;</code>. Is there a convenient wrapper class that adapts a <code>delegate(T,T)=&gt;bool</code> to implement <code>IEqualityComparer&lt;T&gt;</code>? It's easy enough to write one (if your ignore problems with defining a correct hashcode), but I'd like to know if there is an out-of-the-box solution.</p> <p>Specifically, I want to do set operations on <code>Dictionary</code>s, using only the Keys to define membership (while retaining the values according to different rules).</p>
[ { "answer_id": 98119, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": false, "text": "<p>I'm afraid there is no such wrapper out-of-box. However it's not hard to create one:</p>\n\n<pre><code>class Comparer&lt;T&gt;...
2008/09/18
[ "https://Stackoverflow.com/questions/98033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9990/" ]
Several Linq.Enumerable functions take an `IEqualityComparer<T>`. Is there a convenient wrapper class that adapts a `delegate(T,T)=>bool` to implement `IEqualityComparer<T>`? It's easy enough to write one (if your ignore problems with defining a correct hashcode), but I'd like to know if there is an out-of-the-box solution. Specifically, I want to do set operations on `Dictionary`s, using only the Keys to define membership (while retaining the values according to different rules).
Ordinarily, I'd get this resolved by commenting @Sam on the answer (I've done some editing on the original post to clean it up a bit without altering the behavior.) The following is my riff of [@Sam's answer](https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/270203#270203), with a [IMNSHO] critical fix to the default hashing policy:- ``` class FuncEqualityComparer<T> : IEqualityComparer<T> { readonly Func<T, T, bool> _comparer; readonly Func<T, int> _hash; public FuncEqualityComparer( Func<T, T, bool> comparer ) : this( comparer, t => 0 ) // NB Cannot assume anything about how e.g., t.GetHashCode() interacts with the comparer's behavior { } public FuncEqualityComparer( Func<T, T, bool> comparer, Func<T, int> hash ) { _comparer = comparer; _hash = hash; } public bool Equals( T x, T y ) { return _comparer( x, y ); } public int GetHashCode( T obj ) { return _hash( obj ); } } ```
98,074
<p>I have a given certificate installed on my server. That certificate has valid dates, and seems perfectly valid in the Windows certificates MMC snap-in.</p> <p>However, when I try to read the certificate, in order to use it in an HttpRequest, I can't find it. Here is the code used:</p> <pre><code> X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySerialNumber, "xxx", true); </code></pre> <p><code>xxx</code> is the serial number; the argument <code>true</code> means "only valid certificates". The returned collection is empty.</p> <p>The strange thing is that if I pass <code>false</code>, indicating invalid certificates are acceptable, the collection contains one element&mdash;the certificate with the specified serial number.</p> <p>In conclusion: the certificate appears valid, but the <code>Find</code> method treats it as invalid! Why?</p>
[ { "answer_id": 98201, "author": "Tim Erickson", "author_id": 8787, "author_profile": "https://Stackoverflow.com/users/8787", "pm_score": 2, "selected": false, "text": "<p>I believe x509 certs are tied to a particular user. Could it be invalid because in the code you are accessing it as ...
2008/09/18
[ "https://Stackoverflow.com/questions/98074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18073/" ]
I have a given certificate installed on my server. That certificate has valid dates, and seems perfectly valid in the Windows certificates MMC snap-in. However, when I try to read the certificate, in order to use it in an HttpRequest, I can't find it. Here is the code used: ``` X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySerialNumber, "xxx", true); ``` `xxx` is the serial number; the argument `true` means "only valid certificates". The returned collection is empty. The strange thing is that if I pass `false`, indicating invalid certificates are acceptable, the collection contains one element—the certificate with the specified serial number. In conclusion: the certificate appears valid, but the `Find` method treats it as invalid! Why?
Try verifying the certificate chain using the [X509Chain](http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509chain.aspx) class. This can tell you exactly why the certificate isn't considered valid. As erickson suggested, your X509Store may not have the trusted certificate from the CA in the chain. If you used OpenSSL or another tool to generate your own self-signed CA, you need to add the public certificate for that CA to the X509Store.
98,096
<p>I've seen some people use <code>EXISTS (SELECT 1 FROM ...)</code> rather than <code>EXISTS (SELECT id FROM ...)</code> as an optimization--rather than looking up and returning a value, SQL Server can simply return the literal it was given.</p> <p>Is <code>SELECT(1)</code> always faster? Would Selecting a value from the table require work that Selecting a literal would avoid?</p>
[ { "answer_id": 98103, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<p>Yes, because when you select a literal it does not need to read from disk (or even from cache).</p>\n" }, { ...
2008/09/18
[ "https://Stackoverflow.com/questions/98096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18347/" ]
I've seen some people use `EXISTS (SELECT 1 FROM ...)` rather than `EXISTS (SELECT id FROM ...)` as an optimization--rather than looking up and returning a value, SQL Server can simply return the literal it was given. Is `SELECT(1)` always faster? Would Selecting a value from the table require work that Selecting a literal would avoid?
For google's sake, I'll update this question with the same answer as this one ([Subquery using Exists 1 or Exists \*](https://stackoverflow.com/questions/1597442/subquery-using-exists-1-or-exists/)) since (currently) an incorrect answer is marked as accepted. Note the SQL standard actually says that EXISTS via \* is identical to a constant. No. This has been covered a bazillion times. SQL Server is smart and knows it is being used for an EXISTS, and returns NO DATA to the system. Quoth Microsoft: <http://technet.microsoft.com/en-us/library/ms189259.aspx?ppud=4> > > The select list of a subquery > introduced by EXISTS almost always > consists of an asterisk (\*). There is > no reason to list column names because > you are just testing whether rows that > meet the conditions specified in the > subquery exist. > > > Also, don't believe me? Try running the following: ``` SELECT whatever FROM yourtable WHERE EXISTS( SELECT 1/0 FROM someothertable WHERE a_valid_clause ) ``` If it was actually doing something with the SELECT list, it would throw a div by zero error. It doesn't. EDIT: Note, the SQL Standard actually talks about this. ANSI SQL 1992 Standard, pg 191 <http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt> > > > ``` > 3) Case: > > a) If the <select list> "*" is simply contained in a <subquery> that is immediately contained in an <exists predicate>, then the <select list> is equivalent to a <value expression> that is an arbitrary <literal>. > > ``` > >
98,122
<p>I am getting the following error when running a reporting services report.</p> <pre><code>Process name: w3wp.exe Account name: NT AUTHORITY\NETWORK SERVICE Exception information: Exception type: XmlException Exception message: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings to false and pass the settings into XmlReader.Create method. </code></pre> <p>I select a report, enter the parameters(the parameters look messed up) and then press view report. Then at the bottom the message "For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings ..." shows up.</p> <p>How do I fix this?</p>
[ { "answer_id": 98558, "author": "Bart", "author_id": 16980, "author_profile": "https://Stackoverflow.com/users/16980", "pm_score": 1, "selected": false, "text": "<p>Check to see if your reporting server website has the correct local path folder. You might need to do an iisreset if it is...
2008/09/18
[ "https://Stackoverflow.com/questions/98122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am getting the following error when running a reporting services report. ``` Process name: w3wp.exe Account name: NT AUTHORITY\NETWORK SERVICE Exception information: Exception type: XmlException Exception message: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings to false and pass the settings into XmlReader.Create method. ``` I select a report, enter the parameters(the parameters look messed up) and then press view report. Then at the bottom the message "For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings ..." shows up. How do I fix this?
Check to see if your reporting server website has the correct local path folder. You might need to do an iisreset if it is not correct.
98,124
<p>Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year?</p> <pre><code>myDate = new Date(); year = myDate.getYear(); </code></pre> <p>year = 108?</p>
[ { "answer_id": 98129, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>It must return the number of years since the year 1900.</p>\n" }, { "answer_id": 98131, "author": "Nils Pipe...
2008/09/18
[ "https://Stackoverflow.com/questions/98124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year? ``` myDate = new Date(); year = myDate.getYear(); ``` year = 108?
It's a [Y2K](http://en.wikipedia.org/wiki/Y2K) thing, only the years since 1900 are counted. There are potential compatibility issues now that `getYear()` has been deprecated in favour of `getFullYear()` - from [quirksmode](http://www.quirksmode.org/js/introdate.html): > > To make the matter even more complex, date.getYear() is deprecated nowadays and you should use date.getFullYear(), which, in turn, is not supported by the older browsers. If it works, however, it should always give the full year, ie. 2000 instead of 100. > > > Your browser gives the following years with these two methods: > > > ``` * The year according to getYear(): 108 * The year according to getFullYear(): 2008 ``` There are also implementation differences between Internet Explorer and Firefox, as IE's implementation of `getYear()` was changed to behave like `getFullYear()` - from [IBM](http://www-128.ibm.com/developerworks/web/library/wa-ie2mozgd/): > > Per the ECMAScript specification, getYear returns the year minus 1900, originally meant to return "98" for 1998. getYear was deprecated in ECMAScript Version 3 and replaced with getFullYear(). > > > Internet Explorer changed getYear() to work like getFullYear() and make it Y2k-compliant, while Mozilla kept the standard behavior. > > >
98,135
<p>I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?</p> <p>If I run the following code:</p> <pre><code>&gt;&gt;&gt; import django.template &gt;&gt;&gt; from django.template import Template, Context &gt;&gt;&gt; t = Template('My name is {{ my_name }}.') </code></pre> <p>I get:</p> <pre><code>ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. </code></pre>
[ { "answer_id": 98146, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>Any particular reason you want to use Django's templates? Both <a href=\"http://jinja.pocoo.org/\" rel=\"noreferrer\...
2008/09/18
[ "https://Stackoverflow.com/questions/98135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO\_SETTINGS\_MODULE environment variable? If I run the following code: ``` >>> import django.template >>> from django.template import Template, Context >>> t = Template('My name is {{ my_name }}.') ``` I get: ``` ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. ```
The solution is simple. It's actually [well documented](http://docs.djangoproject.com/en/dev/ref/templates/api/#configuring-the-template-system-in-standalone-mode), but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.) The following code works: ``` >>> from django.template import Template, Context >>> from django.conf import settings >>> settings.configure() >>> t = Template('My name is {{ my_name }}.') >>> c = Context({'my_name': 'Daryl Spitzer'}) >>> t.render(c) u'My name is Daryl Spitzer.' ``` See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).
98,153
<p>I've found the standard hashing function on VS2005 is painfully slow when trying to achieve high performance look ups. What are some good examples of fast and efficient hashing algorithms that should void most collisions?</p>
[ { "answer_id": 98164, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": "<p>That always depends on your data-set.</p>\n\n<p>I for one had surprisingly good results by using the CRC32 of t...
2008/09/18
[ "https://Stackoverflow.com/questions/98153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13646/" ]
I've found the standard hashing function on VS2005 is painfully slow when trying to achieve high performance look ups. What are some good examples of fast and efficient hashing algorithms that should void most collisions?
I worked with [Paul Larson](http://research.microsoft.com/~PALARSON/) of Microsoft Research on some hashtable implementations. He investigated a number of string hashing functions on a variety of datasets and found that a simple multiply by 101 and add loop worked surprisingly well. ``` unsigned int hash( const char* s, unsigned int seed = 0) { unsigned int hash = seed; while (*s) { hash = hash * 101 + *s++; } return hash; } ```