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
118,261
<p>E.g. we this code in the asp.net form codebihind:</p> <pre><code>private void btnSendEmails_OnClick() { Send100000EmailsAndWaitForReplies(); } </code></pre> <p>This code execution will be killed by the timeout reason. For resolving the problem I'd like to see something like this:</p> <pre><code>private void btnSendEmails_OnClick() { var taskId = AsyncTask.Run( () =&gt; Send100000EmailsAndWaitForReplies() ); // Store taskId for future task execution status checking. } </code></pre> <p>And this method will be executed for some way outside the w3wp.exe process within a special enveronment.</p> <p>Does anybody know a framework/toolset for resolving this kind of issues?</p> <p><strong>Update:</strong> The emails sending method is only an example of what I mean. In fact, I could have a lot of functionality need to be executed outside the asp.net working process. </p> <p>E.g. this point is very important for an application which aggregates data from a couple of 3rd party services, do something with it and send it back to another service.</p>
[ { "answer_id": 118278, "author": "madcolor", "author_id": 13954, "author_profile": "https://Stackoverflow.com/users/13954", "pm_score": 0, "selected": false, "text": "<p>One option is to have the task execute a certain amount of emails, then Response.Redirect back to itself and repeat un...
2008/09/22
[ "https://Stackoverflow.com/questions/118261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9198/" ]
E.g. we this code in the asp.net form codebihind: ``` private void btnSendEmails_OnClick() { Send100000EmailsAndWaitForReplies(); } ``` This code execution will be killed by the timeout reason. For resolving the problem I'd like to see something like this: ``` private void btnSendEmails_OnClick() { var taskId = AsyncTask.Run( () => Send100000EmailsAndWaitForReplies() ); // Store taskId for future task execution status checking. } ``` And this method will be executed for some way outside the w3wp.exe process within a special enveronment. Does anybody know a framework/toolset for resolving this kind of issues? **Update:** The emails sending method is only an example of what I mean. In fact, I could have a lot of functionality need to be executed outside the asp.net working process. E.g. this point is very important for an application which aggregates data from a couple of 3rd party services, do something with it and send it back to another service.
1. [QueueBackgroundWorkItem](http://blogs.msdn.com/b/webdev/archive/2014/06/04/queuebackgroundworkitem-to-reliably-schedule-and-run-long-background-process-in-asp-net.aspx) My sample shows sending email. 2. [HangFire](http://hangfire.io/) Open source project works on shared hosting. 3. On Azure, you can use [WebJobs](http://www.asp.net/aspnet/overview/developing-apps-with-windows-azure/azure-webjobs-recommended-resources). 4. On Azure, [Cloud services](http://azure.microsoft.com/en-us/documentation/articles/cloud-services-dotnet-get-started/)
118,272
<p>(Java question)</p> <p>If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class?</p> <p>How can I avoid this? </p> <p>Here is an example:</p> <pre><code>public class Outer { private Other o; private Inner i; public Outer() { o = new Other(); i = new Inner() { public void doSomething() { o.foo(); } }; } } </code></pre>
[ { "answer_id": 118317, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 0, "selected": false, "text": "<p>The syntax you're using in the example is a little off there is no declaration of the class or interface Inner. But there...
2008/09/22
[ "https://Stackoverflow.com/questions/118272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18445/" ]
(Java question) If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class? How can I avoid this? Here is an example: ``` public class Outer { private Other o; private Inner i; public Outer() { o = new Other(); i = new Inner() { public void doSomething() { o.foo(); } }; } } ```
**Static vs instance class:** If you declare the inner class as static then the instances of the inner class doesn't have any reference to the outer class. If it's not satic then your inner object efectivelly points to the outer object that created it (it has an implicit reference, in fact, if you use reflection over its constructors you'll see an extra parameter for receiving the outer instance). **Inner instance points outer instance:** Circular reference is in case each instance points the other one. A lot of times you use inner classes for elegantly implementing some interface and accessing private fields while not implementing the interface with the outer class. It does mean inner instance points outer instance but doesn't mean the opposite. Not necesary a circular reference. **Closing the circle:** Anyway there's nothing wrong with circular referencing in Java. Objects work nicely and when they're not more referenced they're garbage collected. It doesn't matter if they point each other.
118,280
<p>I thought I had seen a bug report about this on the jQuery site, but now I cannot find it. I'm trying to resize a dialog in IE6. But when the element is resized, the content and title bar don't resize down. They will resize up if the dialog is made larger, however. The result is that the close button ends up being cut off and the content is clipped if the user resize the dialog to be smaller. </p> <p>I've tried handling the resizeStop event and manually resizing the content and titlebar, but this can gave me weird results. The sizes and positions of elements in the content area were still off. Also, even though I resize the title bar, the close button still doesn't move back into view. Any ideas? If this is a bug in jQuery-ui, does anyone know a good workaround?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Example of IE6 resize issue&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="http://ui.jquery.com/repository/latest/themes/flora/flora.all.css" /&gt; &lt;script src="http://www.google.com/jsapi"&gt;&lt;/script&gt; &lt;script&gt; google.load("jquery", "1"); google.load("jqueryui", "1"); google.setOnLoadCallback( function() { $(document).ready(function() { $("#main-dialog").dialog(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="main-dialog"&gt; This is just some simple content that will fill the dialog. This example is sufficient to reproduce the problem in IE6. It does not seem to occur in IE7 or FF. I haven't tried with Opera or Safari. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 120050, "author": "Dave Richardson", "author_id": 3392, "author_profile": "https://Stackoverflow.com/users/3392", "pm_score": 0, "selected": false, "text": "<p>The css may be a factor. Could you change your example so we can see your stylesheet? I've updated the example so...
2008/09/22
[ "https://Stackoverflow.com/questions/118280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6118/" ]
I thought I had seen a bug report about this on the jQuery site, but now I cannot find it. I'm trying to resize a dialog in IE6. But when the element is resized, the content and title bar don't resize down. They will resize up if the dialog is made larger, however. The result is that the close button ends up being cut off and the content is clipped if the user resize the dialog to be smaller. I've tried handling the resizeStop event and manually resizing the content and titlebar, but this can gave me weird results. The sizes and positions of elements in the content area were still off. Also, even though I resize the title bar, the close button still doesn't move back into view. Any ideas? If this is a bug in jQuery-ui, does anyone know a good workaround? ``` <html> <head> <title>Example of IE6 resize issue</title> <link rel="stylesheet" type="text/css" href="http://ui.jquery.com/repository/latest/themes/flora/flora.all.css" /> <script src="http://www.google.com/jsapi"></script> <script> google.load("jquery", "1"); google.load("jqueryui", "1"); google.setOnLoadCallback( function() { $(document).ready(function() { $("#main-dialog").dialog(); }); }); </script> </head> <body> <div id="main-dialog"> This is just some simple content that will fill the dialog. This example is sufficient to reproduce the problem in IE6. It does not seem to occur in IE7 or FF. I haven't tried with Opera or Safari. </div> </body> </html> ```
I was able to come up with a solution. If you add the style **overflow: hidden** to the dialog container div element (which has the css class .ui-dialog-container applied to it), then everything resizes correctly. All I did was add a css rule as follows to the flora theme: ``` .ui-dialog .ui-dialog-container { overflow: hidden; } ``` It could also be corrected by executing the following: ``` if ($.browser.msie && $.browser.version == 6) { $(".ui-dialog-container").css({ overflow: 'hidden' }); } ``` This corrected the issue I was seeing under IE6 and has not introduced any problems in FireFox.
118,289
<p>I have a string with possible command line arguments (using an Read-Eval-Print-Loop program) and I want it to be parsed similar to the command line arguments when passed to Getopt::Long.</p> <p>To elaborate:</p> <p>I have a string</p> <pre><code>$str = '--infile /tmp/infile_location --outfile /tmp/outfile' </code></pre> <p>I want it to be parsed by GetOptions so that it is easier for me to add new options.</p> <p>One workaround I could think of is to split the string on whitespace and replace @ARGV with new array and then call GetOptions. something like ...</p> <pre><code>my @arg_arr = split (/\s/, $input_line); # This is done so that GetOptions reads these new arguments @ARGV = @arg_arr; print "ARGV is : @ARGV\n"; GetOptions ( 'infile=s' =&gt; \$infile, 'outfile=s' =&gt; \$outfile ); </code></pre> <p>Is there any good/better way?</p>
[ { "answer_id": 118339, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 3, "selected": false, "text": "<p>Instead of splitting on whitespace, use the built-in glob function. In addition to splitting on whitespace, that wil...
2008/09/22
[ "https://Stackoverflow.com/questions/118289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4406/" ]
I have a string with possible command line arguments (using an Read-Eval-Print-Loop program) and I want it to be parsed similar to the command line arguments when passed to Getopt::Long. To elaborate: I have a string ``` $str = '--infile /tmp/infile_location --outfile /tmp/outfile' ``` I want it to be parsed by GetOptions so that it is easier for me to add new options. One workaround I could think of is to split the string on whitespace and replace @ARGV with new array and then call GetOptions. something like ... ``` my @arg_arr = split (/\s/, $input_line); # This is done so that GetOptions reads these new arguments @ARGV = @arg_arr; print "ARGV is : @ARGV\n"; GetOptions ( 'infile=s' => \$infile, 'outfile=s' => \$outfile ); ``` Is there any good/better way?
Check out the section [parsing options from an arbitrary string](http://perldoc.perl.org/Getopt/Long.html#Parsing-options-from-an-arbitrary-string) in the [man page for Getopt::Long](http://perldoc.perl.org/Getopt/Long.html), I think it does exactly what you're looking for.
118,292
<p>So I was writing some code today that basically looks like this:</p> <pre><code>string returnString = s.Replace("!", " ") .Replace("@", " ") .Replace("#", " ") .Replace("$", " ") .Replace("%", " ") .Replace("^", " ") .Replace("*", " ") .Replace("_", " ") .Replace("+", " ") .Replace("=", " ") .Replace("\", " ") </code></pre> <p>Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the <code>Replace()</code> function?</p>
[ { "answer_id": 118306, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "<p>You can use <strong>Regex.Replace()</strong>. All of the characters can be placed between square brackets, which match...
2008/09/22
[ "https://Stackoverflow.com/questions/118292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
So I was writing some code today that basically looks like this: ``` string returnString = s.Replace("!", " ") .Replace("@", " ") .Replace("#", " ") .Replace("$", " ") .Replace("%", " ") .Replace("^", " ") .Replace("*", " ") .Replace("_", " ") .Replace("+", " ") .Replace("=", " ") .Replace("\", " ") ``` Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the `Replace()` function?
You can use **Regex.Replace()**. All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first parameter is the input string and the last parameter is the replacement string. ``` var returnString = Regex.Replace(s,@"[!@#\$%\^*_\+=\\]"," "); ```
118,305
<p>How can UTF-8 strings (i.e. 8-bit string) be converted to/from XML-compatible 7-bit strings (i.e. printable ASCII with numeric entities)?</p> <p>i.e. an <code>encode()</code> function such that:</p> <pre><code>encode("“£”") -&gt; "&amp;#8220;&amp;#163;&amp;#8221;" </code></pre> <p><code>decode()</code> would also be useful:</p> <pre><code>decode("&amp;#8220;&amp;#163;&amp;#8221;") -&gt; "“£”" </code></pre> <p>PHP's <code>htmlenties()</code>/<code>html_entity_decode()</code> pair does not do the right thing:</p> <pre><code>htmlentities(html_entity_decode("&amp;#8220;&amp;#163;&amp;#8221;")) -&gt; "&amp;amp;#8220;&amp;pound;&amp;amp;#8221;" </code></pre> <p>Laboriously specifying types helps a little, but still returns XML-incompatible named entities, not numeric ones:</p> <pre><code>htmlentities(html_entity_decode("&amp;#8220;&amp;#163;&amp;#8221;", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") -&gt; "&amp;ldquo;&amp;pound;&amp;rdquo;" </code></pre>
[ { "answer_id": 193057, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 0, "selected": false, "text": "<p>It's a bit of a workaround, but I read a bit about <code>iconv()</code> and i don't think it'll give you numeric entities ...
2008/09/22
[ "https://Stackoverflow.com/questions/118305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11543/" ]
How can UTF-8 strings (i.e. 8-bit string) be converted to/from XML-compatible 7-bit strings (i.e. printable ASCII with numeric entities)? i.e. an `encode()` function such that: ``` encode("“£”") -> "&#8220;&#163;&#8221;" ``` `decode()` would also be useful: ``` decode("&#8220;&#163;&#8221;") -> "“£”" ``` PHP's `htmlenties()`/`html_entity_decode()` pair does not do the right thing: ``` htmlentities(html_entity_decode("&#8220;&#163;&#8221;")) -> "&amp;#8220;&pound;&amp;#8221;" ``` Laboriously specifying types helps a little, but still returns XML-incompatible named entities, not numeric ones: ``` htmlentities(html_entity_decode("&#8220;&#163;&#8221;", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") -> "&ldquo;&pound;&rdquo;" ```
[`mb_encode_numericentity`](http://php.net/manual/en/function.mb-encode-numericentity.php) does that exactly.
118,307
<p>Tools like 'ps' and 'top' report various kinds of memory usages, such as the VM size and the Resident Set Size. However, none of those are the "real" memory usage:</p> <ul> <li>Program code is shared between multiple instances of the same program.</li> <li>Shared library program code is shared between all processes that use that library.</li> <li>Some apps fork off processes and share memory with them (e.g. via shared memory segments).</li> <li>The virtual memory system makes the VM size report pretty much useless.</li> <li>RSS is 0 when a process is swapped out, making it not very useful.</li> <li>Etc etc.</li> </ul> <p>I've found that the private dirty RSS, as reported by Linux, is the closest thing to the "real" memory usage. This can be obtained by summing all <code>Private_Dirty</code> values in <code>/proc/somepid/smaps</code>.</p> <p>However, do other operating systems provide similar functionality? If not, what are the alternatives? In particular, I'm interested in FreeBSD and OS X.</p>
[ { "answer_id": 118726, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 3, "selected": false, "text": "<p>Top knows how to do this. It shows VIRT, RES and SHR by default on Debian Linux. VIRT = SWAP + RES. RES = CODE + DATA. ...
2008/09/22
[ "https://Stackoverflow.com/questions/118307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20816/" ]
Tools like 'ps' and 'top' report various kinds of memory usages, such as the VM size and the Resident Set Size. However, none of those are the "real" memory usage: * Program code is shared between multiple instances of the same program. * Shared library program code is shared between all processes that use that library. * Some apps fork off processes and share memory with them (e.g. via shared memory segments). * The virtual memory system makes the VM size report pretty much useless. * RSS is 0 when a process is swapped out, making it not very useful. * Etc etc. I've found that the private dirty RSS, as reported by Linux, is the closest thing to the "real" memory usage. This can be obtained by summing all `Private_Dirty` values in `/proc/somepid/smaps`. However, do other operating systems provide similar functionality? If not, what are the alternatives? In particular, I'm interested in FreeBSD and OS X.
On OSX the Activity Monitor gives you actually a very good guess. Private memory is for sure memory that is only used by your application. E.g. stack memory and all memory dynamically reserved using malloc() and comparable functions/methods (alloc method for Objective-C) is private memory. If you fork, private memory will be shared with you child, but marked copy-on-write. That means as long as a page is not modified by either process (parent or child) it is shared between them. As soon as either process modifies any page, this page is copied before it is modified. Even while this memory is shared with fork children (and it can **only** be shared with fork children), it is still shown as "private" memory, because in the worst case, every page of it will get modified (sooner or later) and then it is again private to each process again. Shared memory is either memory that is currently shared (the same pages are visible in the virtual process space of different processes) or that is likely to become shared in the future (e.g. read-only memory, since there is no reason for not sharing read-only memory). At least that's how I read the source code of some command line tools from Apple. So if you share memory between processes using mmap (or a comparable call that maps the same memory into multiple processes), this would be shared memory. However the executable code itself is also shared memory, since if another instance of your application is started there is no reason why it may not share the code already loaded in memory (executable code pages are read-only by default, unless you are running your app in a debugger). Thus shared memory is really memory used by your application, just like private one, but it might additionally be shared with another process (or it might not, but why would it not count towards your application if it was shared?) Real memory is the amount of RAM currently "assigned" to your process, no matter if private or shared. This can be exactly the sum of private and shared, but usually it is not. Your process might have more memory assigned to it than it currently needs (this speeds up requests for more memory in the future), but that is no loss to the system. If another process needs memory and no free memory is available, before the system starts swapping, it will take that extra memory away from your process and assign it another process (which is a fast and painless operation); therefor your next malloc call might be somewhat slower. Real memory can also be smaller than private and physical memory; this is because if your process requests memory from the system, it will only receive "virtual memory". This virtual memory is not linked to any real memory pages as long as you don't use it (so malloc 10 MB of memory, use only one byte of it, your process will get only a single page, 4096 byte, of memory assigned - the rest is only assigned if you actually ever need it). Further memory that is swapped may not count towards real memory either (not sure about this), but it will count towards shared and private memory. Virtual memory is the sum of all address blocks that are consider valid in your apps process space. These addresses might be linked to physical memory (that is again private or shared), or they might not, but in that case they will be linked to physical memory as soon as you use the address. Accessing memory addresses outside of the known addresses will cause a SIGBUS and your app will crash. When memory is swapped, the virtual address space for this memory remains valid and accessing those addresses causes memory to be swapped back in. **Conclusion:** If your app does not explicitly or implicitly use shared memory, private memory is the amount of memory your app needs because of the stack size (or sizes if multithreaded) and because of the malloc() calls you made for dynamic memory. You don't have to care a lot for shared or real memory in that case. If your app uses shared memory, and this includes a graphical UI, where memory is shared between your application and the WindowServer for example, then you might have a look at shared memory as well. A very high shared memory number may mean you have too many graphical resources loaded in memory at the moment. Real memory is of little interest for app development. If it is bigger than the sum of shared and private, then this means nothing other than that the system is lazy at taken memory away from your process. If it is smaller, then your process has requested more memory than it actually needed, which is not bad either, since as long as you don't use all of the requested memory, you are not "stealing" memory from the system. If it is much smaller than the sum of shared and private, you may only consider to request less memory where possible, as you are a bit over-requesting memory (again, this is not bad, but it tells me that your code is not optimized for minimal memory usage and if it is cross platform, other platforms may not have such a sophisticated memory handling, so you may prefer to alloc many small blocks instead of a few big ones for example, or free memory a lot sooner, and so on). If you are still not happy with all that information, you can get even more information. Open a terminal and run: ``` sudo vmmap <pid> ``` where is the process ID of your process. This will show you statistics for **EVERY** block of memory in your process space with start and end address. It will also tell you where this memory came from (A mapped file? Stack memory? Malloc'ed memory? A \_\_DATA or \_\_TEXT section of your executable?), how big it is in KB, the access rights and whether it is private, shared or copy-on-write. If it is mapped from a file, it will even give you the path to the file. If you want only "actual" RAM usage, use ``` sudo vmmap -resident <pid> ``` Now it will show for every memory block how big the memory block is virtually and how much of it is really currently present in physical memory. At the end of each dump is also an overview table with the sums of different memory types. This table looks like this for Firefox right now on my system: ``` REGION TYPE [ VIRTUAL/RESIDENT] =========== [ =======/========] ATS (font support) [ 33.8M/ 2496K] CG backing stores [ 5588K/ 5460K] CG image [ 20K/ 20K] CG raster data [ 576K/ 576K] CG shared images [ 2572K/ 2404K] Carbon [ 1516K/ 1516K] CoreGraphics [ 8K/ 8K] IOKit [ 256.0M/ 0K] MALLOC [ 256.9M/ 247.2M] Memory tag=240 [ 4K/ 4K] Memory tag=242 [ 12K/ 12K] Memory tag=243 [ 8K/ 8K] Memory tag=249 [ 156K/ 76K] STACK GUARD [ 101.2M/ 9908K] Stack [ 14.0M/ 248K] VM_ALLOCATE [ 25.9M/ 25.6M] __DATA [ 6752K/ 3808K] __DATA/__OBJC [ 28K/ 28K] __IMAGE [ 1240K/ 112K] __IMPORT [ 104K/ 104K] __LINKEDIT [ 30.7M/ 3184K] __OBJC [ 1388K/ 1336K] __OBJC/__DATA [ 72K/ 72K] __PAGEZERO [ 4K/ 0K] __TEXT [ 108.6M/ 63.5M] __UNICODE [ 536K/ 512K] mapped file [ 118.8M/ 50.8M] shared memory [ 300K/ 276K] shared pmap [ 6396K/ 3120K] ``` What does this tell us? E.g. the Firefox binary and all library it loads have 108 MB data together in their \_\_TEXT sections, but currently only 63 MB of those are currently resident in memory. The font support (ATS) needs 33 MB, but only about 2.5 MB are really in memory. It uses a bit over 5 MB CG backing stores, CG = Core Graphics, those are most likely window contents, buttons, images and other data that is cached for fast drawing. It has requested 256 MB via malloc calls and currently 247 MB are really in mapped to memory pages. It has 14 MB space reserved for stacks, but only 248 KB stack space is really in use right now. vmmap also has a good summary above the table ``` ReadOnly portion of Libraries: Total=139.3M resident=66.6M(48%) swapped_out_or_unallocated=72.7M(52%) Writable regions: Total=595.4M written=201.8M(34%) resident=283.1M(48%) swapped_out=0K(0%) unallocated=312.3M(52%) ``` And this shows an interesting aspect of the OS X: For read only memory that comes from libraries, it plays no role if it is swapped out or simply unallocated; there is only resident and not resident. For writable memory this makes a difference (in my case 52% of all requested memory has never been used and is such unallocated, 0% of memory has been swapped out to disk). The reason for that is simple: Read-only memory from mapped files is not swapped. If the memory is needed by the system, the current pages are simply dropped from the process, as the memory is already "swapped". It consisted only of content mapped directly from files and this content can be remapped whenever needed, as the files are still there. That way this memory won't waste space in the swap file either. Only writable memory must first be swapped to file before it is dropped, as its content wasn't stored on disk before.
118,341
<p>I have a Linq to objects statement</p> <pre><code> var confirm = from l in lines.Lines where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber) select l; </code></pre> <p>The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext()</p> <p>If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over?</p> <p><strong>EDIT</strong> When I said <em>I know for a fact that there are no null objects</em> it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really'</p> <p>LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool</p>
[ { "answer_id": 118347, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 6, "selected": true, "text": "<p>I'm not sure if it's possible to debug from VS, but I find <a href=\"http://www.linqpad.net/\" rel=\"noreferrer\">LINQPad</a...
2008/09/23
[ "https://Stackoverflow.com/questions/118341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
I have a Linq to objects statement ``` var confirm = from l in lines.Lines where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber) select l; ``` The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext() If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over? **EDIT** When I said *I know for a fact that there are no null objects* it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really' LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool
I'm not sure if it's possible to debug from VS, but I find [LINQPad](http://www.linqpad.net/) to be quite useful. It'll let you dump the results of each part of the LINQ query.
118,342
<p>I am aware of this command: <code>cvs log -N -w&lt;userid&gt; -d"1 day ago"</code></p> <p>Unfortunately this generates a formatted report with lots of newlines in it, such that the file-path, the file-version, and the comment-text are all on separate lines. Therefore it is difficult to scan it for all occurrences of comment text, (eg, grep), and correlate the matches to file/version.</p> <p>(Note that the log output would be perfectly acceptable, if only cvs could perform the filtering natively.)</p> <p>EDIT: Sample output. A block of text like this is reported for each repository file:</p> <pre> RCS file: /data/cvs/dps/build.xml,v Working file: build.xml head: 1.49 branch: locks: strict access list: keyword substitution: kv total revisions: 57; selected revisions: 1 description: ---------------------------- revision 1.48 date: 2008/07/09 17:17:32; author: noec; state: Exp; lines: +2 -2 Fixed src.jar references ---------------------------- revision 1.47 date: 2008/07/03 13:13:14; author: noec; state: Exp; lines: +1 -1 Fixed common-src.jar reference. ============================================================================= </pre>
[ { "answer_id": 118372, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>This might be way overkill, but you could use <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-cvsimport....
2008/09/23
[ "https://Stackoverflow.com/questions/118342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
I am aware of this command: `cvs log -N -w<userid> -d"1 day ago"` Unfortunately this generates a formatted report with lots of newlines in it, such that the file-path, the file-version, and the comment-text are all on separate lines. Therefore it is difficult to scan it for all occurrences of comment text, (eg, grep), and correlate the matches to file/version. (Note that the log output would be perfectly acceptable, if only cvs could perform the filtering natively.) EDIT: Sample output. A block of text like this is reported for each repository file: ``` RCS file: /data/cvs/dps/build.xml,v Working file: build.xml head: 1.49 branch: locks: strict access list: keyword substitution: kv total revisions: 57; selected revisions: 1 description: ---------------------------- revision 1.48 date: 2008/07/09 17:17:32; author: noec; state: Exp; lines: +2 -2 Fixed src.jar references ---------------------------- revision 1.47 date: 2008/07/03 13:13:14; author: noec; state: Exp; lines: +1 -1 Fixed common-src.jar reference. ============================================================================= ```
The `-w` options seems to work better with the `-S` option. Otherwise there are additional results which don't seem related to the userid. Perhaps someone can explain it. ``` cvs log -N -S -w<userid> -d"1 day ago" ``` With that I have been getting reasonable success piping it to grep: ``` cvs log -N -S -w<userid> -d"1 day ago" | grep -B14 "some text" > afile ``` I'm redirecting output to a file since the cvs log is noisy and I'm not sure how to make it quiet. I suppose an alternative is to redirect the stderr to `/dev/null`.
118,343
<p>Ruby on Rails has <a href="http://wiki.rubyonrails.com/rails/pages/Timestamping" rel="nofollow noreferrer">magic timestamping fields</a> that are automatically updated when a record is created or updated. I'm trying to find similar functionality in Entity Framework. I've considered database triggers and a SavingChanges event handler. Is there a more obvious method I'm overlooking?</p>
[ { "answer_id": 118372, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>This might be way overkill, but you could use <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-cvsimport....
2008/09/23
[ "https://Stackoverflow.com/questions/118343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453303/" ]
Ruby on Rails has [magic timestamping fields](http://wiki.rubyonrails.com/rails/pages/Timestamping) that are automatically updated when a record is created or updated. I'm trying to find similar functionality in Entity Framework. I've considered database triggers and a SavingChanges event handler. Is there a more obvious method I'm overlooking?
The `-w` options seems to work better with the `-S` option. Otherwise there are additional results which don't seem related to the userid. Perhaps someone can explain it. ``` cvs log -N -S -w<userid> -d"1 day ago" ``` With that I have been getting reasonable success piping it to grep: ``` cvs log -N -S -w<userid> -d"1 day ago" | grep -B14 "some text" > afile ``` I'm redirecting output to a file since the cvs log is noisy and I'm not sure how to make it quiet. I suppose an alternative is to redirect the stderr to `/dev/null`.
118,370
<p>This came up in <a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
[ { "answer_id": 118395, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 8, "selected": true, "text": "<p><code>Ellipsis</code>, or <code>...</code> is not a hidden feature, it's just a constant. It's quite different to, say, j...
2008/09/23
[ "https://Stackoverflow.com/questions/118370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15677/" ]
This came up in [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works.
`Ellipsis`, or `...` is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it. So the syntax for it depends entirely on you, or someone else, having written code to understand it. Numpy uses it, as stated in the [documentation](http://wiki.scipy.org/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb). Some examples [here](http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c). In your own class, you'd use it like this: ``` >>> class TestEllipsis(object): ... def __getitem__(self, item): ... if item is Ellipsis: ... return "Returning all items" ... else: ... return "return %r items" % item ... >>> x = TestEllipsis() >>> print x[2] return 2 items >>> print x[...] Returning all items ``` Of course, there is the [python documentation](https://docs.python.org/library/constants.html#Ellipsis "Ellipsis"), and [language reference](https://docs.python.org/reference/expressions.html#grammar-token-slicing). But those aren't very helpful.
118,371
<p>When a class field is accessed via a getter method by multiple threads, how do you maintain thread safety? Is the synchronized keyword sufficient?</p> <p>Is this safe:</p> <pre><code>public class SomeClass { private int val; public synchronized int getVal() { return val; } private void setVal(int val) { this.val = val; } } </code></pre> <p>or does the setter introduce further complications?</p>
[ { "answer_id": 118377, "author": "Jacob Schoen", "author_id": 3340, "author_profile": "https://Stackoverflow.com/users/3340", "pm_score": 2, "selected": false, "text": "<p>From my understanding you should use synchronized on both the getter and the setter methods, and that is sufficient....
2008/09/23
[ "https://Stackoverflow.com/questions/118371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
When a class field is accessed via a getter method by multiple threads, how do you maintain thread safety? Is the synchronized keyword sufficient? Is this safe: ``` public class SomeClass { private int val; public synchronized int getVal() { return val; } private void setVal(int val) { this.val = val; } } ``` or does the setter introduce further complications?
If you use 'synchronized' on the setter here too, this code is threadsafe. However it may not be sufficiently granular; if you have 20 getters and setters and they're all synchronized, you may be creating a synchronization bottleneck. In this specific instance, with a single int variable, then eliminating the 'synchronized' and marking the int field 'volatile' will also ensure visibility (each thread will see the latest value of 'val' when calling the getter) but it may not be synchronized enough for your needs. For example, expecting ``` int old = someThing.getVal(); if (old == 1) { someThing.setVal(2); } ``` to set val to 2 if and only if it's already 1 is incorrect. For this you need an external lock, or some atomic compare-and-set method. I strongly suggest you read *Java Concurrency In Practice* by Brian Goetz *et al*, it has the best coverage of Java's concurrency constructs.
118,415
<p>My database is located in e.g. california. My user table has all the user's timezone e.g. -0700 UTC </p> <p>How can I adjust the time from my database server whenever I display a date to the user who lives in e.g. new york? UTC/GMT -4 hours</p>
[ { "answer_id": 118432, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>You should store your data in UTC format and showing it in local timezone format.</p>\n\n<pre><code>DateTime.ToUniversalTime(...
2008/09/23
[ "https://Stackoverflow.com/questions/118415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
My database is located in e.g. california. My user table has all the user's timezone e.g. -0700 UTC How can I adjust the time from my database server whenever I display a date to the user who lives in e.g. new york? UTC/GMT -4 hours
You should store your data in UTC format and showing it in local timezone format. ``` DateTime.ToUniversalTime() -> server; DateTime.ToLocalTime() -> client ``` You can adjust date/time using AddXXX methods group, but it can be error prone. .NET has support for time zones in [System.TimeZoneInfo](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx) class.
118,423
<p>I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)?</p> <p>The reason why I'm asking is that I'm going to be trying out CodeIgniter, and I would like to use it for multiple projects. I would rather not clutter up my machine's DocumentRoot with each one. Suggestions on how to do database migrations are also welcome.</p> <hr /> <p>Thank you for your responses so far. I should clarify that I'm on Mac OS X. It looks like WAMP is Windows-only. Also, XAMPP looks like a great way to install Apache and many other web tools, but I don't see a way of loading up an instance to serve up a project directory. Mac OS X has both Apache and PHP installed - I'm just looking for a way to get it to serve up a project on a non-standard port.</p> <p>I just found <a href="http://www.mamp.info/en/mamp-pro/" rel="nofollow noreferrer">MAMP Pro</a> which does what I want, but a more minimalist approach would be better if it's possible. Does anyone have a <code>httpd.conf</code> file that can be edited and dropped into a project directory?</p> <p>Also, sorry that I just threw in that database migration question. What I'm hoping to find is something that will enable me to push schema changes onto a live server without losing the existing data. I suspect that this is difficult and highly dependent on environmental factors.</p>
[ { "answer_id": 118450, "author": "phloopy", "author_id": 8507, "author_profile": "https://Stackoverflow.com/users/8507", "pm_score": 0, "selected": false, "text": "<p>You could use a low up front setup package such as <a href=\"http://www.apachefriends.org/en/index.html\" rel=\"nofollow ...
2008/09/23
[ "https://Stackoverflow.com/questions/118423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)? The reason why I'm asking is that I'm going to be trying out CodeIgniter, and I would like to use it for multiple projects. I would rather not clutter up my machine's DocumentRoot with each one. Suggestions on how to do database migrations are also welcome. --- Thank you for your responses so far. I should clarify that I'm on Mac OS X. It looks like WAMP is Windows-only. Also, XAMPP looks like a great way to install Apache and many other web tools, but I don't see a way of loading up an instance to serve up a project directory. Mac OS X has both Apache and PHP installed - I'm just looking for a way to get it to serve up a project on a non-standard port. I just found [MAMP Pro](http://www.mamp.info/en/mamp-pro/) which does what I want, but a more minimalist approach would be better if it's possible. Does anyone have a `httpd.conf` file that can be edited and dropped into a project directory? Also, sorry that I just threw in that database migration question. What I'm hoping to find is something that will enable me to push schema changes onto a live server without losing the existing data. I suspect that this is difficult and highly dependent on environmental factors.
Your Mac comes with both an Apache Web Server and a build of PHP. It's one of the big reasons the platform is well loved by web developers. Since you're using Code Igniter, you'll want PHP 5, which is the default version of PHP shipped with 10.5. If you're on a previous version of the OS hop on over to [entropy.ch](http://www.entropy.ch/home/) and install the provided PHP5 package. Next, you'll want to turn Apache on. In the sharing preferences panel, turn on personal web sharing. This will start up apache on your local machine. Next, you'll want to setup some fake development URLs to use for your sites. Long standing tradition was that we'd use the fake TLD .dev for this (ex. stackoverflow.dev). However, `.dev` is now an actual TLD so you probably don't want to do this -- `.localhost` seems like an emerging defacto standard. Edit your /etc/hosts file and add the following lines ``` 127.0.0.1 www.example.localhost 127.0.0.1 example.localhost ``` This points the above URLs at your local machine. The last step is configuring apache. Specifically, enabling named virtual hosting, enabling PHP and setting up a few virtual hosts. If you used the entropy PHP package, enabling PHP will already be done. If not, you'll need to edit your http.conf file as described [here](http://foundationphp.com/tutorials/php_leopard.php). Basically, you're uncommenting the lines that will load the PHP module. Whenever you make a change to your apache config, you'll need to restart apache for the changes to take effect. At a terminal window, type the following command ``` sudo apachectl graceful ``` This will gracefully restart apache. If you've made a syntax error in the config file apache won't restart. You can highlight config problems with ``` sudo apachectl configtest ``` So,with PHP enabled, you'll want to turn on NamedVirtualHosts. This will let apache respond to multiple URLs. Look for the following (or similar) line in your http.conf file and uncomment it. ``` #NameVirtualHost * ``` Finally, you'll need to tell apache where it should look for the files for your new virtual hosts. You can do so by adding the following to your http.conf file. NOTE: I find it's a good best practice to break out config rules like this into a separate file and use the include directive to include your changes. This will stop any automatic updates from wiping out your changes. ``` <VirtualHost *> DocumentRoot /Users/username/Sites/example.localhost ServerName example.localhost ServerAlias www.example.localhost </VirtualHost> ``` You can specify any folder as the DocumentRoot, but I find it convenient to use your personal Sites folder, as it's already been configured with the correct permissions to include files.
118,443
<p>I have an application that tracks high scores in a game. </p> <p>I have a <strong>user_scores</strong> table that maps a user_id to a score.</p> <p>I need to return the 5 highest scores, but only 1 high score for any <em>specific</em> user.</p> <p>So if user X has the 5 highest scores on a purely numerical basis, I simply return the highest one and then the next 4 user scores.</p> <p>I have tried to use:</p> <pre><code>SELECT user_id, score FROM user_scores ORDER BY score DESC GROUP BY user_id LIMIT 5 </code></pre> <p>But it seems that MySQL drops any user_id with more than 1 score. </p>
[ { "answer_id": 118446, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>You can't group by without a summary-function (SUM, COUNT, etc.)</p>\n\n<p>The GROUP BY clause says how to group the SUM...
2008/09/23
[ "https://Stackoverflow.com/questions/118443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14971/" ]
I have an application that tracks high scores in a game. I have a **user\_scores** table that maps a user\_id to a score. I need to return the 5 highest scores, but only 1 high score for any *specific* user. So if user X has the 5 highest scores on a purely numerical basis, I simply return the highest one and then the next 4 user scores. I have tried to use: ``` SELECT user_id, score FROM user_scores ORDER BY score DESC GROUP BY user_id LIMIT 5 ``` But it seems that MySQL drops any user\_id with more than 1 score.
This should work: ``` SELECT user_id, MAX(score) FROM user_scores GROUP BY user_id ORDER BY MAX(score) DESC LIMIT 5 ```
118,458
<p>Along the lines of my previous <a href="https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">question</a>, how can i join a list of strings into a string such that values get quoted cleanly. Something like:</p> <pre><code>['a', 'one "two" three', 'foo, bar', """both"'"""] </code></pre> <p>into:</p> <pre><code>a, 'one "two" three', "foo, bar", "both\"'" </code></pre> <p>I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.</p>
[ { "answer_id": 118462, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 4, "selected": true, "text": "<p>Using the <code>csv</code> module you can do that way:</p>\n\n<pre><code>import csv\nwriter = csv.writer(open(\"some.csv\...
2008/09/23
[ "https://Stackoverflow.com/questions/118458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
Along the lines of my previous [question](https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat), how can i join a list of strings into a string such that values get quoted cleanly. Something like: ``` ['a', 'one "two" three', 'foo, bar', """both"'"""] ``` into: ``` a, 'one "two" three', "foo, bar", "both\"'" ``` I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.
Using the `csv` module you can do that way: ``` import csv writer = csv.writer(open("some.csv", "wb")) writer.writerow(the_list) ``` If you need a string just use `StringIO` instance as a file: ``` f = StringIO.StringIO() writer = csv.writer(f) writer.writerow(the_list) print f.getvalue() ``` The output: `a,"one ""two"" three","foo, bar","both""'"` `csv` will write in a way it can read back later. You can fine-tune its output by defining a `dialect`, just set `quotechar`, `escapechar`, etc, as needed: ``` class SomeDialect(csv.excel): delimiter = ',' quotechar = '"' escapechar = "\\" doublequote = False lineterminator = '\n' quoting = csv.QUOTE_MINIMAL f = cStringIO.StringIO() writer = csv.writer(f, dialect=SomeDialect) writer.writerow(the_list) print f.getvalue() ``` The output: `a,one \"two\" three,"foo, bar",both\"'` The same dialect can be used with csv module to read the string back later to a list.
118,474
<p>Has anybody established a good naming convention for action in MVC? I was specifically looking at ASP.net MVC but it is a general question. For instance I have an action which displays the login screen (Login) and one which process the login request from that page (LoginTest). I'm not keen on the names and I have a lot of the applicaiton left to write. </p>
[ { "answer_id": 118495, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>The builtin Django actions suffix _done. So LoginDone would be the page that processes Login (in ASP.NET MVC camel ca...
2008/09/23
[ "https://Stackoverflow.com/questions/118474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
Has anybody established a good naming convention for action in MVC? I was specifically looking at ASP.net MVC but it is a general question. For instance I have an action which displays the login screen (Login) and one which process the login request from that page (LoginTest). I'm not keen on the names and I have a lot of the applicaiton left to write.
Rob Conery at MS suggested some useful RESTful style naming for actions. > > > ``` > * Index - the main "landing" page. This is also the default endpoint. > * List - a list of whatever "thing" you're showing them - like a list of Products. > * Show - a particular item of whatever "thing" you're showing them (like a Product) > * Edit - an edit page for the "thing" > * New - a create page for the "thing" > * Create - creates a new "thing" (and saves it if you're using a DB) > * Update - updates the "thing" > * Delete - deletes the "thing" > > ``` > > results in URLs along the lines of (for a forum) > > > ``` > * http://mysite/forum/group/list - shows all the groups in my forum > * http://mysite/forum/forums/show/1 - shows all the topics in forum id=1 > * http://mysite/forums/topic/show/20 - shows all the posts for topic id=20 > > ``` > > [Rob Conery on RESTful Architecture for MVC](http://blog.wekeroad.com/2007/12/06/aspnet-mvc-using-restful-architecture/)
118,487
<p>Sorry the title isn't more help. I have a database of media-file URLs that came from two sources: </p> <p>(1) RSS feeds and (2) manual entries. </p> <p>I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table '<code>urls</code>' has columns <code>'url, feed_id, timestamp'</code>. </p> <p><code>feed_id=''</code> for any URL that was entered manually.</p> <p>How would I write the query? Remember, I want the ten most-recent urls, but only one from any single <code>feed_id</code>.</p>
[ { "answer_id": 118523, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 0, "selected": false, "text": "<p>You probably want a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/union.html\" rel=\"nofollow noreferrer\">union</a>. S...
2008/09/23
[ "https://Stackoverflow.com/questions/118487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17307/" ]
Sorry the title isn't more help. I have a database of media-file URLs that came from two sources: (1) RSS feeds and (2) manual entries. I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table '`urls`' has columns `'url, feed_id, timestamp'`. `feed_id=''` for any URL that was entered manually. How would I write the query? Remember, I want the ten most-recent urls, but only one from any single `feed_id`.
Assuming feed\_id = 0 is the manually entered stuff this does the trick: ``` select p.* from programs p left join ( select max(id) id1 from programs where feed_id <> 0 group by feed_id order by max(id) desc limit 10 ) t on id1 = id where id1 is not null or feed_id = 0 order by id desc limit 10; ``` It works cause the id column is constantly increasing, its also pretty speedy. t is a table alias. This was my original answer: ``` ( select feed_id, url, dt from feeds where feed_id = '' order by dt desc limit 10 ) union ( select feed_id, min(url), max(dt) from feeds where feed_id <> '' group by feed_id order by dt desc limit 10 ) order by dt desc limit 10 ```
118,490
<p>Can anyone recommend a cheap and good RTF control for .Net 1.1 Windows development. It needs to be able to do print/preview and some basic text formatting, fonts etc but nothing too advanced.</p> <p>Cheers</p> <p>Andreas</p>
[ { "answer_id": 118523, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 0, "selected": false, "text": "<p>You probably want a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/union.html\" rel=\"nofollow noreferrer\">union</a>. S...
2008/09/23
[ "https://Stackoverflow.com/questions/118490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can anyone recommend a cheap and good RTF control for .Net 1.1 Windows development. It needs to be able to do print/preview and some basic text formatting, fonts etc but nothing too advanced. Cheers Andreas
Assuming feed\_id = 0 is the manually entered stuff this does the trick: ``` select p.* from programs p left join ( select max(id) id1 from programs where feed_id <> 0 group by feed_id order by max(id) desc limit 10 ) t on id1 = id where id1 is not null or feed_id = 0 order by id desc limit 10; ``` It works cause the id column is constantly increasing, its also pretty speedy. t is a table alias. This was my original answer: ``` ( select feed_id, url, dt from feeds where feed_id = '' order by dt desc limit 10 ) union ( select feed_id, min(url), max(dt) from feeds where feed_id <> '' group by feed_id order by dt desc limit 10 ) order by dt desc limit 10 ```
118,501
<p>If I was, for example, going to <em>count</em> "activities" across many computers and show a rollup of that activity, what would the database look like to store the data? </p> <p>Simply this? Seems too simple. I'm overthinking this.</p> <pre><code>ACTIVITYID COUNT ---------- ----- </code></pre>
[ { "answer_id": 118568, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 0, "selected": false, "text": "<p>Yes, I'm afraid it's that simple, assuming you are only interested in the number of times each activity occurs. On...
2008/09/23
[ "https://Stackoverflow.com/questions/118501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6380/" ]
If I was, for example, going to *count* "activities" across many computers and show a rollup of that activity, what would the database look like to store the data? Simply this? Seems too simple. I'm overthinking this. ``` ACTIVITYID COUNT ---------- ----- ```
If the volume is not going to be ridiculously large, I'd probably create a table that logs each event individually, with a DateTime as @Turnkey suggests, and possibly the machine that logged it, etc. ``` LOGID (PK) ACTIVITYID SOURCE DATELOGGED ---------- ---------- ------ ---------- ``` That would give you the ability to run a query to get the current count, and also to use the data to determine events in a time period, and/or coming from a specific machine. A clustered index on ActivityID should give you good query performance, and the table is narrow so inserts shouldn't be too costly.
118,506
<p>The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.</p> <p>I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures.</p>
[ { "answer_id": 118582, "author": "Gleb Popoff", "author_id": 18076, "author_profile": "https://Stackoverflow.com/users/18076", "pm_score": 2, "selected": false, "text": "<p>You'll need to use <strong>MySQLI</strong> (MySQL Improved Extension) to call stored procedures. Here's how you wou...
2008/09/23
[ "https://Stackoverflow.com/questions/118506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4665/" ]
The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots. I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures.
Forget about `mysqli`, it's much harder to use than PDO and should have been already removed. It is true that it introduced huge improvements over mysql, but to achieve the same effect in mysqli sometimes requires enormous effort over PDO i.e. associative `fetchAll`. Instead, take a look at [PDO](http://www.php.net/manual/en/book.pdo.php), specifically [prepared statements and stored procedures](http://www.php.net/manual/en/pdo.prepared-statements.php). ``` $stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)"); $value = 'hello'; $stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); // call the stored procedure $stmt->execute(); print "procedure returned $value\n"; ```
118,516
<p>My issue is below but would be interested comments from anyone with experience with xlrd.</p> <p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages" rel="nofollow noreferrer">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p> <p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p> <p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties" rel="nofollow noreferrer">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p> <p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p> <p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq" rel="nofollow noreferrer">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p> <p>Any thoughts on: How to trick xlrd into recognizing the file so I can extract data? How to use python to automate the explicit 'save as' format to one that xlrd will accept? Plan B?</p>
[ { "answer_id": 118586, "author": "Michael Neale", "author_id": 699, "author_profile": "https://Stackoverflow.com/users/699", "pm_score": 0, "selected": false, "text": "<p>Well here is some code that I did: (look down the bottom): <a href=\"http://anonsvn.labs.jboss.com/labs/jbossrules/tr...
2008/09/23
[ "https://Stackoverflow.com/questions/118516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <http://www.djindexes.com/mdsidx/?event=showAverages>) When I open the file unmodified I get a nasty BIFF error (binary format not recognized) However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <http://skitch.com/alok/ssa3/componentreport-dji.xls-properties>) If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls Here is a pastebin of an ipython session replicating the issue: <http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq> Any thoughts on: How to trick xlrd into recognizing the file so I can extract data? How to use python to automate the explicit 'save as' format to one that xlrd will accept? Plan B?
FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points: 1. The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python: ``` >>> open('ComponentReport-DJI.xls', 'rb').read(200) 'COMPANY NAME\tPRIMARY EXCHANGE\tTICKER\tSTYLE\tICB SUBSECTOR\tMARKET CAP RANGE\ tWEIGHT PCT\tUSD CLOSE\t\r\n3M Co.\tNew York SE\tMMM\tN/A\tDiversified Industria ls\tBroad\t5.15676229508\t50.33\t\r\nAlcoa Inc.\tNew York SE\tA' ``` You can read this file using Python's csv module ... just use `delimiter="\t"` in your call to `csv.reader()`. 2. xlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation. 3. pyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out <http://groups.google.com/group/python-excel> HTH John
118,528
<h2>I've actually solved this, but I'm posting it for posterity.</h2> <p>I ran into a very odd issue with the DataGridView on my dual-monitor system. The issue manifests itself as an EXTREMELY slow repaint of the control (<em>like 30 seconds for a full repaint</em>), but only when it is on one of my screens. When on the other, the repaint speed is fine.</p> <p>I have an Nvidia 8800 GT with the latest non-beta drivers (175. something). Is it a driver bug? I'll leave that up in the air, since I have to live with this particular configuration. (It does not happen on ATI cards, though...)</p> <p>The paint speed has nothing to do with the cell contents, and custom drawing doesn't improve the performance at all - even when just painting a solid rectangle.</p> <p>I later find out that placing a ElementHost (from the System.Windows.Forms.Integration namespace) on the form corrects the problem. It doesn't have to be messed with; it just needs to be a child of the form the DataGridView is also on. It can be resized to (0, 0) as long as the <em>Visible</em> property is true.</p> <p>I don't want to explicitly add the .NET 3/3.5 dependency to my application; I make a method to create this control at runtime (if it can) using reflection. It works, and at least it fails gracefully on machines that don't have the required library - it just goes back to being slow.</p> <p>This method also lets me apply to fix while the app is running, making it easier to see what the WPF libraries are changing on my form (using Spy++).</p> <p>After a lot of trial and error, I notice that enabling double buffering on the control itself (as opposed to just the form) corrects the issue!</p> <hr> <p>So, you just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!</p> <pre><code>class CustomDataGridView: DataGridView { public CustomDataGridView() { DoubleBuffered = true; } } </code></pre> <p>As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (<em>although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency</em>).</p> <p>It is sad that such a trivially simple thing ate up so much of my time...</p>
[ { "answer_id": 157386, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 7, "selected": true, "text": "<p>You just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!</p>\n\n<...
2008/09/23
[ "https://Stackoverflow.com/questions/118528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5927/" ]
I've actually solved this, but I'm posting it for posterity. ------------------------------------------------------------ I ran into a very odd issue with the DataGridView on my dual-monitor system. The issue manifests itself as an EXTREMELY slow repaint of the control (*like 30 seconds for a full repaint*), but only when it is on one of my screens. When on the other, the repaint speed is fine. I have an Nvidia 8800 GT with the latest non-beta drivers (175. something). Is it a driver bug? I'll leave that up in the air, since I have to live with this particular configuration. (It does not happen on ATI cards, though...) The paint speed has nothing to do with the cell contents, and custom drawing doesn't improve the performance at all - even when just painting a solid rectangle. I later find out that placing a ElementHost (from the System.Windows.Forms.Integration namespace) on the form corrects the problem. It doesn't have to be messed with; it just needs to be a child of the form the DataGridView is also on. It can be resized to (0, 0) as long as the *Visible* property is true. I don't want to explicitly add the .NET 3/3.5 dependency to my application; I make a method to create this control at runtime (if it can) using reflection. It works, and at least it fails gracefully on machines that don't have the required library - it just goes back to being slow. This method also lets me apply to fix while the app is running, making it easier to see what the WPF libraries are changing on my form (using Spy++). After a lot of trial and error, I notice that enabling double buffering on the control itself (as opposed to just the form) corrects the issue! --- So, you just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it! ``` class CustomDataGridView: DataGridView { public CustomDataGridView() { DoubleBuffered = true; } } ``` As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (*although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency*). It is sad that such a trivially simple thing ate up so much of my time...
You just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it! ``` class CustomDataGridView: DataGridView { public CustomDataGridView() { DoubleBuffered = true; } } ``` As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency). It is sad that such a trivially simple thing ate up so much of my time... Note: Making the answer an answer so the question can be marked as answered
118,540
<p>First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.</p> <p>Here's the situation</p> <p>I have an abstract concept of a grid, with Y steps exactly Y_STEP apart (the x steps are working fine so ignore them for now)</p> <p>The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y_OFFSET</p> <p>to snap to the grid I've got the following code (python)</p> <pre><code>def snapToGrid(originalPos, offset, step): index = int((originalPos - offset) / step) #truncates the remainder away return index * gap + offset </code></pre> <p>so I pass the cursor position, Y_OFFSET and Y_STEP into that function and it returns me the nearest floored y position on the grid</p> <p>That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird.</p> <p>Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it.</p> <p>Here's a snippet of the cursor's mouseMotion code:</p> <pre><code>def mouseMotion(self, event): pixelPos = event.pos[Y] odePos = Scroll.pixelPosToOdePos(pixelPos) self.tool.positionChanged(odePos) </code></pre> <p>So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step.</p> <p>Here's the relevant Scroll code</p> <pre><code>def pixelPosToOdePos(pixelPos): offsetPixelPos = pixelPos - self.viewPortOffset return pixelsToOde(offsetPixelPos) def pixelsToOde(pixels): return float(pixels) / float(pixels_in_an_ode_unit) </code></pre> <p>And the tools update code</p> <pre><code>def positionChanged(self, newPos): self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP) </code></pre> <p>The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code:</p> <pre><code>#in Tool def render(self, screen): Scroll.render(screen, self.image, self.snappedPos) #in Scroll def render(self, screen, image, odePos): pixelPos = self.odePosToPixelPos(odePos) screen.blit(image, pixelPos) # screen is a surface from pygame for the curious def odePosToPixelPos(self.odePos): offsetPos = odePos + self.viewPortOffset return odeToPixels(offsetPos) def odeToPixels(odeUnits): return int(odeUnits * pixels_in_an_ode_unit) </code></pre> <p>Whew, that was a long explanation. Hope you're still with me... </p> <p>The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor.<br> It starts snapping to the Y step exactly 1 step below the cursor. Additionally it appears to phase in and out of allignment.<br> At some scrolls it is out by 1 and other scrolls it is spot on.<br> It's never out by more than 1 and it's always snapping to a valid grid location.</p> <p>Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior.</p> <p>Anyone familiar with coordinate spaces, scrolling and snapping?</p>
[ { "answer_id": 118645, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 0, "selected": false, "text": "<p>Do you have a typo in positionChanged() ?</p>\n\n<pre><code>def positionChanged(self, newPos):\n self.snapp...
2008/09/23
[ "https://Stackoverflow.com/questions/118540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong. Here's the situation I have an abstract concept of a grid, with Y steps exactly Y\_STEP apart (the x steps are working fine so ignore them for now) The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y\_OFFSET to snap to the grid I've got the following code (python) ``` def snapToGrid(originalPos, offset, step): index = int((originalPos - offset) / step) #truncates the remainder away return index * gap + offset ``` so I pass the cursor position, Y\_OFFSET and Y\_STEP into that function and it returns me the nearest floored y position on the grid That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird. Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it. Here's a snippet of the cursor's mouseMotion code: ``` def mouseMotion(self, event): pixelPos = event.pos[Y] odePos = Scroll.pixelPosToOdePos(pixelPos) self.tool.positionChanged(odePos) ``` So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step. Here's the relevant Scroll code ``` def pixelPosToOdePos(pixelPos): offsetPixelPos = pixelPos - self.viewPortOffset return pixelsToOde(offsetPixelPos) def pixelsToOde(pixels): return float(pixels) / float(pixels_in_an_ode_unit) ``` And the tools update code ``` def positionChanged(self, newPos): self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP) ``` The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code: ``` #in Tool def render(self, screen): Scroll.render(screen, self.image, self.snappedPos) #in Scroll def render(self, screen, image, odePos): pixelPos = self.odePosToPixelPos(odePos) screen.blit(image, pixelPos) # screen is a surface from pygame for the curious def odePosToPixelPos(self.odePos): offsetPos = odePos + self.viewPortOffset return odeToPixels(offsetPos) def odeToPixels(odeUnits): return int(odeUnits * pixels_in_an_ode_unit) ``` Whew, that was a long explanation. Hope you're still with me... The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor. It starts snapping to the Y step exactly 1 step below the cursor. Additionally it appears to phase in and out of allignment. At some scrolls it is out by 1 and other scrolls it is spot on. It's never out by more than 1 and it's always snapping to a valid grid location. Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior. Anyone familiar with coordinate spaces, scrolling and snapping?
Ok, I'm answering my own question here, as alexk mentioned, using int to truncate was my mistake. The behaviour I'm after is best modeled by math.floor(). Apologies, the original question does not contain enough information to really work out what the problem is. I didn't have the extra bit of information at that point. With regards to the typo note, I think I may be using the context in a confusing manner... From the perspective of the positionChanged() function, the parameter is a new position coming in. From the perspective of the snapToGrid() function the parameter is an original position which is being changed to a snapped position. The language is like that because part of it is in my event handling code and the other part is in my general services code. I should have changed it for the example
118,547
<p>I am looking for a way to create a ZIP file from a folder in Windows C/C++ APIs. I can find the way to do this in VBScript using the Shell32.Application CopyHere method, and I found a tutorial explaining how to do it in C# also, but nothing for the C API (C++ is fine too, project already uses MFC).</p> <p>I'd be really grateful if anyone can share some sample C code that can successfully create a zip file on Windows XP/2003. Failing that, if someone can find solid docs or a tutorial that would be great, since MSDN searches don't turn up much. I'm really hoping to avoid having to ship a third-party lib for this, because the functionality is obviously there, I just can't figure out how to access it. Google searches turn up nothing useful, just tantalizing bits and pieces of information. Here's hoping someone in the community has sorted this out and can share it for posterity!</p>
[ { "answer_id": 118602, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 1, "selected": false, "text": "<p>I do not think that MFC or the Windows standard C/C++ APIs provide an interface to the built in zip functionality.</p>\n"...
2008/09/23
[ "https://Stackoverflow.com/questions/118547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20840/" ]
I am looking for a way to create a ZIP file from a folder in Windows C/C++ APIs. I can find the way to do this in VBScript using the Shell32.Application CopyHere method, and I found a tutorial explaining how to do it in C# also, but nothing for the C API (C++ is fine too, project already uses MFC). I'd be really grateful if anyone can share some sample C code that can successfully create a zip file on Windows XP/2003. Failing that, if someone can find solid docs or a tutorial that would be great, since MSDN searches don't turn up much. I'm really hoping to avoid having to ship a third-party lib for this, because the functionality is obviously there, I just can't figure out how to access it. Google searches turn up nothing useful, just tantalizing bits and pieces of information. Here's hoping someone in the community has sorted this out and can share it for posterity!
EDIT: This answer is old, but I cannot delete it because it was accepted. See the next one <https://stackoverflow.com/a/121720/3937> ----- ORIGINAL ANSWER ----- There is sample code to do that here [EDIT: Link is now broken] <http://www.eggheadcafe.com/software/aspnet/31056644/using-shfileoperation-to.aspx> Make sure you read about how to handle monitoring for the thread to complete. Edit: From the comments, this code only works on existing zip file, but @[Simon](https://stackoverflow.com/users/20135/simonbuchanmyopenidcom) provided this code to create a blank zip file ``` FILE* f = fopen("path", "wb"); fwrite("\x50\x4B\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 22, 1, f); fclose(f); ```
118,565
<p>Say I have a web service <a href="http://www.example.com/webservice.pl?q=google" rel="noreferrer">http://www.example.com/webservice.pl?q=google</a> which returns text "google.com". I need to call this web service (<a href="http://www.example.com/webservice.pl" rel="noreferrer">http://www.example.com/webservice.pl</a>) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.</p> <p>What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated.</p>
[ { "answer_id": 118574, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "<p>Take a look at one of the many javascript libraries out there. I'd recommend <a href=\"http://www.jquery.com\" rel=\"norefer...
2008/09/23
[ "https://Stackoverflow.com/questions/118565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734/" ]
Say I have a web service <http://www.example.com/webservice.pl?q=google> which returns text "google.com". I need to call this web service (<http://www.example.com/webservice.pl>) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing. What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated.
Take a look at one of the many javascript libraries out there. I'd recommend [jQuery](http://www.jquery.com), personally. Aside from all the fancy UI stuff they can do, it has really good [cross-browser AJAX libraries](http://docs.jquery.com/Ajax). ``` $.get( "http://xyz.com/webservice.pl", { q : "google" }, function(data) { alert(data); // "google.com" } ); ```
118,591
<p>I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:</p> <pre><code>find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \; </code></pre> <p>I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current:</p> <pre><code>def AllFiles(filepath, depth=1, flist=[]): fpath=os.walk(filepath) fpath=[item for item in fpath] while depth &lt; len(fpath): for item in fpath[depth][-1]: flist.append(fpath[depth][0]+os.sep+item) depth+=1 return flist </code></pre> <p>First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list_member).st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.</p> <p>Of course, anything with the concision of the bash command would also be illuminating.</p>
[ { "answer_id": 118647, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>That's not a Bash command, it's a <code>find</code> command. If you really want to port it to Python it's possible,...
2008/09/23
[ "https://Stackoverflow.com/questions/118591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11596/" ]
I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive: ``` find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \; ``` I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current: ``` def AllFiles(filepath, depth=1, flist=[]): fpath=os.walk(filepath) fpath=[item for item in fpath] while depth < len(fpath): for item in fpath[depth][-1]: flist.append(fpath[depth][0]+os.sep+item) depth+=1 return flist ``` First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list\_member).st\_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit. Of course, anything with the concision of the bash command would also be illuminating.
``` import os import shutil from os import path from os.path import join, getmtime from time import time archive = "bak" current = "cur" def archive_old_versions(days = 3): for root, dirs, files in os.walk(current): for name in files: fullname = join(root, name) if (getmtime(fullname) < time() - days * 60 * 60 * 24): shutil.move(fullname, join(archive, name)) ```
118,599
<p>I'm trying to store a password in a file that I'd like to retrieve for later. Hashing is not an option as I need the password for connecting to a remote server for later.</p> <p>The following code works well, but it creates a different output each time even though the key is the same. This is bad as when the application shuts down and restarts I won't be able to retrieve my password any more. How can I store passwords in a file and retrieve them later?</p> <pre><code>public class EncyptDecrypt { static System.Security.Cryptography.TripleDESCryptoServiceProvider keyProv = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); public static System.Security.Cryptography.TripleDESCryptoServiceProvider KeyProvider { get { keyProv.Key = new byte[] { /* redacted with prejudice */ }; return keyProv; } } public static string Encrypt(string text, SymmetricAlgorithm key) { if (text.Equals(string.Empty)) return text; // Create a memory stream. MemoryStream ms = new MemoryStream(); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write); // Create a StreamWriter to write a string // to the stream. StreamWriter sw = new StreamWriter(encStream); // Write the plaintext to the stream. sw.WriteLine(text); // Close the StreamWriter and CryptoStream. sw.Close(); encStream.Close(); // Get an array of bytes that represents // the memory stream. byte[] buffer = ms.ToArray(); // Close the memory stream. ms.Close(); // Return the encrypted byte array. return System.Convert.ToBase64String(buffer); } // Decrypt the byte array. public static string Decrypt(string cypherText, SymmetricAlgorithm key) { if (cypherText.Equals(string.Empty)) return cypherText; string val; try { // Create a memory stream to the passed buffer. MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(cypherText)); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read); // Create a StreamReader for reading the stream. StreamReader sr = new StreamReader(encStream); // Read the stream as a string. val = sr.ReadLine(); // Close the streams. sr.Close(); encStream.Close(); ms.Close(); } catch (System.Exception) { return string.Empty; } return val; } } </code></pre>
[ { "answer_id": 118613, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 4, "selected": true, "text": "<p>I believe that what's happening is that the crypto provider is randomly generating an IV. Specify this and it s...
2008/09/23
[ "https://Stackoverflow.com/questions/118599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
I'm trying to store a password in a file that I'd like to retrieve for later. Hashing is not an option as I need the password for connecting to a remote server for later. The following code works well, but it creates a different output each time even though the key is the same. This is bad as when the application shuts down and restarts I won't be able to retrieve my password any more. How can I store passwords in a file and retrieve them later? ``` public class EncyptDecrypt { static System.Security.Cryptography.TripleDESCryptoServiceProvider keyProv = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); public static System.Security.Cryptography.TripleDESCryptoServiceProvider KeyProvider { get { keyProv.Key = new byte[] { /* redacted with prejudice */ }; return keyProv; } } public static string Encrypt(string text, SymmetricAlgorithm key) { if (text.Equals(string.Empty)) return text; // Create a memory stream. MemoryStream ms = new MemoryStream(); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write); // Create a StreamWriter to write a string // to the stream. StreamWriter sw = new StreamWriter(encStream); // Write the plaintext to the stream. sw.WriteLine(text); // Close the StreamWriter and CryptoStream. sw.Close(); encStream.Close(); // Get an array of bytes that represents // the memory stream. byte[] buffer = ms.ToArray(); // Close the memory stream. ms.Close(); // Return the encrypted byte array. return System.Convert.ToBase64String(buffer); } // Decrypt the byte array. public static string Decrypt(string cypherText, SymmetricAlgorithm key) { if (cypherText.Equals(string.Empty)) return cypherText; string val; try { // Create a memory stream to the passed buffer. MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(cypherText)); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read); // Create a StreamReader for reading the stream. StreamReader sr = new StreamReader(encStream); // Read the stream as a string. val = sr.ReadLine(); // Close the streams. sr.Close(); encStream.Close(); ms.Close(); } catch (System.Exception) { return string.Empty; } return val; } } ```
I believe that what's happening is that the crypto provider is randomly generating an IV. Specify this and it should no longer differ. Edit: You can do this in your 'keyProvider' by setting the IV property.
118,630
<p>I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this:</p> <pre><code>const T operator+(const T&amp; lhs, const T&amp; rhs) { return T(lhs) +=rhs; } </code></pre> <p>But it was pointed out to me that this would also work:</p> <pre><code>const T operator+ (T lhs, const T&amp; rhs) { return lhs+=rhs; } </code></pre> <p>In essence, this form transfers creation of the temporary from the body of the implementation to the function call.</p> <p>It seems a little awkward to have different types for the two parameters, but is there anything wrong with the second form? Is there a reason to prefer one over the other?</p>
[ { "answer_id": 118664, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 3, "selected": true, "text": "<p>With the edited question, the first form would be preferred. The compiler will more likely optimize the return value ...
2008/09/23
[ "https://Stackoverflow.com/questions/118630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1674/" ]
I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this: ``` const T operator+(const T& lhs, const T& rhs) { return T(lhs) +=rhs; } ``` But it was pointed out to me that this would also work: ``` const T operator+ (T lhs, const T& rhs) { return lhs+=rhs; } ``` In essence, this form transfers creation of the temporary from the body of the implementation to the function call. It seems a little awkward to have different types for the two parameters, but is there anything wrong with the second form? Is there a reason to prefer one over the other?
With the edited question, the first form would be preferred. The compiler will more likely optimize the return value (you could verify this by placing a breakpoint in the constructor for T). The first form also takes both parameters as const, which would be more desirable. Research on the topic of **return value optimization**, such as this link as a quick example: <http://www.cs.cmu.edu/~gilpin/c++/performance.html>
118,632
<p>I need to layout a html datatable with CSS. </p> <p>The actual content of the table can differ, but there is always one main column and 2 or more other columns. I'd like to make the main column take up as MUCH width as possible, regardless of its contents, while the other columns take up as little width as possible. I can't specify exact widths for any of the columns because their contents can change.</p> <p>How can I do this using a simple semantically valid html table and css only?</p> <p>For example:</p> <pre> | Main column | Col 2 | Column 3 | &lt;------------------ fixed width in px -------------------&gt; &lt;------- as wide as possible ---------&gt; Thin as possible depending on contents: &lt;-----&gt; &lt;--------&gt; </pre>
[ { "answer_id": 118655, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 4, "selected": true, "text": "<p>I'm far from being a CSS expert but this works for me (in IE, FF, Safari and Chrome):</p>\n\n<pre><code>td.zero...
2008/09/23
[ "https://Stackoverflow.com/questions/118632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ]
I need to layout a html datatable with CSS. The actual content of the table can differ, but there is always one main column and 2 or more other columns. I'd like to make the main column take up as MUCH width as possible, regardless of its contents, while the other columns take up as little width as possible. I can't specify exact widths for any of the columns because their contents can change. How can I do this using a simple semantically valid html table and css only? For example: ``` | Main column | Col 2 | Column 3 | <------------------ fixed width in px -------------------> <------- as wide as possible ---------> Thin as possible depending on contents: <-----> <--------> ```
I'm far from being a CSS expert but this works for me (in IE, FF, Safari and Chrome): ``` td.zero_width { width: 1%; } ``` Then in your HTML: ``` <td class="zero_width">...</td> ```
118,643
<p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
[ { "answer_id": 118651, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 4, "selected": false, "text": "<p>I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is ...
2008/09/23
[ "https://Stackoverflow.com/questions/118643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14744/" ]
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
There's a solution to your problem that is distributed with python itself. `pindent.py`, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have to [grab it from svn.python.org](https://svn.python.org/projects/python/trunk/Tools/scripts/pindent.py) if you are running on Linux or OSX. It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command: `pindent.py -c myfile.py` ``` def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 # end if else: print 'oops!' # end if # end def foobar ``` Where the original `myfile.py` was: ``` def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 else: print 'oops!' ``` You can also use `pindent.py -r` to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation. For example, running `pindent.py -r myfile.py` will convert the following code in `myfile.py` into the same properly indented (and also commented) code as produced by the `pindent.py -c` example above: ``` def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 # end if else: print 'oops!' # end if # end def foobar ``` I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help.
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
[ { "answer_id": 118671, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 0, "selected": false, "text": "<p>I haven't tested it, but I'd say it'll most likely work with the latest IPy2.</p>\n\n<p>As for distribution, it...
2008/09/23
[ "https://Stackoverflow.com/questions/118654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ]
Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)?
I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was anything comparable available for .NET, but then I found the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) and if anything I think I've actually gained some maintainability over BeautifulSoup. It takes clean or crufty HTML and produces a elegant XML DOM from it that can be queried via XPath. With a couple lines of code you can even get back a raw XDocument and then [craft your queries in LINQ to XML](http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx). Honestly, if web scraping is your goal, this is about the cleanest solution you are likely to find. **Edit** Here is a simple (read: not robust at all) example that parses out the US House of Representatives holiday schedule: ``` using System; using System.Collections.Generic; using HtmlAgilityPack; namespace GovParsingTest { class Program { static void Main(string[] args) { HtmlWeb hw = new HtmlWeb(); string url = @"http://www.house.gov/house/House_Calendar.shtml"; HtmlDocument doc = hw.Load(url); HtmlNode docNode = doc.DocumentNode; HtmlNode div = docNode.SelectSingleNode("//div[@id='primary']"); HtmlNodeCollection tableRows = div.SelectNodes(".//tr"); foreach (HtmlNode row in tableRows) { HtmlNodeCollection cells = row.SelectNodes(".//td"); HtmlNode dateNode = cells[0]; HtmlNode eventNode = cells[1]; while (eventNode.HasChildNodes) { eventNode = eventNode.FirstChild; } Console.WriteLine(dateNode.InnerText); Console.WriteLine(eventNode.InnerText); Console.WriteLine(); } //Console.WriteLine(div.InnerHtml); Console.ReadKey(); } } } ```
118,686
<p>I'm using GDI+ in C++. (This issue might exist in C# too). </p> <p>I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right.</p> <p>For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP".</p> <p>My question is: is this intended or documented behaviour, and how do I disable this? </p> <pre><code>RectF Rect(0,0,32767,32767); RectF Bounds1, Bounds2; graphics-&gt;MeasureString(L"PP", 1, font, Rect, &amp;Bounds1); graphics-&gt;MeasureString(L"PP", 2, font, Rect, &amp;Bounds2); margin = Bounds1.Width * 2 - Bounds2.Width; </code></pre>
[ { "answer_id": 118764, "author": "HitScan", "author_id": 9490, "author_profile": "https://Stackoverflow.com/users/9490", "pm_score": 5, "selected": true, "text": "<p>It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of...
2008/09/23
[ "https://Stackoverflow.com/questions/118686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10592/" ]
I'm using GDI+ in C++. (This issue might exist in C# too). I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right. For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP". My question is: is this intended or documented behaviour, and how do I disable this? ``` RectF Rect(0,0,32767,32767); RectF Bounds1, Bounds2; graphics->MeasureString(L"PP", 1, font, Rect, &Bounds1); graphics->MeasureString(L"PP", 2, font, Rect, &Bounds2); margin = Bounds1.Width * 2 - Bounds2.Width; ```
It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of overhangs. [MSDN](http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx) suggests using a different method if you need more accuracy: > > To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the [MeasureCharacterRanges](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurecharacterranges.aspx) method or one of the [MeasureString](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurestring.aspx) methods that takes a [StringFormat](http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.aspx), and pass [GenericTypographic](http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.generictypographic.aspx). Also, ensure the [TextRenderingHint](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint.aspx) for the [Graphics](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.aspx) is [AntiAlias](http://msdn.microsoft.com/en-us/library/ssazt6bs.aspx). > > >
118,693
<p>Dynamically creating a radio button using eg </p> <pre><code>var radioInput = document.createElement('input'); radioInput.setAttribute('type', 'radio'); radioInput.setAttribute('name', name); </code></pre> <p>works in Firefox but not in IE. Why not?</p>
[ { "answer_id": 118702, "author": "Patrick Wilkes", "author_id": 6370, "author_profile": "https://Stackoverflow.com/users/6370", "pm_score": 3, "selected": false, "text": "<p>Based on this post and its comments:\n<a href=\"http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-c...
2008/09/23
[ "https://Stackoverflow.com/questions/118693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6370/" ]
Dynamically creating a radio button using eg ``` var radioInput = document.createElement('input'); radioInput.setAttribute('type', 'radio'); radioInput.setAttribute('name', name); ``` works in Firefox but not in IE. Why not?
Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch: ``` function createRadioElement(name, checked) { var radioHtml = '<input type="radio" name="' + name + '"'; if ( checked ) { radioHtml += ' checked="checked"'; } radioHtml += '/>'; var radioFragment = document.createElement('div'); radioFragment.innerHTML = radioHtml; return radioFragment.firstChild; } ```
118,698
<p>In JavaScript, you can use <a href="http://peter.michaux.ca/article/3556" rel="noreferrer">Lazy Function Definitions</a> to optimize the 2nd - Nth call to a function by performing the <strong>expensive</strong> one-time operations only on the first call to the function.</p> <p>I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed, nor is overloading a function.</p> <p>Effectively what I'd like to do is like the following, only optimized so the 2nd - Nth calls (say 25-100) don't need to re-check if they are the first call.</p> <pre><code>$called = false; function foo($param_1){ global $called; if($called == false){ doExpensiveStuff($param_1); $called = true; } echo '&lt;b&gt;'.$param_1.'&lt;/b&gt;'; } </code></pre> <p>PS I've thought about using an include_once() or require_once() as the first line in the function to execute the external code just once, but I've heard that these too are expensive.</p> <p>Any Ideas? or is there a better way to tackle this?</p>
[ { "answer_id": 118717, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>Have you actually profiled this code? I'm doubtful that an extra boolean test is going to have any measurable impac...
2008/09/23
[ "https://Stackoverflow.com/questions/118698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6144/" ]
In JavaScript, you can use [Lazy Function Definitions](http://peter.michaux.ca/article/3556) to optimize the 2nd - Nth call to a function by performing the **expensive** one-time operations only on the first call to the function. I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed, nor is overloading a function. Effectively what I'd like to do is like the following, only optimized so the 2nd - Nth calls (say 25-100) don't need to re-check if they are the first call. ``` $called = false; function foo($param_1){ global $called; if($called == false){ doExpensiveStuff($param_1); $called = true; } echo '<b>'.$param_1.'</b>'; } ``` PS I've thought about using an include\_once() or require\_once() as the first line in the function to execute the external code just once, but I've heard that these too are expensive. Any Ideas? or is there a better way to tackle this?
Use a local static var: ``` function foo() { static $called = false; if ($called == false) { $called = true; expensive_stuff(); } } ``` Avoid using a global for this. It clutters the global namespace and makes the function less encapsulated. If other places besides the innards of the function need to know if it's been called, then it'd be worth it to put this function inside a class like Alan Storm indicated.
118,719
<p>Usecase: The user makes font customizations to an object on the design surface, that I need to load/save to my datastore. I.e. settings like Bold, Italics, Size, Font Name need to persisted.</p> <p>Is there some easy (and reliable) mechanism to convert/read back from a string representation of the font object (in which case I would need just one attribute)? Or is multiple properties combined with custom logic the right option? </p>
[ { "answer_id": 118754, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx\" rel=\"noreferrer\">TypeConver...
2008/09/23
[ "https://Stackoverflow.com/questions/118719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
Usecase: The user makes font customizations to an object on the design surface, that I need to load/save to my datastore. I.e. settings like Bold, Italics, Size, Font Name need to persisted. Is there some easy (and reliable) mechanism to convert/read back from a string representation of the font object (in which case I would need just one attribute)? Or is multiple properties combined with custom logic the right option?
Use [TypeConverter](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx): ``` Font font = new Font("Arial", 12, GraphicsUnit.Pixel); TypeConverter converter = TypeDescriptor.GetConverter(typeof (Font)); string fontStr = converter.ConvertToInvariantString(font); Font font2 = (Font) converter.ConvertFromString(fontStr); Console.WriteLine(font.Name == font2.Name); // prints True ``` If you want to use XML serialization you can create Font class wrapper which will store some subset of Font properties. *Note(Gishu) - Never access a type converter directly. Instead, access the appropriate converter by using TypeDescriptor. Very important :)*
118,727
<p>I'm in the process of moving one of our projects from VS6 to VS2008 and I've hit the following compile error with mshtml.h:</p> <pre><code>1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5272) : error C2143: syntax error : missing '}' before 'constant' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C2143: syntax error : missing ';' before '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2143: syntax error : missing ';' before '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' </code></pre> <p>Following the first error statement drops into this part of the mshtml.h code, pointing at the "True = 1" line:</p> <pre><code>EXTERN_C const GUID CLSID_CDocument; EXTERN_C const GUID CLSID_CScriptlet; typedef enum _BoolValue { True = 1, False = 0, BoolValue_Max = 2147483647L } BoolValue; EXTERN_C const GUID CLSID_CPluginSite; </code></pre> <p>It looks like someone on expert-sexchange also came across this error but I'd rather not dignify that site with a "7 day free trial".</p> <p>Any suggestions would be most welcome.</p>
[ { "answer_id": 118734, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": true, "text": "<p>There is probably a #define changing something. Try running just the preprocessor on your .cpp and generating a .i fil...
2008/09/23
[ "https://Stackoverflow.com/questions/118727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341/" ]
I'm in the process of moving one of our projects from VS6 to VS2008 and I've hit the following compile error with mshtml.h: ``` 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5272) : error C2143: syntax error : missing '}' before 'constant' 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C2143: syntax error : missing ';' before '}' 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2143: syntax error : missing ';' before '}' 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' ``` Following the first error statement drops into this part of the mshtml.h code, pointing at the "True = 1" line: ``` EXTERN_C const GUID CLSID_CDocument; EXTERN_C const GUID CLSID_CScriptlet; typedef enum _BoolValue { True = 1, False = 0, BoolValue_Max = 2147483647L } BoolValue; EXTERN_C const GUID CLSID_CPluginSite; ``` It looks like someone on expert-sexchange also came across this error but I'd rather not dignify that site with a "7 day free trial". Any suggestions would be most welcome.
There is probably a #define changing something. Try running just the preprocessor on your .cpp and generating a .i file. The setting is in the project property pages. EDIT: Also, you can get the answer from that other expert site by scrolling to the bottom of the page. They have to do that or Google will take them out of their indexes.
118,730
<p>Does anyone know how I can get rid of the following assembler warning?</p> <p>Code is x86, 32 bit:</p> <pre><code>int test (int x) { int y; // do a bit-rotate by 8 on the lower word. leave upper word intact. asm ("rorw $8, %0\n\t": "=q"(y) :"0"(x)); return y; } </code></pre> <p>If I compile it I get the following (very valid) warning:</p> <pre><code>Warning: using `%ax' instead of `%eax' due to `w' suffix </code></pre> <p>What I'm looking for is a way to tell the compiler/assembler that I want to access the lower 16 bit sub-register of %0. Accessing the byte sub-registers (in this case AL and AH) would be nice to know as well. </p> <p>I've already chosen the "q" modifier, so the compiler is forced to use EAX, EBX, ECX or EDX. I've made sure the compiler has to pick a register that has sub-registers.</p> <p>I know that I can force the asm-code to use a specific register (and its sub-registers), but I want to leave the register-allocation job up to the compiler.</p>
[ { "answer_id": 118737, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<p>You can use <code>%w0</code> if I remember right. I just tested it, too. :-)</p>\n<pre><code>int\ntest(int x)\n{\n int ...
2008/09/23
[ "https://Stackoverflow.com/questions/118730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
Does anyone know how I can get rid of the following assembler warning? Code is x86, 32 bit: ``` int test (int x) { int y; // do a bit-rotate by 8 on the lower word. leave upper word intact. asm ("rorw $8, %0\n\t": "=q"(y) :"0"(x)); return y; } ``` If I compile it I get the following (very valid) warning: ``` Warning: using `%ax' instead of `%eax' due to `w' suffix ``` What I'm looking for is a way to tell the compiler/assembler that I want to access the lower 16 bit sub-register of %0. Accessing the byte sub-registers (in this case AL and AH) would be nice to know as well. I've already chosen the "q" modifier, so the compiler is forced to use EAX, EBX, ECX or EDX. I've made sure the compiler has to pick a register that has sub-registers. I know that I can force the asm-code to use a specific register (and its sub-registers), but I want to leave the register-allocation job up to the compiler.
You can use `%w0` if I remember right. I just tested it, too. :-) ``` int test(int x) { int y; asm ("rorw $8, %w0" : "=q" (y) : "0" (x)); return y; } ``` Edit: In response to the OP, yes, you can do the following too: ``` int test(int x) { int y; asm ("xchg %b0, %h0" : "=Q" (y) : "0" (x)); return y; } ``` For x86 it's documented in the [x86 Operand Modifiers section](https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#x86-Operand-Modifiers) of the Extended Asm part of the manual. For non-x86 instruction sets, you may have to dig through their `.md` files in the GCC source. For example, `gcc/config/i386/i386.md` was the only place to find this before it was officially documented. (Related: [In GNU C inline asm, what are the size-override modifiers for xmm/ymm/zmm for a single operand?](https://stackoverflow.com/questions/34459803/in-gnu-c-inline-asm-what-are-the-size-override-modifiers-for-xmm-ymm-zmm-for-a) for vector registers.)
118,748
<p>How do I open multiple pages in Internet Explorer 7 with a single DOS command? Is a batch file the only way to do this?</p> <p>Thanks!</p>
[ { "answer_id": 118763, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, there is no way to include multiple URLs as command-line parameters. Here is a a <a href=\"http://b...
2008/09/23
[ "https://Stackoverflow.com/questions/118748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I open multiple pages in Internet Explorer 7 with a single DOS command? Is a batch file the only way to do this? Thanks!
A batch file will work as a quick and dirty solution. ``` @echo off @setlocal :openurl set url=%~1 if "%url:~0,4%" == "http" ( start "%ProgramFiles%\Internet Explorer\iexplore.exe" "%url%" ) if NOT "%url:~0,4%" == "http" ( start "%ProgramFiles%\Internet Explorer\iexplore.exe" "http://%url%" ) shift if "%~1" == "" goto :end goto :openurl :end ``` Edit: added support for domain names without http handler prefix.
118,774
<p>Deep down in WinDef.h there's this relic from the segmented memory era:</p> <pre><code>#define far #define near </code></pre> <p>This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?</p>
[ { "answer_id": 118779, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 2, "selected": false, "text": "<p>maybe:</p>\n\n<pre><code>#undef near\n#undef far\n</code></pre>\n\n<p>could be dangerous though...</p>\n" }, { ...
2008/09/23
[ "https://Stackoverflow.com/questions/118774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841/" ]
Deep down in WinDef.h there's this relic from the segmented memory era: ``` #define far #define near ``` This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?
You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended. The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone.
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
[ { "answer_id": 118820, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<p>I have both installed:</p>\n\n<pre><code>$ which python\n/usr/bin/python\n$ which python2.5\n/opt/local/bin/python2.5\n...
2008/09/23
[ "https://Stackoverflow.com/questions/118813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013/" ]
I want to use the macports version of python instead of the one that comes with Leopard.
I have both installed: ``` $ which python /usr/bin/python $ which python2.5 /opt/local/bin/python2.5 ``` I also added the following line to my `.profile`: ``` export PATH=/opt/local/bin:/opt/local/sbin:$PATH ```
118,839
<p>I would like to replace only the group in parenthesis in this expression :</p> <pre><code>my_string.gsub(/&lt;--MARKER_START--&gt;(.)*&lt;--MARKER_END--&gt;/, 'replace_text') </code></pre> <p>so that I get : <code>&lt;--MARKER_START--&gt;replace_text&lt;--MARKER_END--&gt;</code></p> <p>I know I could repeat the whole <code>MARKER_START</code> and <code>MARKER_END</code> blocks in the substitution expression but I thought there should be a more simple way to do this.</p>
[ { "answer_id": 118852, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>You could do something like this:</p>\n\n<pre><code>my_string.gsub(/(&lt;--MARKER_START--&gt;)(.*)(&lt;--MARKER_END--&g...
2008/09/23
[ "https://Stackoverflow.com/questions/118839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20871/" ]
I would like to replace only the group in parenthesis in this expression : ``` my_string.gsub(/<--MARKER_START-->(.)*<--MARKER_END-->/, 'replace_text') ``` so that I get : `<--MARKER_START-->replace_text<--MARKER_END-->` I know I could repeat the whole `MARKER_START` and `MARKER_END` blocks in the substitution expression but I thought there should be a more simple way to do this.
You could do something like this: ``` my_string.gsub(/(<--MARKER_START-->)(.*)(<--MARKER_END-->)/, '\1replace_text\3') ```
118,851
<p>Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work.</p> <p>A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here?</p> <pre><code>routes.MapRoute("UserItems", "User/{UserID}/Items", new {controller = "User", action = "Items"}); </code></pre> <p>And on my aspx page</p> <pre><code>Html.ActionLink("Items", "UserItems", new { UserID = 1 }) </code></pre>
[ { "answer_id": 118996, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 1, "selected": false, "text": "<p>Can you post more information? What URL is the aspx page generating in the link? It could be because of the order of your rou...
2008/09/23
[ "https://Stackoverflow.com/questions/118851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work. A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here? ``` routes.MapRoute("UserItems", "User/{UserID}/Items", new {controller = "User", action = "Items"}); ``` And on my aspx page ``` Html.ActionLink("Items", "UserItems", new { UserID = 1 }) ```
Going by the MVC Preview 4 code I have in front of me the overload for Html.ActionLink() you are using is this one: ``` public string ActionLink(string linkText, string actionName, object values); ``` Note how the second parameter is the *actionName* not the *routeName*. As such, try: ``` Html.ActionLink("Items", "Items", new { UserID = 1 }) ``` Alternatively, try: ``` <a href="<%=Url.RouteUrl("UserItems", new { UserId = 1 })%>">Items</a> ```
118,863
<p>When is it appropriate to use a class in Visual Basic for Applications (VBA)?</p> <p>I'm assuming the <a href="http://en.wikipedia.org/wiki/Class_(computer_science)#Reasons_for_using_classes" rel="noreferrer">accelerated development and reduction of introducing bugs</a> is a common benefit for most languages that support OOP. But with VBA, is there a specific criterion? </p>
[ { "answer_id": 118870, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": -1, "selected": false, "text": "<p>I don't see why the criteria for VBA would be any different from another language, particularly if you are referring ...
2008/09/23
[ "https://Stackoverflow.com/questions/118863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
When is it appropriate to use a class in Visual Basic for Applications (VBA)? I'm assuming the [accelerated development and reduction of introducing bugs](http://en.wikipedia.org/wiki/Class_(computer_science)#Reasons_for_using_classes) is a common benefit for most languages that support OOP. But with VBA, is there a specific criterion?
It depends on who's going to develop and maintain the code. Typical "Power User" macro writers hacking small ad-hoc apps may well be confused by using classes. But for serious development, the reasons to use classes are the same as in other languages. You have the same restrictions as VB6 - no inheritance - but you can have polymorphism by using interfaces. A good use of classes is to represent entities, and collections of entities. For example, I often see VBA code that copies an Excel range into a two-dimensional array, then manipulates the two dimensional array with code like: ``` Total = 0 For i = 0 To NumRows-1 Total = Total + (OrderArray(i,1) * OrderArray(i,3)) Next i ``` It's more readable to copy the range into a collection of objects with appropriately-named properties, something like: ``` Total = 0 For Each objOrder in colOrders Total = Total + objOrder.Quantity * objOrder.Price Next i ``` Another example is to use classes to implement the RAII design pattern (google for it). For example, one thing I may need to do is to unprotect a worksheet, do some manipulations, then protect it again. Using a class ensures that the worksheet will always be protected again even if an error occurs in your code: ``` --- WorksheetProtector class module --- Private m_objWorksheet As Worksheet Private m_sPassword As String Public Sub Unprotect(Worksheet As Worksheet, Password As String) ' Nothing to do if we didn't define a password for the worksheet If Len(Password) = 0 Then Exit Sub ' If the worksheet is already unprotected, nothing to do If Not Worksheet.ProtectContents Then Exit Sub ' Unprotect the worksheet Worksheet.Unprotect Password ' Remember the worksheet and password so we can protect again Set m_objWorksheet = Worksheet m_sPassword = Password End Sub Public Sub Protect() ' Protects the worksheet with the same password used to unprotect it If m_objWorksheet Is Nothing Then Exit Sub If Len(m_sPassword) = 0 Then Exit Sub ' If the worksheet is already protected, nothing to do If m_objWorksheet.ProtectContents Then Exit Sub m_objWorksheet.Protect m_sPassword Set m_objWorksheet = Nothing m_sPassword = "" End Sub Private Sub Class_Terminate() ' Reprotect the worksheet when this object goes out of scope On Error Resume Next Protect End Sub ``` You can then use this to simplify your code: ``` Public Sub DoSomething() Dim objWorksheetProtector as WorksheetProtector Set objWorksheetProtector = New WorksheetProtector objWorksheetProtector.Unprotect myWorksheet, myPassword ... manipulate myWorksheet - may raise an error End Sub ``` When this Sub exits, objWorksheetProtector goes out of scope, and the worksheet is protected again.
118,884
<p>I have noticed that some browsers (in particular, Firefox and <a href="https://en.wikipedia.org/wiki/Opera_%28web_browser%29" rel="noreferrer">Opera</a>) are very zealous in using cached copies of <strong>.css</strong> and <strong>.js</strong> files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keeps on using the cached copy.</p> <p>What is the most elegant way of forcing the user's browser to reload the file when it has changed?</p> <p>Ideally, the solution would not force the browser to reload the file on every visit to the page.</p> <hr/> <p>I have found <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118921#118921">John Millikin's</a> and <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118901#118901">da5id's</a> suggestion to be useful. It turns out there is a term for this: <strong>auto-versioning</strong>.</p> <p>I have posted a new answer below which is a combination of my original solution and John's suggestion.</p> <p>Another idea that was suggested by <strong>SCdF</strong> would be to append a bogus query string to the file. (Some Python code, to automatically use the timestamp as a bogus query string, was <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/121143#121143">submitted by <em>pi.</em></a>.)</p> <p>However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.)</p>
[ { "answer_id": 118886, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 9, "selected": false, "text": "<p>This solution is written in PHP, but it should be easily adapted to other languages.</p>\n<p>The original <code>.htaccess</...
2008/09/23
[ "https://Stackoverflow.com/questions/118884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
I have noticed that some browsers (in particular, Firefox and [Opera](https://en.wikipedia.org/wiki/Opera_%28web_browser%29)) are very zealous in using cached copies of **.css** and **.js** files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keeps on using the cached copy. What is the most elegant way of forcing the user's browser to reload the file when it has changed? Ideally, the solution would not force the browser to reload the file on every visit to the page. --- I have found [John Millikin's](https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118921#118921) and [da5id's](https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118901#118901) suggestion to be useful. It turns out there is a term for this: **auto-versioning**. I have posted a new answer below which is a combination of my original solution and John's suggestion. Another idea that was suggested by **SCdF** would be to append a bogus query string to the file. (Some Python code, to automatically use the timestamp as a bogus query string, was [submitted by *pi.*](https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/121143#121143).) However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.)
This solution is written in PHP, but it should be easily adapted to other languages. The original `.htaccess` regex can cause problems with files like `json-1.3.js`. The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.) First, we use the following rewrite rule in .htaccess: ``` RewriteEngine on RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L] ``` Now, we write the following PHP function: ```php /** * Given a file, i.e. /css/base.css, replaces it with a string containing the * file's mtime, i.e. /css/base.1221534296.css. * * @param $file The file to be loaded. Must be an absolute path (i.e. * starting with slash). */ function auto_version($file) { if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file); } ``` Now, wherever you include your CSS, change it from this: ```html <link rel="stylesheet" href="/css/base.css" type="text/css" /> ``` To this: ``` <link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" /> ``` This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy. This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.
118,905
<p>I'm trying to write a parser to get the data out of a typical html table day/time schedule (like <a href="http://kut.org/about/schedule" rel="nofollow noreferrer">this</a>). </p> <p>I'd like to give this parser a page and a table class/id, and have it return a list of events, along with days &amp; times they occur. It should take into account rowspans and colspans, so for the linked example, it would return </p> <pre><code>{:event =&gt; "Music With Paul Ray", :times =&gt; [T 12:00am - 3:00am, F 12:00am - 3:00am]}, etc. </code></pre> <p>I've sort of figured out a half-executed messy approach using ruby, and am wondering how you might tackle such a problem?</p>
[ { "answer_id": 119029, "author": "treat your mods well", "author_id": 20772, "author_profile": "https://Stackoverflow.com/users/20772", "pm_score": 0, "selected": false, "text": "<p>This is what the program will need to do:</p>\n\n<ol>\n<li>Read the tags in (detect attributes and open/cl...
2008/09/23
[ "https://Stackoverflow.com/questions/118905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to write a parser to get the data out of a typical html table day/time schedule (like [this](http://kut.org/about/schedule)). I'd like to give this parser a page and a table class/id, and have it return a list of events, along with days & times they occur. It should take into account rowspans and colspans, so for the linked example, it would return ``` {:event => "Music With Paul Ray", :times => [T 12:00am - 3:00am, F 12:00am - 3:00am]}, etc. ``` I've sort of figured out a half-executed messy approach using ruby, and am wondering how you might tackle such a problem?
The best thing to do here is to use a HTML parser. With a HTML parser you can look at the table rows programmatically, without having to resort to fragile regular expressions and doing the parsing yourself. Then you can run some logic along the lines of (this is not runnable code, just a sketch that you should be able to see the idea from): ``` for row in table: i = 0 for cell in row: # skipping row 1 event = name starttime = row[0] endtime = table[ i + cell.rowspan + 1 ][0] print event, starttime, endtime i += 1 ```
119,009
<p>In our Java applications we typically use the maven conventions (docs, src/java, test, etc.). For Perl we follow similar conventions only using a top level 'lib' which is easy to add to Perl's @INC.</p> <p>I'm about to embark on creating a service written in Erlang, what's a good source layout for Erlang applications?</p>
[ { "answer_id": 119443, "author": "Bwooce", "author_id": 15290, "author_profile": "https://Stackoverflow.com/users/15290", "pm_score": 5, "selected": true, "text": "<p>The Erlang recommended standard directory structure can be <a href=\"http://erlang.org/doc/design_principles/applications...
2008/09/23
[ "https://Stackoverflow.com/questions/119009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19784/" ]
In our Java applications we typically use the maven conventions (docs, src/java, test, etc.). For Perl we follow similar conventions only using a top level 'lib' which is easy to add to Perl's @INC. I'm about to embark on creating a service written in Erlang, what's a good source layout for Erlang applications?
The Erlang recommended standard directory structure can be [found here](http://erlang.org/doc/design_principles/applications.html#id80846). In addition you may need a few more directories depending on your project, common ones are (credit to Vance Shipley): ``` lib: OS driver libraries bin: OS executables c_src: C language source files (e.g. for drivers) java_src: Java language source files examples: Example code mibs: SNMP MIBs ``` Other projects such as [Mochiweb](http://bob.pythonmac.org/archives/2007/12/17/using-the-mochiweb-project-skeleton/) have their own structures, Mochiweb even have a script to create it all for you. Other projects such as [Erlware](http://www.erlware.org) overlay on the standard structure.
119,011
<p>Can anyone suggest a good way of detecting if a database is empty from Java (needs to support at least Microsoft SQL Server, Derby and Oracle)?</p> <p>By empty I mean in the state it would be if the database were freshly created with a new create database statement, though the check need not be 100% perfect if covers 99% of cases.</p> <p>My first thought was to do something like this...</p> <pre><code>tables = metadata.getTables(null, null, null, null); Boolean isEmpty = !tables.next(); return isEmpty; </code></pre> <p>...but unfortunately that gives me a bunch of underlying system tables (at least in Microsoft SQL Server).</p>
[ { "answer_id": 119046, "author": "Nathan Feger", "author_id": 8563, "author_profile": "https://Stackoverflow.com/users/8563", "pm_score": 0, "selected": false, "text": "<p>Are you always checking databases created in the same way? If so you might be able to simply select from a subset o...
2008/09/23
[ "https://Stackoverflow.com/questions/119011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
Can anyone suggest a good way of detecting if a database is empty from Java (needs to support at least Microsoft SQL Server, Derby and Oracle)? By empty I mean in the state it would be if the database were freshly created with a new create database statement, though the check need not be 100% perfect if covers 99% of cases. My first thought was to do something like this... ``` tables = metadata.getTables(null, null, null, null); Boolean isEmpty = !tables.next(); return isEmpty; ``` ...but unfortunately that gives me a bunch of underlying system tables (at least in Microsoft SQL Server).
There are some cross-database SQL-92 schema query standards - mileage for this of course varies according to vendor ``` SELECT COUNT(*) FROM [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_TYPE] = <tabletype> ``` Support for these varies by vendor, as does the content of the columns for the Tables view. SQL implementation of Information Schema docs found here: > > <http://msdn.microsoft.com/en-us/library/aa933204(SQL.80).aspx> > > > More specifically in SQL Server, sysobjects metadata predates the SQL92 standards initiative. ``` SELECT COUNT(*) FROM [sysobjects] WHERE [type] = 'U' ``` Query above returns the count of User tables in the database. More information about the sysobjects table here: > > <http://msdn.microsoft.com/en-us/library/aa260447(SQL.80).aspx> > > >
119,018
<p>It seems that anyone can snoop on incoming/outgoing .NET web service SOAP messages just by dropping in a simple SoapExtension into the bin folder and then plumbing it in using:</p> <pre><code>&lt;soapExtensionTypes&gt; &lt;add type="MyLoggingSoapExtension, SoapLoggingTools" priority="0" group="High" /&gt; &lt;soapExtensionTypes&gt; </code></pre> <p>Is there a way to prevent SOAP extensions from loading or to be asked in my app (through an event or some such mechanism) whether it's ok to load ?</p> <p>@Hurst: thanks for the answer. I know about message level encryption/WS-Security and was hoping not to have to go that road. We have classic ASP clients using the service and that opens a small world of pain. There are SSL certs on the site running the web service but I was kinda hoping that I could discourage the client from tinkering with soap extensions as they have developers who have some ability to 'play'.</p>
[ { "answer_id": 119212, "author": "hurst", "author_id": 10991, "author_profile": "https://Stackoverflow.com/users/10991", "pm_score": 3, "selected": true, "text": "<p>I am not sure what you mean by extensions and bin folders (I would guess you are using .NET), so I can't answer about them...
2008/09/23
[ "https://Stackoverflow.com/questions/119018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
It seems that anyone can snoop on incoming/outgoing .NET web service SOAP messages just by dropping in a simple SoapExtension into the bin folder and then plumbing it in using: ``` <soapExtensionTypes> <add type="MyLoggingSoapExtension, SoapLoggingTools" priority="0" group="High" /> <soapExtensionTypes> ``` Is there a way to prevent SOAP extensions from loading or to be asked in my app (through an event or some such mechanism) whether it's ok to load ? @Hurst: thanks for the answer. I know about message level encryption/WS-Security and was hoping not to have to go that road. We have classic ASP clients using the service and that opens a small world of pain. There are SSL certs on the site running the web service but I was kinda hoping that I could discourage the client from tinkering with soap extensions as they have developers who have some ability to 'play'.
I am not sure what you mean by extensions and bin folders (I would guess you are using .NET), so I can't answer about them being loaded etc. However, note that SOAP is designed to allow intermediaries to read the headers and even to modify them. (Do a search for "SOAP Active Intermediaries"). **Judging by that, I expect there to be no reason for a technology to avoid snooping by preventing code from reading the SOAP**. The proper way to protect yourself is to use "***message-level security***". (This is in contrast to *transport-level security*, such as SSL, which does not protect from intermediaries). **In other words, encrypt your own messages before sending.** One available standard used to implement message-level security mechanisms is the **WS-Security** protocol. This allows you to target the encryption to the payload and relevant headers regardless of transport. It is more complex, but that is how you would go about restricting access.
119,060
<p>The Image Web Part doesn't seem to have an href attribute that I can set. Is there something I am missing?</p>
[ { "answer_id": 119122, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 3, "selected": false, "text": "<p>Does it have to be an Image Web Part? If not I would simply use a <a href=\"http://office.microsoft.com/en-us/sha...
2008/09/23
[ "https://Stackoverflow.com/questions/119060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The Image Web Part doesn't seem to have an href attribute that I can set. Is there something I am missing?
Does it have to be an Image Web Part? If not I would simply use a [Content Editor Web Part](http://office.microsoft.com/en-us/sharepointserver/HA100240461033.aspx) and paste the required HTML there. ``` <a href="http://www.google.com"><img src="urlToImage" /></a> ```
119,098
<p>In new C++ code, I tend to use the C++ iostream library instead of the C stdio library.</p> <p>I've noticed some programmers seem to stick to stdio, insisting that it's more portable.</p> <p>Is this really the case? What is better to use?</p>
[ { "answer_id": 119118, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "<p>If, like me, you learned C before learning C++, the stdio libraries seem more natural to use. There are pros and cons...
2008/09/23
[ "https://Stackoverflow.com/questions/119098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
In new C++ code, I tend to use the C++ iostream library instead of the C stdio library. I've noticed some programmers seem to stick to stdio, insisting that it's more portable. Is this really the case? What is better to use?
To answer the original question: Anything that can be done using stdio can be done using the iostream library. ``` Disadvantages of iostreams: verbose Advantages of iostreams: easy to extend for new non POD types. ``` The step forward the C++ made over C was type safety. * iostreams was designed to be explicitly type safe. Thus assignment to an object explicitly checked the type (at compiler time) of the object being assigned too (generating an compile time error if required). Thus prevent run-time memory over-runs or writing a float value to a char object etc. * scanf()/printf() and family on the other hand rely on the programmer getting the format string correct and there was no type checking (I believe gcc has an extension that helps). As a result it was the source of many bugs (as programmers are less perfect in their analysis than compilers [not going to say compilers are perfect just better than humans]). Just to clarify comments from Colin Jensen. * The iostream libraries have been stable since the release of the last standard (I forget the actual year but about 10 years ago). To clarify comments by Mikael Jansson. * The other languages that he mentions that use the format style have explicit safeguards to prevent the dangerous side effects of the C stdio library that can (in C but not the mentioned languages) cause a run-time crash. **N.B.** I agree that the iostream library is a bit on the verbose side. But I am willing to put up with the verboseness to ensure runtime safety. But we can mitigate the verbosity by using [Boost Format Library](http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html). ``` #include <iostream> #include <iomanip> #include <boost/format.hpp> struct X { // this structure reverse engineered from // example provided by 'Mikael Jansson' in order to make this a running example char* name; double mean; int sample_count; }; int main() { X stats[] = {{"Plop",5.6,2}}; // nonsense output, just to exemplify // stdio version fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n", stats, stats->name, stats->mean, stats->sample_count); // iostream std::cerr << "at " << (void*)stats << "/" << stats->name << ": mean value " << std::fixed << std::setprecision(3) << stats->mean << " of " << std::setw(4) << std::setfill(' ') << stats->sample_count << " samples\n"; // iostream with boost::format std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n") % stats % stats->name % stats->mean % stats->sample_count; } ```
119,107
<p>This is what I have so far: </p> <pre><code>myArray.map!{ rand(max) } </code></pre> <p>Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?</p> <p><strong>Edit:</strong><br> I'd really like to see this done w/o loop - if at all possible.</p>
[ { "answer_id": 119120, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 1, "selected": false, "text": "<p>You could use a hash to track the random numbers you've used so far:</p>\n\n<pre><code>seen = {}\nmax = 100\n(1..10...
2008/09/23
[ "https://Stackoverflow.com/questions/119107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
This is what I have so far: ``` myArray.map!{ rand(max) } ``` Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers? **Edit:** I'd really like to see this done w/o loop - if at all possible.
This uses Set: ``` require 'set' def rand_n(n, max) randoms = Set.new loop do randoms << rand(max) return randoms.to_a if randoms.size >= n end end ```
119,114
<p>I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in.</p> <p>Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling on my home box or not ?</p> <p>What I am after is a way of defining a symbol, let's call it _ATHOME, automatically so I can do this:</p> <pre><code>#ifdef _ATHOME # define TEST_FILES "E:\\Test" # define TEST_SERVER "192.168.0.1" #else # define TEST_FILE "Z:\\Project\\Blah\\Test" # define TEST_SERVER "212.45.68.43" #endif </code></pre> <p><em>NB: This is for development and debugging purposes of course, I would never release software with hard coded constants like this.</em></p>
[ { "answer_id": 119121, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>You can set preproccesor variables in the properties->c++->preprocessor<br>\nin visual studio settings you can u...
2008/09/23
[ "https://Stackoverflow.com/questions/119114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ]
I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in. Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling on my home box or not ? What I am after is a way of defining a symbol, let's call it \_ATHOME, automatically so I can do this: ``` #ifdef _ATHOME # define TEST_FILES "E:\\Test" # define TEST_SERVER "192.168.0.1" #else # define TEST_FILE "Z:\\Project\\Blah\\Test" # define TEST_SERVER "212.45.68.43" #endif ``` *NB: This is for development and debugging purposes of course, I would never release software with hard coded constants like this.*
On your home and work machines, set an environment variable `LOCATION` that is either "1" for home or "2" for work. Then in the preprocessor options, add a preprocessor define /DLOCATION=$(LOCATION). This will evaluate to either the "home" or "work" string that you set in the environment variable. Then in your code: ``` #if LOCATION==1 // home #else // work #endif ```
119,123
<p>Why does the <code>sizeof</code> operator return a size larger for a structure than the total sizes of the structure's members?</p>
[ { "answer_id": 119128, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 11, "selected": true, "text": "<p>This is because of padding added to satisfy alignment constraints. <a href=\"http://en.wikipedia.org/wiki/Data_structure_al...
2008/09/23
[ "https://Stackoverflow.com/questions/119123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ]
Why does the `sizeof` operator return a size larger for a structure than the total sizes of the structure's members?
This is because of padding added to satisfy alignment constraints. [Data structure alignment](http://en.wikipedia.org/wiki/Data_structure_alignment) impacts both performance and correctness of programs: * Mis-aligned access might be a hard error (often `SIGBUS`). * Mis-aligned access might be a soft error. + Either corrected in hardware, for a modest performance-degradation. + Or corrected by emulation in software, for a severe performance-degradation. + In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors. Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes): ``` struct X { short s; /* 2 bytes */ /* 2 padding bytes */ int i; /* 4 bytes */ char c; /* 1 byte */ /* 3 padding bytes */ }; struct Y { int i; /* 4 bytes */ char c; /* 1 byte */ /* 1 padding byte */ short s; /* 2 bytes */ }; struct Z { int i; /* 4 bytes */ short s; /* 2 bytes */ char c; /* 1 byte */ /* 1 padding byte */ }; const int sizeX = sizeof(struct X); /* = 12 */ const int sizeY = sizeof(struct Y); /* = 8 */ const int sizeZ = sizeof(struct Z); /* = 8 */ ``` One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure `Z` in the example above). IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special `#pragma` statements to change the structure alignment settings.
119,160
<p>What is the difference between this:</p> <pre><code>this.btnOk.Click += new System.EventHandler(this.btnOK_Click); </code></pre> <p>and this?</p> <pre><code>this.btnOk.Click += this.btnOK_Click; </code></pre> <p>They both work. The former is what Visual Studio defaults to when you use the snippets. But it seems like it only ads extra verbiage, or am I missing something?</p>
[ { "answer_id": 119162, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 1, "selected": false, "text": "<p>I believe that C# since 3.0 has implicitly added the delegate handler. However, it can help to be more explici...
2008/09/23
[ "https://Stackoverflow.com/questions/119160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
What is the difference between this: ``` this.btnOk.Click += new System.EventHandler(this.btnOK_Click); ``` and this? ``` this.btnOk.Click += this.btnOK_Click; ``` They both work. The former is what Visual Studio defaults to when you use the snippets. But it seems like it only ads extra verbiage, or am I missing something?
No difference. Omitting the delegate instantiation is just syntax candy; the C# compiler will generate the delegate instantiation for you under the hood.
119,167
<p>I'm taking a look at how the model system in django works and I noticed something that I don't understand.</p> <p>I know that you create an empty <code>__init__.py</code> file to specify that the current directory is a package. And that you can set some variable in <code>__init__.py</code> so that import * works properly.</p> <p>But django adds a bunch of from ... import ... statements and defines a bunch of classes in <code>__init__.py</code>. Why? Doesn't this just make things look messy? Is there a reason that requires this code in <code>__init__.py</code>?</p>
[ { "answer_id": 119178, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 7, "selected": true, "text": "<p>All imports in <code>__init__.py</code> are made available when you import the package (directory) that contain...
2008/09/23
[ "https://Stackoverflow.com/questions/119167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3935/" ]
I'm taking a look at how the model system in django works and I noticed something that I don't understand. I know that you create an empty `__init__.py` file to specify that the current directory is a package. And that you can set some variable in `__init__.py` so that import \* works properly. But django adds a bunch of from ... import ... statements and defines a bunch of classes in `__init__.py`. Why? Doesn't this just make things look messy? Is there a reason that requires this code in `__init__.py`?
All imports in `__init__.py` are made available when you import the package (directory) that contains it. Example: `./dir/__init__.py`: ``` import something ``` `./test.py`: ``` import dir # can now use dir.something ``` EDIT: forgot to mention, the code in `__init__.py` runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code. EDIT2: dgrant pointed out to a possible confusion in my example. In `__init__.py` `import something` can import any module, not necessary from the package. For example, we can replace it with `import datetime`, then in our top level `test.py` both of these snippets will work: ``` import dir print dir.datetime.datetime.now() ``` and ``` import dir.some_module_in_dir print dir.datetime.datetime.now() ``` The bottom line is: all names assigned in `__init__.py`, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.
119,168
<p>I have a datagridview assigned a datasource to it. now how to add a new row to that grid and remove a row from it?</p>
[ { "answer_id": 119175, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 0, "selected": false, "text": "<p>I believe you'll have to get the Table collection item and retrieve the Row collection item from that. Then you ca...
2008/09/23
[ "https://Stackoverflow.com/questions/119168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a datagridview assigned a datasource to it. now how to add a new row to that grid and remove a row from it?
One way to do this is as follows: **Step #1** Setup the Data Adapter, Data Grid etc: ``` // the data grid DataGridView dataGrid; // create a new data table DataTable table = new DataTable(); // create the data adapter SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strDSN); // populate the table using the SQL adapter dataAdapter.Fill(table); // bind the table to a data source BindingSource dbSource = new BindingSource(); dbSource.DataSource = table; // finally bind the data source to the grid dataGrid.DataSource = dbSource; ``` **Step #2** Setup the Data Adapter SQL Commands: These SQL commands define how to move the data between the grid and the database via the adapter. ``` dataAdapter.DeleteCommand = new SqlCommand(...); dataAdapter.InsertCommand = new SqlCommand(...); dataAdapter.UpdateCommand = new SqlCommand(...); ``` **Step #3** Code to Remove Select lines from the Data Grid: ``` public int DeleteSelectedItems() { int itemsDeleted = 0; int count = dataGrid.RowCount; for (int i = count - 1; i >=0; --i) { DataGridViewRow row = dataGrid.Rows[i]; if (row.Selected == true) { dataGrid.Rows.Remove(row); // count the item deleted ++itemsDeleted; } } // commit the deletes made if (itemsDeleted > 0) Commit(); } ``` **Step #4** Handling Row Inserts and Row Changes: These types of changes are relatively easy to implement as you can let the grid manage the cell changes and new row inserts. The only thing you will have to decide is when do you commit these changes. I would recomment putting the commit in the **RowValidated** event handler of the DataGridView as at that point you should have a full row of data. **Step #5** Commit Method to Save the Changes back to the Database: This function will handle all the pending updates, insert and deletes and move these changes from the grid back into the database. ``` public void Commit() { SqlConnection cn = new SqlConnection(); cn.ConnectionString = "Do the connection using a DSN"; // open the connection cn.Open(); // commit any data changes dataAdapter.DeleteCommand.Connection = cn; dataAdapter.InsertCommand.Connection = cn; dataAdapter.UpdateCommand.Connection = cn; dataAdapter.Update(table); dataAdapter.DeleteCommand.Connection = null; dataAdapter.InsertCommand.Connection = null; dataAdapter.UpdateCommand.Connection = null; // clean up cn.Close(); } ```
119,197
<p>I have a question about how to do something "The Rails Way". With an application that has a public facing side and an admin interface what is the general consensus in the Rails community on how to do it?</p> <p>Namespaces, subdomains or forego them altogether?</p>
[ { "answer_id": 119301, "author": "psst", "author_id": 6392, "author_profile": "https://Stackoverflow.com/users/6392", "pm_score": 3, "selected": false, "text": "<p>In some smaller applications I don't think you need to separate the admin interface. Just use the regular interface and add ...
2008/09/23
[ "https://Stackoverflow.com/questions/119197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20899/" ]
I have a question about how to do something "The Rails Way". With an application that has a public facing side and an admin interface what is the general consensus in the Rails community on how to do it? Namespaces, subdomains or forego them altogether?
There's no real "Rails way" for admin interfaces, actually - you can find every possible solution in a number of applications. DHH has implied that he prefers namespaces (with HTTP Basic authentication), but that has remained a simple implication and not one of the official Rails Opinions. That said, I've found good success with that approach lately (namespacing + HTTP Basic). It looks like this: routes.rb: ``` map.namespace :admin do |admin| admin.resources :users admin.resources :posts end ``` admin/users\_controller.rb: ``` class Admin::UsersController < ApplicationController before_filter :admin_required # ... end ``` application.rb ``` class ApplicationController < ActionController::Base # ... protected def admin_required authenticate_or_request_with_http_basic do |user_name, password| user_name == 'admin' && password == 's3cr3t' end if RAILS_ENV == 'production' || params[:admin_http] end end ``` The conditional on `authenticate_or_request_with_http_basic` triggers the HTTP Basic auth in production mode or when you append `?admin_http=true` to any URL, so you can test it in your functional tests and by manually updating the URL as you browse your development site.
119,207
<p>I'm new to Ruby, and I'm trying the following: </p> <pre><code>mySet = numOfCuts.times.map{ rand(seqLength) } </code></pre> <p>but I get the 'yield called out of block' error. I'm not sure what his means. BTW, this question is part of a more general question I asked <a href="https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby"><strong>here</strong></a>.</p>
[ { "answer_id": 119226, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>if \"numOfCuts\" is an integer, </p>\n\n<pre><code>5.times.foo \n</code></pre>\n\n<p>is invalid </p>\n\n<p>\"t...
2008/09/23
[ "https://Stackoverflow.com/questions/119207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
I'm new to Ruby, and I'm trying the following: ``` mySet = numOfCuts.times.map{ rand(seqLength) } ``` but I get the 'yield called out of block' error. I'm not sure what his means. BTW, this question is part of a more general question I asked [**here**](https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby).
The problem is that the times method expects to get a block that it will yield control to. However you haven't passed a block to it. There are two ways to solve this. The first is to not use times: ``` mySet = (1..numOfCuts).map{ rand(seqLength) } ``` or else pass a block to it: ``` mySet = [] numOfCuts.times {mySet.push( rand(seqLength) )} ```
119,271
<p>Just wondering if someone could help me with some msbuild scripts that I am trying to write. What I would like to do is copy all the files and sub folders from a folder to another folder using msbuild.</p> <pre><code>{ProjectName} |-----&gt;Source |-----&gt;Tools |-----&gt;Viewer |-----{about 5 sub dirs} </code></pre> <p>What I need to be able to do is copy all the files and sub folders from the tools folder into the debug folder for the application. This is the code that I have so far.</p> <pre><code>&lt;ItemGroup&gt; &lt;Viewer Include=&quot;..\$(ApplicationDirectory)\Tools\viewer\**\*.*&quot; /&gt; &lt;/ItemGroup&gt; &lt;Target Name=&quot;BeforeBuild&quot;&gt; &lt;Copy SourceFiles=&quot;@(Viewer)&quot; DestinationFolder=&quot;@(Viewer-&gt;'$(OutputPath)\\Tools')&quot; /&gt; &lt;/Target&gt; </code></pre> <p>The build script runs but doesn't copy any of the files or folders.</p> <p>Thanks</p>
[ { "answer_id": 119288, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Did you try to specify concrete destination directory instead of</p>\n<pre><code>DestinationFolder=&quot;@(Viewer-&gt;'$(Outp...
2008/09/23
[ "https://Stackoverflow.com/questions/119271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
Just wondering if someone could help me with some msbuild scripts that I am trying to write. What I would like to do is copy all the files and sub folders from a folder to another folder using msbuild. ``` {ProjectName} |----->Source |----->Tools |----->Viewer |-----{about 5 sub dirs} ``` What I need to be able to do is copy all the files and sub folders from the tools folder into the debug folder for the application. This is the code that I have so far. ``` <ItemGroup> <Viewer Include="..\$(ApplicationDirectory)\Tools\viewer\**\*.*" /> </ItemGroup> <Target Name="BeforeBuild"> <Copy SourceFiles="@(Viewer)" DestinationFolder="@(Viewer->'$(OutputPath)\\Tools')" /> </Target> ``` The build script runs but doesn't copy any of the files or folders. Thanks
I was searching help on this too. It took me a while, but here is what I did that worked really well. ``` <Target Name="AfterBuild"> <ItemGroup> <ANTLR Include="..\Data\antlrcs\**\*.*" /> </ItemGroup> <Copy SourceFiles="@(ANTLR)" DestinationFolder="$(TargetDir)\%(RecursiveDir)" SkipUnchangedFiles="true" /> </Target> ``` This recursively copied the contents of the folder named `antlrcs` to the `$(TargetDir)`.
119,278
<p>I am using informix database, I want a query which you could also generate a row number along with the query</p> <p>Like</p> <pre><code>select row_number(),firstName,lastName from students; row_number() firstName lastName 1 john mathew 2 ricky pointing 3 sachin tendulkar </code></pre> <p>Here firstName, lastName are from Database, where as row number is generated in a query.</p>
[ { "answer_id": 120767, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 1, "selected": false, "text": "<p>I think the easiest way would be to use the following code and adjust its return accordingly.\n SELECT rowid, ...
2008/09/23
[ "https://Stackoverflow.com/questions/119278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using informix database, I want a query which you could also generate a row number along with the query Like ``` select row_number(),firstName,lastName from students; row_number() firstName lastName 1 john mathew 2 ricky pointing 3 sachin tendulkar ``` Here firstName, lastName are from Database, where as row number is generated in a query.
The best way is to use a (newly initialized) sequence. ``` begin work; create sequence myseq; select myseq.nextval,s.firstName,s.lastName from students s; drop sequence myseq; commit work; ```
119,281
<ol> <li><p>New class is a subclass of the original object</p></li> <li><p>It needs to be php4 compatible</p></li> </ol>
[ { "answer_id": 119287, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 1, "selected": false, "text": "<p>I would imagine you would have to invent some sort of a \"copy constructor\". Then you would just create a new sub...
2008/09/23
[ "https://Stackoverflow.com/questions/119281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20907/" ]
1. New class is a subclass of the original object 2. It needs to be php4 compatible
You could have your classes instantiated empty and then loaded by any number of methods. One of these methods could accept an instance of the parent class as an argument, and then copy its data from there ``` class childClass extends parentClass { function childClass() { //do nothing } function loadFromParentObj( $parentObj ) { $this->a = $parentObj->a; $this->b = $parentObj->b; $this->c = $parentObj->c; } }; $myParent = new parentClass(); $myChild = new childClass(); $myChild->loadFromParentObj( $myParent ); ```
119,284
<p>I would like to be able to override the default behaviour for positioning the caret in a masked textbox.</p> <p>The default is to place the caret where the mouse was clicked, the masked textbox already contains characters due to the mask.</p> <p>I know that you can hide the caret as mentioned in this <a href="https://stackoverflow.com/questions/44131/how-do-i-hide-the-input-caret-in-a-systemwindowsformstextbox">post</a>, is there something similar for positioning the caret at the beginning of the textbox when the control gets focus. </p>
[ { "answer_id": 119368, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 6, "selected": true, "text": "<p>This should do the trick:</p>\n\n<pre><code> private void maskedTextBox1_Enter(object sender, EventArgs e)\n {\n ...
2008/09/23
[ "https://Stackoverflow.com/questions/119284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
I would like to be able to override the default behaviour for positioning the caret in a masked textbox. The default is to place the caret where the mouse was clicked, the masked textbox already contains characters due to the mask. I know that you can hide the caret as mentioned in this [post](https://stackoverflow.com/questions/44131/how-do-i-hide-the-input-caret-in-a-systemwindowsformstextbox), is there something similar for positioning the caret at the beginning of the textbox when the control gets focus.
This should do the trick: ``` private void maskedTextBox1_Enter(object sender, EventArgs e) { this.BeginInvoke((MethodInvoker)delegate() { maskedTextBox1.Select(0, 0); }); } ```
119,286
<p>Consider the following ruby code</p> <p>test.rb:</p> <pre><code>begin puts thisFunctionDoesNotExist x = 1+1 rescue Exception =&gt; e p e end </code></pre> <p>For debugging purposes, I would like the rescue block to know that the error occurred in line 4 of this file. Is there a clean way of doing that?</p>
[ { "answer_id": 119304, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 7, "selected": true, "text": "<pre><code>p e.backtrace \n</code></pre>\n\n<p>I ran it on an IRB session which has no source and it still gave releva...
2008/09/23
[ "https://Stackoverflow.com/questions/119286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17674/" ]
Consider the following ruby code test.rb: ``` begin puts thisFunctionDoesNotExist x = 1+1 rescue Exception => e p e end ``` For debugging purposes, I would like the rescue block to know that the error occurred in line 4 of this file. Is there a clean way of doing that?
``` p e.backtrace ``` I ran it on an IRB session which has no source and it still gave relevant info. ``` => ["(irb):11:in `foo'", "(irb):17:in `irb_binding'", "/usr/lib64/ruby/1.8/irb/workspace.rb:52:in `irb_binding'", "/usr/lib64/ruby/1.8/irb/workspace.rb:52"] ``` If you want a nicely parsed backtrace, the following regex might be handy: ``` p x.backtrace.map{ |x| x.match(/^(.+?):(\d+)(|:in `(.+)')$/); [$1,$2,$4] } [ ["(irb)", "11", "foo"], ["(irb)", "48", "irb_binding"], ["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", "irb_binding"], ["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", nil] ] ``` ( Regex /should/ be safe against weird characters in function names or directories/filenames ) ( If you're wondering where foo camefrom, i made a def to grab the exception out : ``` >>def foo >> thisFunctionDoesNotExist >> rescue Exception => e >> return e >>end >>x = foo >>x.backtrace ```
119,295
<p>Within our Active Directory domain, we have a MS SQL 2005 server, and a SharePoint (MOSS 3.0 I believe) server. Both authenticate against our LDAP server. Would like to allow these authenticated SharePoint visitors to see some of the data from the MS SQL database. Primary challenge is authentication.</p> <p>Any tips on getting the pass-through authentication to work? I have searched (Google) for a proper connection string to use, but keep finding ones that have embedded credentials or other schemes. I gather that SSPI is what I want to use, but am not sure how to implement.</p> <p>clarification: we don't have a single-sign-on server (e.g. Shibboleth) setup yet</p>
[ { "answer_id": 119348, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 2, "selected": true, "text": "<p>If you are using C# the code and connection string is:</p>\n\n<pre><code>using System.Data.SqlClient; \n... \nSqlConnect...
2008/09/23
[ "https://Stackoverflow.com/questions/119295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18484/" ]
Within our Active Directory domain, we have a MS SQL 2005 server, and a SharePoint (MOSS 3.0 I believe) server. Both authenticate against our LDAP server. Would like to allow these authenticated SharePoint visitors to see some of the data from the MS SQL database. Primary challenge is authentication. Any tips on getting the pass-through authentication to work? I have searched (Google) for a proper connection string to use, but keep finding ones that have embedded credentials or other schemes. I gather that SSPI is what I want to use, but am not sure how to implement. clarification: we don't have a single-sign-on server (e.g. Shibboleth) setup yet
If you are using C# the code and connection string is: ``` using System.Data.SqlClient; ... SqlConnection oSQLConn = new SqlConnection(); oSQLConn.ConnectionString = "Data Source=(local);" + "Initial Catalog=myDatabaseName;" + "Integrated Security=SSPI"; //Or // "Server=(local);" + // "Database=myDatabaseName;" + // "Trusted_Connection=Yes"; oSQLConn.Open(); ... oSQLConn.Close(); ``` An excellent resource for connection strings can be found at [Carl Prothman's Blog](http://www.carlprothman.net/Default.aspx?tabid=81). Yoy should probably replace `(local)` with the name of the SQL server. You will need to either configure SQL server to give the Domain Roles the access privilages you want. In SQL server you will need to go to Security\Logins and make sure you have the Domain\User Role (ie MyCompany\SharpointUsers). In your config you should have
119,308
<p>I have a huge database with some 100 tables and some 250 stored procedures. I want to know the list of tables affected by a subset of stored procedures. For example, I have a list of 50 stored procedures, out of 250, and I want to know the list of tables that will be affected by these 50 stored procedures. Is there any easy way for doing this, other than reading all the stored procedures and finding the list of tables manually? </p> <p>PS: I am using SQL Server 2000 and SQL Server 2005 clients for this.</p>
[ { "answer_id": 119333, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": -1, "selected": false, "text": "<p>One very invasive option would be to get a duplicate database and set a trigger on every table that logs that something happ...
2008/09/23
[ "https://Stackoverflow.com/questions/119308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a huge database with some 100 tables and some 250 stored procedures. I want to know the list of tables affected by a subset of stored procedures. For example, I have a list of 50 stored procedures, out of 250, and I want to know the list of tables that will be affected by these 50 stored procedures. Is there any easy way for doing this, other than reading all the stored procedures and finding the list of tables manually? PS: I am using SQL Server 2000 and SQL Server 2005 clients for this.
This would be your SQL Server query: ``` SELECT [NAME] FROM sysobjects WHERE xType = 'U' AND --specifies a user table object id in ( SELECT sd.depid FROM sysobjects so, sysdepends sd WHERE so.name = 'NameOfStoredProcedure' AND sd.id = so.id ) ``` Hope this helps someone.
119,328
<p>How do I truncate a java <code>String</code> so that I know it will fit in a given number of bytes storage once it is UTF-8 encoded?</p>
[ { "answer_id": 119338, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 3, "selected": false, "text": "<p>UTF-8 encoding has a neat trait that allows you to see where in a byte-set you are.</p>\n\n<p>check the stream at ...
2008/09/23
[ "https://Stackoverflow.com/questions/119328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4220/" ]
How do I truncate a java `String` so that I know it will fit in a given number of bytes storage once it is UTF-8 encoded?
Here is a simple loop that counts how big the UTF-8 representation is going to be, and truncates when it is exceeded: ``` public static String truncateWhenUTF8(String s, int maxBytes) { int b = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // ranges from http://en.wikipedia.org/wiki/UTF-8 int skip = 0; int more; if (c <= 0x007f) { more = 1; } else if (c <= 0x07FF) { more = 2; } else if (c <= 0xd7ff) { more = 3; } else if (c <= 0xDFFF) { // surrogate area, consume next char as well more = 4; skip = 1; } else { more = 3; } if (b + more > maxBytes) { return s.substring(0, i); } b += more; i += skip; } return s; } ``` This *does* handle [surrogate pairs](http://en.wikipedia.org/wiki/UTF-16) that appear in the input string. Java's UTF-8 encoder (correctly) outputs surrogate pairs as a single 4-byte sequence instead of two 3-byte sequences, so `truncateWhenUTF8()` will return the longest truncated string it can. If you ignore surrogate pairs in the implementation then the truncated strings may be shorted than they needed to be. I haven't done a lot of testing on that code, but here are some preliminary tests: ``` private static void test(String s, int maxBytes, int expectedBytes) { String result = truncateWhenUTF8(s, maxBytes); byte[] utf8 = result.getBytes(Charset.forName("UTF-8")); if (utf8.length > maxBytes) { System.out.println("BAD: our truncation of " + s + " was too big"); } if (utf8.length != expectedBytes) { System.out.println("BAD: expected " + expectedBytes + " got " + utf8.length); } System.out.println(s + " truncated to " + result); } public static void main(String[] args) { test("abcd", 0, 0); test("abcd", 1, 1); test("abcd", 2, 2); test("abcd", 3, 3); test("abcd", 4, 4); test("abcd", 5, 4); test("a\u0080b", 0, 0); test("a\u0080b", 1, 1); test("a\u0080b", 2, 1); test("a\u0080b", 3, 3); test("a\u0080b", 4, 4); test("a\u0080b", 5, 4); test("a\u0800b", 0, 0); test("a\u0800b", 1, 1); test("a\u0800b", 2, 1); test("a\u0800b", 3, 1); test("a\u0800b", 4, 4); test("a\u0800b", 5, 5); test("a\u0800b", 6, 5); // surrogate pairs test("\uD834\uDD1E", 0, 0); test("\uD834\uDD1E", 1, 0); test("\uD834\uDD1E", 2, 0); test("\uD834\uDD1E", 3, 0); test("\uD834\uDD1E", 4, 4); test("\uD834\uDD1E", 5, 4); } ``` **Updated** Modified code example, it now handles surrogate pairs.
119,336
<p>I've got a customer trying to access one of my sites, and they keep getting this error > ssl_error_rx_record_too_long</p> <p>They're getting this error on all browsers, all platforms. I can't reproduce the problem at all.</p> <p>My server and myself are located in the USA, the customer is located in India.</p> <p>I googled on the problem, and the main source seems to be that the SSL port is speaking in HTTP. I checked my server, and this is not happening. I tried <a href="http://support.servertastic.com/error-code-ssl-error-rx-record-too-long/" rel="noreferrer">the solution mentioned here</a>, but the customer has stated it did not fix the issue.</p> <p>Can anyone tell me how I can fix this, or how I can reproduce this???</p> <p><strong>THE SOLUTION</strong></p> <p>Turns out the customer had a misconfigured local proxy!</p> <p>Hope that helps anyone finding this question trying to debug it in the future.</p>
[ { "answer_id": 119345, "author": "dan-manges", "author_id": 20072, "author_profile": "https://Stackoverflow.com/users/20072", "pm_score": 3, "selected": false, "text": "<p>Ask the user for the exact URL they're using in their browser. If they're entering <a href=\"https://your.site:80\" ...
2008/09/23
[ "https://Stackoverflow.com/questions/119336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10596/" ]
I've got a customer trying to access one of my sites, and they keep getting this error > ssl\_error\_rx\_record\_too\_long They're getting this error on all browsers, all platforms. I can't reproduce the problem at all. My server and myself are located in the USA, the customer is located in India. I googled on the problem, and the main source seems to be that the SSL port is speaking in HTTP. I checked my server, and this is not happening. I tried [the solution mentioned here](http://support.servertastic.com/error-code-ssl-error-rx-record-too-long/), but the customer has stated it did not fix the issue. Can anyone tell me how I can fix this, or how I can reproduce this??? **THE SOLUTION** Turns out the customer had a misconfigured local proxy! Hope that helps anyone finding this question trying to debug it in the future.
The [link mentioned by Subimage](http://support.servertastic.com/error-code-ssl-error-rx-record-too-long/) was right on the money for me. It suggested changing the virtual host tag, ie, from `<VirtualHost myserver.example.com:443>` to `<VirtualHost _default_:443>` > > Error code: `ssl_error_rx_record_too_long` > > > This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate. > > > Below are some things we recommend trying. > > > * Ensure that port 443 is open and enabled on your server. This is the standard port for https communications. > * If SSL is using a non-standard port then FireFox 3 can sometimes give this error. Ensure SSL is running on port 443. > * If using Apache2 check that you are using port 443 for SSL. This can be done by setting the ports.conf file as follows > > > > ``` > Listen 80 > Listen 443 https > > ``` > * Make sure you do not have more than one SSL certificate sharing the same IP. Please ensure that all SSL certificates utilise their own dedicated IP. > * If using Apache2 check your vhost config. Some users have reported changing `<VirtualHost>` to `_default_` resolved the error. > > > That fixed my problem. It's rare that I google an error message and get the first hit with the right answer! :-) *In addition to the above*, these are some other solutions that other folks have found were causing the issue: * Make sure that your SSL certificate is not expired * Try to specify the Cipher: `SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3`
119,404
<p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
[ { "answer_id": 119418, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 6, "selected": true, "text": "<p>You can use <a href=\"http://spacepants.org/src/pymad/\" rel=\"noreferrer\">pymad</a>. It's an external library, ...
2008/09/23
[ "https://Stackoverflow.com/questions/119404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9440/" ]
What is the simplest way to determine the length (in seconds) of a given mp3 file, **without using outside libraries**? (python source highly appreciated)
You can use [pymad](http://spacepants.org/src/pymad/). It's an external library, but don't fall for the Not Invented Here trap. Any particular reason you don't want any external libraries? ``` import mad mf = mad.MadFile("foo.mp3") track_length_in_milliseconds = mf.total_time() ``` Spotted [here](http://simonwillison.net/2003/Dec/4/mp3lengths/). -- If you really don't want to use an external library, have a look [here](http://ibofobi.dk/stuff/mp3/) and check out how he's done it. Warning: it's complicated.
119,426
<p>Are there any industry standard conventions for naming jar files?</p>
[ { "answer_id": 119430, "author": "Ron Tuffin", "author_id": 939, "author_profile": "https://Stackoverflow.com/users/939", "pm_score": 6, "selected": true, "text": "<p>I have been using </p>\n\n<pre><code>*Informative*-*name*-*M*.*m*.*b*.jar\n</code></pre>\n\n<p>Where:</p>\n\n<p><em>M</em...
2008/09/23
[ "https://Stackoverflow.com/questions/119426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]
Are there any industry standard conventions for naming jar files?
I have been using ``` *Informative*-*name*-*M*.*m*.*b*.jar ``` Where: *M* = `major version number` (changed when backward compatibility is not necessarily maintained) *m* = `minor version number` (feature additions etc) *b* = `build number` (for releases containing bug fixes)
119,432
<p>Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing.</p> <p>Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)?</p>
[ { "answer_id": 119442, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 0, "selected": false, "text": "<p>You could potentially make an Ajax call to the server from a try/catch, but that's probably about the best you can do.</...
2008/09/23
[ "https://Stackoverflow.com/questions/119432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17558/" ]
Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing. Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)?
You could try setting up your own handler for the [onerror event](http://developer.mozilla.org/En/DOM:window.onerror) and use XMLHttpRequest to tell the server what went wrong, however since it's not part of any specification, [support is somewhat flaky](http://www.quirksmode.org/dom/events/error.html). Here's an example from [Using XMLHttpRequest to log JavaScript errors](http://www.the-art-of-web.com/javascript/ajax-onerror/): ``` window.onerror = function(msg, url, line) { var req = new XMLHttpRequest(); var params = "msg=" + encodeURIComponent(msg) + '&amp;url=' + encodeURIComponent(url) + "&amp;line=" + line; req.open("POST", "/scripts/logerror.php"); req.send(params); }; ```
119,441
<p>I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word &quot;dolor&quot; in this text:</p> <pre class="lang-html prettyprint-override"><code>&lt;p&gt; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. &lt;/p&gt; &lt;p&gt; Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. &lt;/p&gt; </code></pre> <p>How do I convert the above to something like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;p&gt; Lorem ipsum &lt;span class=&quot;myClass&quot;&gt;dolor&lt;/span&gt; sit amet, consectetuer adipiscing elit. &lt;/p&gt; &lt;p&gt; Quisque bibendum sem ut lacus. Integer &lt;span class=&quot;myClass&quot;&gt;dolor&lt;/span&gt; ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. &lt;/p&gt; </code></pre> <p>Is this possible with jQuery?</p> <p><strong>Edit</strong>: As <a href="https://stackoverflow.com/users/9535/sebastian-hoitz">Sebastian</a> <a href="https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery#119450">pointed out</a>, this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy.</p>
[ { "answer_id": 119450, "author": "Sebastian Hoitz", "author_id": 9535, "author_profile": "https://Stackoverflow.com/users/9535", "pm_score": 1, "selected": false, "text": "<p>You need to get the content of the p tag and replace all the dolors in it with the highlighted version.</p>\n\n<p...
2008/09/23
[ "https://Stackoverflow.com/questions/119441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text: ```html <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p> <p> Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. </p> ``` How do I convert the above to something like this: ```html <p> Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit. </p> <p> Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. </p> ``` Is this possible with jQuery? **Edit**: As [Sebastian](https://stackoverflow.com/users/9535/sebastian-hoitz) [pointed out](https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery#119450), this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy.
~~Try [highlight: JavaScript text highlighting jQuery plugin](http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html).~~ **Warning: The source code available on this page contains a cryptocurrency mining script, either use the code below or remove the mining script from the script downloaded from the website.** ``` /* highlight v4 Highlights arbitrary terms. <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html> MIT license. Johann Burkard <http://johannburkard.de> <mailto:jb@eaio.com> */ jQuery.fn.highlight = function(pat) { function innerHighlight(node, pat) { var skip = 0; if (node.nodeType == 3) { var pos = node.data.toUpperCase().indexOf(pat); if (pos >= 0) { var spannode = document.createElement('span'); spannode.className = 'highlight'; var middlebit = node.splitText(pos); var endbit = middlebit.splitText(pat.length); var middleclone = middlebit.cloneNode(true); spannode.appendChild(middleclone); middlebit.parentNode.replaceChild(spannode, middlebit); skip = 1; } } else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { for (var i = 0; i < node.childNodes.length; ++i) { i += innerHighlight(node.childNodes[i], pat); } } return skip; } return this.length && pat && pat.length ? this.each(function() { innerHighlight(this, pat.toUpperCase()); }) : this; }; jQuery.fn.removeHighlight = function() { return this.find("span.highlight").each(function() { this.parentNode.firstChild.nodeName; with (this.parentNode) { replaceChild(this.firstChild, this); normalize(); } }).end(); }; ``` Also try the ["updated" version of the original script](http://bartaz.github.com/sandbox.js/jquery.highlight.html). ``` /* * jQuery Highlight plugin * * Based on highlight v3 by Johann Burkard * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html * * Code a little bit refactored and cleaned (in my humble opinion). * Most important changes: * - has an option to highlight only entire words (wordsOnly - false by default), * - has an option to be case sensitive (caseSensitive - false by default) * - highlight element tag and class names can be specified in options * * Usage: * // wrap every occurrance of text 'lorem' in content * // with <span class='highlight'> (default options) * $('#content').highlight('lorem'); * * // search for and highlight more terms at once * // so you can save some time on traversing DOM * $('#content').highlight(['lorem', 'ipsum']); * $('#content').highlight('lorem ipsum'); * * // search only for entire word 'lorem' * $('#content').highlight('lorem', { wordsOnly: true }); * * // don't ignore case during search of term 'lorem' * $('#content').highlight('lorem', { caseSensitive: true }); * * // wrap every occurrance of term 'ipsum' in content * // with <em class='important'> * $('#content').highlight('ipsum', { element: 'em', className: 'important' }); * * // remove default highlight * $('#content').unhighlight(); * * // remove custom highlight * $('#content').unhighlight({ element: 'em', className: 'important' }); * * * Copyright (c) 2009 Bartek Szopka * * Licensed under MIT license. * */ jQuery.extend({ highlight: function (node, re, nodeName, className) { if (node.nodeType === 3) { var match = node.data.match(re); if (match) { var highlight = document.createElement(nodeName || 'span'); highlight.className = className || 'highlight'; var wordNode = node.splitText(match.index); wordNode.splitText(match[0].length); var wordClone = wordNode.cloneNode(true); highlight.appendChild(wordClone); wordNode.parentNode.replaceChild(highlight, wordNode); return 1; //skip added node in parent } } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children !/(script|style)/i.test(node.tagName) && // ignore script and style nodes !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted for (var i = 0; i < node.childNodes.length; i++) { i += jQuery.highlight(node.childNodes[i], re, nodeName, className); } } return 0; } }); jQuery.fn.unhighlight = function (options) { var settings = { className: 'highlight', element: 'span' }; jQuery.extend(settings, options); return this.find(settings.element + "." + settings.className).each(function () { var parent = this.parentNode; parent.replaceChild(this.firstChild, this); parent.normalize(); }).end(); }; jQuery.fn.highlight = function (words, options) { var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false }; jQuery.extend(settings, options); if (words.constructor === String) { words = [words]; } words = jQuery.grep(words, function(word, i){ return word != ''; }); words = jQuery.map(words, function(word, i) { return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }); if (words.length == 0) { return this; }; var flag = settings.caseSensitive ? "" : "i"; var pattern = "(" + words.join("|") + ")"; if (settings.wordsOnly) { pattern = "\\b" + pattern + "\\b"; } var re = new RegExp(pattern, flag); return this.each(function () { jQuery.highlight(this, re, settings.element, settings.className); }); }; ```
119,462
<p>I'd like to remove all of the black from a picture attached to a sprite so that it becomes transparent. </p>
[ { "answer_id": 124493, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>This looks like it'll do the trick:</p>\n\n<p><a href=\"http://www.quartzcompositions.com/phpBB2/viewtopic.php?t=281\" rel=...
2008/09/23
[ "https://Stackoverflow.com/questions/119462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20824/" ]
I'd like to remove all of the black from a picture attached to a sprite so that it becomes transparent.
I'll copy and paste in case that link dies: *" I used a 'Color Matrix' patch, setting 'Alpha Vector (W)' and 'Bias Vector(X,Y,Z)' to 1 and all other to 0. You will then find the alpha channel from the input image at the output."* I found this before, but I can't figure out exactly how to do it. I found another solution using core image filter: ``` kernel vec4 darkToTransparent(sampler image) { vec4 color = sample(image, samplerCoord(image)); color.a = (color.r+color.g+color.b) > 0.005 ? 1.0:0.; return color; } ```
119,477
<p>I have an MSSQL2005 stored procedure here, which is supposed to take an XML message as input, and store it's content into a table. The table fields are varchars, because our delphi backend application could not handle unicode. Now, the messages that come in, are encoded ISO-8859-1. All is fine until characters over the > 128 standard set are included (in this case, ÄÖäö, which are an integral part of finnish). This causes the DB server to raise exception 0xc00ce508. The database's default, as well as the table's and field's, collation is set to latin1, which should be the same as ISO-8859-1.</p> <p>The XML message is parsed using the XML subsystem, like so:</p> <pre><code>ALTER PROCEDURE [dbo].[parse] @XmlIn NVARCHAR(1000) AS SET NOCOUNT ON DECLARE @XmlDocumentHandle INT DECLARE @XmlDocument VARCHAR(1000) BEGIN SET @XmlDocument = @XmlIn EXECUTE sp_xml_preparedocument @XmlDocumentHandle OUTPUT, @XmlDocument BEGIN TRANSACTION //the xml message's fields are looped through here, and rows added or modified in two tables accordingly // like ... DECLARE TempCursor CURSOR FOR SELECT AM_WORK_ID,CUSTNO,STYPE,REFE,VIN_NUMBER,REG_NO,VEHICLE_CONNO,READY_FOR_INVOICE,IS_SP,SMANID,INVOICENO,SUB_STATUS,TOTAL,TOTAL0,VAT,WRKORDNO FROM OPENXML (@XmlDocumentHandle, '/ORDER_NEW_CP_REQ/ORDER_NEW_CUSTOMER_REQ',8) WITH (AM_WORK_ID int '@EXIDNO',CUSTNO int '@CUSTNO',STYPE VARCHAR(1) '@STYPE',REFE VARCHAR(50) '@REFE',VIN_NUMBER VARCHAR(30) '@VEHICLE_VINNO', REG_NO VARCHAR(20) '@VEHICLE_LICNO',VEHICLE_CONNO VARCHAR(30) '@VEHICLE_CONNO',READY_FOR_INVOICE INT '@READY_FOR_INVOICE',IS_SP INT '@IS_SP', SMANID INT '@SMANID',INVOICENO INT '@INVOICENO',SUB_STATUS VARCHAR(1) '@SUB_STATUS',TOTAL NUMERIC(12,2) '@TOTAL',TOTAL0 NUMERIC(12,2) '@TOTAL0',VAT NUMERIC(12,2) '@VAT',WRKORDNO INT '@WRKORDNO') OPEN TempCursor FETCH NEXT FROM TempCursor INTO @wAmWork,@wCustNo,@wType,@wRefe,@wVIN,@wReg,@wConNo,@wRdy,@wIsSp,@wSMan,@wInvoNo,@wSubStatus,@wTot,@wTot0,@wVat,@wWrkOrdNo // ... etc COMMIT TRANSACTION EXECUTE sp_xml_removedocument @XmlDocumentHandle END </code></pre> <p>Previously, the stored procedure used to use nvarchar for input, but since that caused problems with the ancient backend application (Delphi 5 + ODBC), we had to switch the fields to varchars, at which point everything broke.</p> <p>I also tried taking in nvarchar and converting that to varchar at the start, but the result is the same.</p>
[ { "answer_id": 119836, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 0, "selected": false, "text": "<p>The errorcode you mention seems to come from the MSXML Library. How is that involved there? From your question I would as...
2008/09/23
[ "https://Stackoverflow.com/questions/119477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15477/" ]
I have an MSSQL2005 stored procedure here, which is supposed to take an XML message as input, and store it's content into a table. The table fields are varchars, because our delphi backend application could not handle unicode. Now, the messages that come in, are encoded ISO-8859-1. All is fine until characters over the > 128 standard set are included (in this case, ÄÖäö, which are an integral part of finnish). This causes the DB server to raise exception 0xc00ce508. The database's default, as well as the table's and field's, collation is set to latin1, which should be the same as ISO-8859-1. The XML message is parsed using the XML subsystem, like so: ``` ALTER PROCEDURE [dbo].[parse] @XmlIn NVARCHAR(1000) AS SET NOCOUNT ON DECLARE @XmlDocumentHandle INT DECLARE @XmlDocument VARCHAR(1000) BEGIN SET @XmlDocument = @XmlIn EXECUTE sp_xml_preparedocument @XmlDocumentHandle OUTPUT, @XmlDocument BEGIN TRANSACTION //the xml message's fields are looped through here, and rows added or modified in two tables accordingly // like ... DECLARE TempCursor CURSOR FOR SELECT AM_WORK_ID,CUSTNO,STYPE,REFE,VIN_NUMBER,REG_NO,VEHICLE_CONNO,READY_FOR_INVOICE,IS_SP,SMANID,INVOICENO,SUB_STATUS,TOTAL,TOTAL0,VAT,WRKORDNO FROM OPENXML (@XmlDocumentHandle, '/ORDER_NEW_CP_REQ/ORDER_NEW_CUSTOMER_REQ',8) WITH (AM_WORK_ID int '@EXIDNO',CUSTNO int '@CUSTNO',STYPE VARCHAR(1) '@STYPE',REFE VARCHAR(50) '@REFE',VIN_NUMBER VARCHAR(30) '@VEHICLE_VINNO', REG_NO VARCHAR(20) '@VEHICLE_LICNO',VEHICLE_CONNO VARCHAR(30) '@VEHICLE_CONNO',READY_FOR_INVOICE INT '@READY_FOR_INVOICE',IS_SP INT '@IS_SP', SMANID INT '@SMANID',INVOICENO INT '@INVOICENO',SUB_STATUS VARCHAR(1) '@SUB_STATUS',TOTAL NUMERIC(12,2) '@TOTAL',TOTAL0 NUMERIC(12,2) '@TOTAL0',VAT NUMERIC(12,2) '@VAT',WRKORDNO INT '@WRKORDNO') OPEN TempCursor FETCH NEXT FROM TempCursor INTO @wAmWork,@wCustNo,@wType,@wRefe,@wVIN,@wReg,@wConNo,@wRdy,@wIsSp,@wSMan,@wInvoNo,@wSubStatus,@wTot,@wTot0,@wVat,@wWrkOrdNo // ... etc COMMIT TRANSACTION EXECUTE sp_xml_removedocument @XmlDocumentHandle END ``` Previously, the stored procedure used to use nvarchar for input, but since that caused problems with the ancient backend application (Delphi 5 + ODBC), we had to switch the fields to varchars, at which point everything broke. I also tried taking in nvarchar and converting that to varchar at the start, but the result is the same.
I don't know if anybody with enough rights to edit the answer will see this but while the answer is correct I would like to add that without specifying the collation explicitly the default collation of the database would be used in this case since it is implicitly assigned to every varchar-variable without a collation statement. So ``` DECLARE @XmlDocument VARCHAR(2000) COLLATE SQL_Latin1_General_CP1_CI_AS ``` should do the trick, too.
119,548
<p>I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients. </p> <p>The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error:</p> <blockquote> <p>The process cannot access the file because it is being used by another process.</p> </blockquote> <p>The solutions that I have tried to implement in C# and failed are as below.</p> <ol> <li>Implemented singleton class that contains code that writes to a file.</li> <li>Used lock statement to wrap the code that writes to the file. </li> <li>I have also tried to use open source logger log4net but it also is not a perfect solution. </li> <li>I know about logging to system event logger, but I do not have that choice.</li> </ol> <p>I want to know if there exists a perfect and complete solution to such a problem? </p>
[ { "answer_id": 119564, "author": "Joel", "author_id": 13713, "author_profile": "https://Stackoverflow.com/users/13713", "pm_score": 0, "selected": false, "text": "<p>Maybe write a \"queue line\" of sorts for writing to the file, so when you try to write to the file it keeps checking to s...
2008/09/23
[ "https://Stackoverflow.com/questions/119548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20933/" ]
I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients. The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error: > > The process cannot access the file because it is being used by another process. > > > The solutions that I have tried to implement in C# and failed are as below. 1. Implemented singleton class that contains code that writes to a file. 2. Used lock statement to wrap the code that writes to the file. 3. I have also tried to use open source logger log4net but it also is not a perfect solution. 4. I know about logging to system event logger, but I do not have that choice. I want to know if there exists a perfect and complete solution to such a problem?
The locking is probably failing because your webservice is being run by more than one worker process. You could protect the access with a named mutex, which is shared across processes, unlike the locks you get by using `lock(someobject) {...}`: ``` Mutex lock = new Mutex("mymutex", false); lock.WaitOne(); // access file lock.ReleaseMutex(); ```
119,559
<p>Is there an easy way to programmatically determine the number of lines within a text file? </p>
[ { "answer_id": 119572, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 10, "selected": true, "text": "<p><strong>Seriously belated edit: If you're using .NET 4.0 or later</strong></p>\n\n<p>The <code>File</code> class has...
2008/09/23
[ "https://Stackoverflow.com/questions/119559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
Is there an easy way to programmatically determine the number of lines within a text file?
**Seriously belated edit: If you're using .NET 4.0 or later** The `File` class has a new [`ReadLines`](http://msdn.microsoft.com/en-us/library/dd383503.aspx) method which lazily enumerates lines rather than greedily reading them all into an array like `ReadAllLines`. So now you can have both efficiency and conciseness with: ``` var lineCount = File.ReadLines(@"C:\file.txt").Count(); ``` --- **Original Answer** If you're not too bothered about efficiency, you can simply write: ``` var lineCount = File.ReadAllLines(@"C:\file.txt").Length; ``` For a more efficient method you could do: ``` var lineCount = 0; using (var reader = File.OpenText(@"C:\file.txt")) { while (reader.ReadLine() != null) { lineCount++; } } ``` **Edit: In response to questions about efficiency** The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large). In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler.
119,578
<p>What is the best way to disable the warnings generated via <code>_CRT_SECURE_NO_DEPRECATE</code> that allows them to be reinstated with ease and will work across Visual Studio versions?</p>
[ { "answer_id": 119619, "author": "dennisV", "author_id": 20208, "author_profile": "https://Stackoverflow.com/users/20208", "pm_score": 1, "selected": false, "text": "<p>You can define the _CRT_SECURE_NO_WARNINGS symbol to suppress them and undefine it to reinstate them back.</p>\n" }, ...
2008/09/23
[ "https://Stackoverflow.com/questions/119578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8516/" ]
What is the best way to disable the warnings generated via `_CRT_SECURE_NO_DEPRECATE` that allows them to be reinstated with ease and will work across Visual Studio versions?
If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add `_CRT_SECURE_NO_WARNINGS` symbol to your project settings via "Project"->"Properties"->"Configuration properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions". Also you can define it just before you include a header file which generates this warning. You should add something like this ``` #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif ``` And just a small remark, make sure you understand what this warning stands for, and maybe, if you don't intend to use other compilers than MSVC, consider using safer version of functions i.e. strcpy\_s instead of strcpy.
119,588
<p>I've just built a basic ASP MVC web site for deployment on our intranet. It expects users to be on the same domain as the IIS box and if you're not an authenticated Windows User, you should not get access.</p> <p>I've just deployed this to IIS6 running on Server 2003 R2 SP2. The web app is configured with it's own pool with it's own pool user account. The IIS Directory Security options for the web app are set to "Windows Integrated Security" only and the web.config file has:</p> <pre><code>&lt;authentication mode="Windows" /&gt; </code></pre> <p>From a Remote Desktop session on the IIS6 server itself, an IE7 browser window can successfully authenticate and navigate the web app if accessed via <a href="http://localhost/myapp" rel="nofollow noreferrer">http://localhost/myapp</a>.</p> <p>However, also from the server, if accessed via the server's name (ie <a href="http://myserver/myapp" rel="nofollow noreferrer">http://myserver/myapp</a>) then IE7 presents a credentials dialog which after three attempts entering the correct credentials eventually returns "HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials".</p> <p>The same problem occurs when a workstation browses to the web app url (naturally using the server's name and not "localhost").</p> <p>The IIS6 server is a member of the only domain we have and has no firewall enabled.</p> <p>Is there something I have failed to configure correctly for this to work?</p> <p>Thanks,</p> <hr> <p>I have tried the suggestions from Matt Ryan, Graphain, and Mike Dimmick to date without success. I have just built a virtual machine test lab with a Server 2003 DC and a separate server 2003 IIS6 server and I am able to replicate the problem.</p> <p>I am seeing an entry in the IIS6 server's System Event Log the first time I try to access the site via the non-localhost url (ie <a href="http://iis/myapp" rel="nofollow noreferrer">http://iis/myapp</a>). FQDN urls fail too. </p> <blockquote> <p><em>Source: Kerberos, Event ID: 4</em><br> The kerberos client received a KRB_AP_ERR_MODIFIED error from the server host/iis.test.local. The target name used was HTTP/iis.test.local. This indicates that the password used to encrypt the kerberos service ticket is different than that on the target server. Commonly, this is due to identically named machine accounts in the target realm (TEST.LOCAL), and the client realm.</p> </blockquote>
[ { "answer_id": 119689, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "<p>It sounds to me as though you've done everything right.</p>\n\n<p>I'm sure you are but have you made sure you are usi...
2008/09/23
[ "https://Stackoverflow.com/questions/119588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20819/" ]
I've just built a basic ASP MVC web site for deployment on our intranet. It expects users to be on the same domain as the IIS box and if you're not an authenticated Windows User, you should not get access. I've just deployed this to IIS6 running on Server 2003 R2 SP2. The web app is configured with it's own pool with it's own pool user account. The IIS Directory Security options for the web app are set to "Windows Integrated Security" only and the web.config file has: ``` <authentication mode="Windows" /> ``` From a Remote Desktop session on the IIS6 server itself, an IE7 browser window can successfully authenticate and navigate the web app if accessed via <http://localhost/myapp>. However, also from the server, if accessed via the server's name (ie <http://myserver/myapp>) then IE7 presents a credentials dialog which after three attempts entering the correct credentials eventually returns "HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials". The same problem occurs when a workstation browses to the web app url (naturally using the server's name and not "localhost"). The IIS6 server is a member of the only domain we have and has no firewall enabled. Is there something I have failed to configure correctly for this to work? Thanks, --- I have tried the suggestions from Matt Ryan, Graphain, and Mike Dimmick to date without success. I have just built a virtual machine test lab with a Server 2003 DC and a separate server 2003 IIS6 server and I am able to replicate the problem. I am seeing an entry in the IIS6 server's System Event Log the first time I try to access the site via the non-localhost url (ie <http://iis/myapp>). FQDN urls fail too. > > *Source: Kerberos, Event ID: 4* > > The kerberos client received a KRB\_AP\_ERR\_MODIFIED error from the server host/iis.test.local. The target name used was HTTP/iis.test.local. This indicates that the password used to encrypt the kerberos service ticket is different than that on the target server. Commonly, this is due to identically named machine accounts in the target realm (TEST.LOCAL), and the client realm. > > >
After extensive Googling I managed to find a solution on the following MSDN article: [How To: Create a Service Account for an ASP.NET 2.0 Application](http://msdn.microsoft.com/en-us/library/ms998297.aspx) Specifically the Additional Considerations section which describes "Creating Service Principal Names (SPNs) for Domain Accounts" using the setspn tool from the Windows Support Tools: > > setspn -A HTTP/myserver MYDOMAIN\MyPoolUser > > setspn -A HTTP/myserver.fqdn.com MYDOMAIN\MyPoolUser > > > This solved my problem on both my virtual test lab and my original problem server. There is also an important note in the article that using Windows Authentication with custom pool users constrains the associated DNS name to be used by that pool only. That is, another pool with another identity would need to be associated with a different DNS name.
119,609
<p>I have 20 ips from my isp. I have them bound to a router box running centos. What commands, and in what order, do I set up so that the other boxes on my lan, based either on their mac addresses or 192 ips can I have them route out my box on specific ips. For example I want mac addy <code>xxx:xxx:xxx0400</code> to go out <code>72.049.12.157</code> and <code>xxx:xxx:xxx:0500</code> to go out <code>72.049.12.158</code>.</p>
[ { "answer_id": 119655, "author": "Christopher Mahan", "author_id": 479, "author_profile": "https://Stackoverflow.com/users/479", "pm_score": 0, "selected": false, "text": "<p>What's the router hardware and software version?</p>\n\n<p>Are you trying to do this with a linux box? Stop now a...
2008/09/23
[ "https://Stackoverflow.com/questions/119609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8456/" ]
I have 20 ips from my isp. I have them bound to a router box running centos. What commands, and in what order, do I set up so that the other boxes on my lan, based either on their mac addresses or 192 ips can I have them route out my box on specific ips. For example I want mac addy `xxx:xxx:xxx0400` to go out `72.049.12.157` and `xxx:xxx:xxx:0500` to go out `72.049.12.158`.
Use `iptables` to setup `NAT`. ``` iptables -t nat -I POSTROUTING -s 192.168.0.0/24 -j SNAT --to-source 72.049.12.157 iptables -t nat -I POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source 72.049.12.158 ``` This should cause any ips on the `192.168.0.0` subnet to have an 'external' ip of `72.049.12.157` and those on the `192.168.1.0` subnet to have an 'external' ip of `72.049.12.158`. For MAC address matching, use `-m mac --mac-source MAC-ADDRESS` in place of the `-s 192.168.0.0/24` argument Don't forget to activate ip forwarding: ``` cat /proc/sys/net/ipv4/ip_forward ``` If the above returns a `0` then it won't work, you'll have to enable it. Unfortunately this is distro-specific and I don't know CentOS. For a quick hack, do this: ``` echo 1 > /proc/sys/net/ipv4/ip_forward ```
119,627
<p>I'm trying to store an xml serialized object in a cookie, but i get an error like this:</p> <pre><code>A potentially dangerous Request.Cookies value was detected from the client (KundeContextCookie="&lt;?xml version="1.0" ...") </code></pre> <p>I know the problem from similiar cases when you try to store something that looks like javascript code in a form input field.</p> <p>What is the best practise here? Is there a way (like the form problem i described) to supress this warning from the asp.net framework, or should i JSON serialize instead or perhaps should i binary serialize it? What is common practise when storing serialized data in a cookie?</p> <p>EDIT: Thanks for the feedback. The reason i want to store more data in the cookie than the ID is because the object i really need takes about 2 seconds to retreive from a service i have no control over. I made a lightweight object 'KundeContext' to hold a few of the properties from the full object, but these are used 90% of the time. This way i only have to call the slow service on 10% of my pages. If i only stored the Id i would still have to call the service on almost all my pages.</p> <p>I could store all the strings and ints seperately but the object has other lightweight objects like 'contactinformation' and 'address' that would be tedious to manually store for each of their properties.</p>
[ { "answer_id": 119665, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 2, "selected": true, "text": "<p>I wouldn't store data in XML in the cookie - there is a limit on cookie size for starters (used to be 4K for <em>all</em...
2008/09/23
[ "https://Stackoverflow.com/questions/119627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
I'm trying to store an xml serialized object in a cookie, but i get an error like this: ``` A potentially dangerous Request.Cookies value was detected from the client (KundeContextCookie="<?xml version="1.0" ...") ``` I know the problem from similiar cases when you try to store something that looks like javascript code in a form input field. What is the best practise here? Is there a way (like the form problem i described) to supress this warning from the asp.net framework, or should i JSON serialize instead or perhaps should i binary serialize it? What is common practise when storing serialized data in a cookie? EDIT: Thanks for the feedback. The reason i want to store more data in the cookie than the ID is because the object i really need takes about 2 seconds to retreive from a service i have no control over. I made a lightweight object 'KundeContext' to hold a few of the properties from the full object, but these are used 90% of the time. This way i only have to call the slow service on 10% of my pages. If i only stored the Id i would still have to call the service on almost all my pages. I could store all the strings and ints seperately but the object has other lightweight objects like 'contactinformation' and 'address' that would be tedious to manually store for each of their properties.
I wouldn't store data in XML in the cookie - there is a limit on cookie size for starters (used to be 4K for *all* headers including the cookie). Pick a less verbose encoding strategy such as delimiters instead e.g. a|b|c or separate cookie values. Delimited encoding makes it especially easy and fast to decode the values. The error you see is ASP.NET complaining that the headers look like an XSS attack.
119,651
<p>Let me start off with a bit of background.</p> <p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p> <p>A now, for the actual question.</p> <p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p> <p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p> <pre><code>from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) </code></pre> <p>Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.</p>
[ { "answer_id": 119671, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "<p>Why don't you contact CA and ask them to tell them what they're searching for, for that virus?</p>\n\n<p>Or, you coul...
2008/09/23
[ "https://Stackoverflow.com/questions/119651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15109/" ]
Let me start off with a bit of background. This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem. A now, for the actual question. Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing. I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way. ``` from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) ``` Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.
See [the longest common substring problem](http://en.wikipedia.org/wiki/Longest_common_substring_problem). I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays. Using perl [Tree::Suffix](http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm) might be easiest solution. Apparently it gives all common substrings in a specified length range: ``` @lcs = $tree->lcs; @lcs = $tree->lcs($min_len, $max_len); @lcs = $tree->longest_common_substrings; ```
119,669
<p>How can I fetch data in a Winforms application or ASP.NET form from a SAP database? The .NET framework used is 2.0. , language is C# and SAP version is 7.10. </p>
[ { "answer_id": 119671, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "<p>Why don't you contact CA and ask them to tell them what they're searching for, for that virus?</p>\n\n<p>Or, you coul...
2008/09/23
[ "https://Stackoverflow.com/questions/119669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4021/" ]
How can I fetch data in a Winforms application or ASP.NET form from a SAP database? The .NET framework used is 2.0. , language is C# and SAP version is 7.10.
See [the longest common substring problem](http://en.wikipedia.org/wiki/Longest_common_substring_problem). I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays. Using perl [Tree::Suffix](http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm) might be easiest solution. Apparently it gives all common substrings in a specified length range: ``` @lcs = $tree->lcs; @lcs = $tree->lcs($min_len, $max_len); @lcs = $tree->longest_common_substrings; ```
119,679
<p>I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table.</p>
[ { "answer_id": 119704, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 1, "selected": false, "text": "<p>You could try exporting all of your stored procedures into a text file and then use a simple search.</p>\n\n<p>A ...
2008/09/23
[ "https://Stackoverflow.com/questions/119679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table.
``` select so.name, sc.text from sysobjects so inner join syscomments sc on so.id = sc.id where sc.text like '%INSERT INTO xyz%' or sc.text like '%UPDATE xyz%' ``` This will give you a list of all stored procedure contents with INSERT or UPDATE in them for a particular table (you can obviously tweak the query to suit). Also longer procedures will be broken across multiple rows in the returned recordset so you may need to do a bit of manual sifting through the results. **Edit**: Tweaked query to return SP name as well. Also, note the above query will return any UDFs as well as SPs.
119,696
<p>Is there anywhere on the web free vista look and feel theme pack for java?</p>
[ { "answer_id": 119722, "author": "Josh Moore", "author_id": 5004, "author_profile": "https://Stackoverflow.com/users/5004", "pm_score": 0, "selected": false, "text": "<p>If you use SWT it has a native vista look and feel built in. However, if you are using swing I honestly do not know.<...
2008/09/23
[ "https://Stackoverflow.com/questions/119696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15878/" ]
Is there anywhere on the web free vista look and feel theme pack for java?
I'm guessing that what you want is to use the system look and feel regardless on whatever platform your application is started. This can be done with ``` UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); ``` on the main() method (you have to handle possible exceptions of course ;-). As I don't have a vista installation here I can't check whether the jvm natively supports the vista laf... edit: Seems to be possible with the above statement. See this thread in the java forums: <http://forums.sun.com/thread.jspa?threadID=5287193&tstart=345>
119,730
<p>I have a <code>VARCHAR</code> column in a <code>SQL Server 2000</code> database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer. </p> <p>When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order.</p> <pre><code>1 2 10 A B B1 </code></pre> <p>What is the best way to achieve this? </p>
[ { "answer_id": 119780, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 4, "selected": false, "text": "<p>There are a few possible ways to do this.</p>\n\n<p>One would be</p>\n\n<pre><code>SELECT\n ...\nORDER BY\n CASE \n W...
2008/09/23
[ "https://Stackoverflow.com/questions/119730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
I have a `VARCHAR` column in a `SQL Server 2000` database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer. When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order. ``` 1 2 10 A B B1 ``` What is the best way to achieve this?
One possible solution is to pad the numeric values with a character in front so that all are of the same string length. Here is an example using that approach: ```sql select MyColumn from MyTable order by case IsNumeric(MyColumn) when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn else MyColumn end ``` The `100` should be replaced with the actual length of that column.
119,754
<p>I am sending newsletters from a Java server and one of the hyperlinks is arriving missing a period, rendering it useless:</p> <pre><code>Please print your &lt;a href=3D&quot;http://xxxxxxx.xxx.xx.edu= au//newsletter2/3/InnovExpoInviteVIP.pdf&quot;&gt; VIP invitation&lt;/a&gt; for future re= ference and check the Innovation Expo website &lt;a href=3D&quot;http://xxxxxxx.xx= xx.xx.edu.au/2008/&quot;&gt; xxxxxxx.xxxx.xx.edu.au&lt;/a&gt; for updates. </code></pre> <p>In the example above the period was lost between edu and au on the first hyperlink.</p> <p>We have determined that the mail body is being line wrapped and the wrapping splits the line at the period, and that it is illegal to start a line with a period in an SMTP email:</p> <p><a href="https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2</a></p> <p>My question is this - what settings should I be using to ensure that the wrapping is period friendly and/or not performed in the first place?</p> <p>UPDATE: After a <em>lot</em> of testing and debugging it turned out that our code was fine - the client's Linux server had shipped with a <em>very</em> old Java version and the old Mail classes were still in one of the lib folders and getting picked up in preference to ours. JDK prior to 1.2 have this bug.</p>
[ { "answer_id": 119772, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>From an SMTP perspective, you can start a line with a period but you have to send two periods instead. If the SMTP cli...
2008/09/23
[ "https://Stackoverflow.com/questions/119754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ]
I am sending newsletters from a Java server and one of the hyperlinks is arriving missing a period, rendering it useless: ``` Please print your <a href=3D"http://xxxxxxx.xxx.xx.edu= au//newsletter2/3/InnovExpoInviteVIP.pdf"> VIP invitation</a> for future re= ference and check the Innovation Expo website <a href=3D"http://xxxxxxx.xx= xx.xx.edu.au/2008/"> xxxxxxx.xxxx.xx.edu.au</a> for updates. ``` In the example above the period was lost between edu and au on the first hyperlink. We have determined that the mail body is being line wrapped and the wrapping splits the line at the period, and that it is illegal to start a line with a period in an SMTP email: <https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2> My question is this - what settings should I be using to ensure that the wrapping is period friendly and/or not performed in the first place? UPDATE: After a *lot* of testing and debugging it turned out that our code was fine - the client's Linux server had shipped with a *very* old Java version and the old Mail classes were still in one of the lib folders and getting picked up in preference to ours. JDK prior to 1.2 have this bug.
From an SMTP perspective, you can start a line with a period but you have to send two periods instead. If the SMTP client you're using doesn't do this, you may encounter the problem you describe. It might be worth trying an IP sniffer to see where the problem really is. There are likely at least two separate SMTP transactions involved in sending that email.
119,788
<p>Before moving on to use SVN, I used to manage my project by simply keeping a <code>/develop/</code> directory and editing and testing files there, then moving them to the <code>/main/</code> directory. When I decided to move to SVN, I needed to be sure that the directories were indeed in sync.</p> <p>So, what is a good way to write a shell script [ bash ] to recursively compare files with the same name in two different directories?</p> <p>Note: The directory names used above are for sample only. I do not recommend storing your code in the top level :).</p>
[ { "answer_id": 119811, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<p>The diff command has a -r option to recursively compare directories:</p>\n\n<pre><code>diff -r /develop /main\n</code><...
2008/09/23
[ "https://Stackoverflow.com/questions/119788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20386/" ]
Before moving on to use SVN, I used to manage my project by simply keeping a `/develop/` directory and editing and testing files there, then moving them to the `/main/` directory. When I decided to move to SVN, I needed to be sure that the directories were indeed in sync. So, what is a good way to write a shell script [ bash ] to recursively compare files with the same name in two different directories? Note: The directory names used above are for sample only. I do not recommend storing your code in the top level :).
The diff command has a -r option to recursively compare directories: ``` diff -r /develop /main ```
119,792
<p>I've got a Subversion repository, backed by the berkeley DB. Occasionally it breaks down due to some locks and such not being released, but this morning it was impossible to recover it using the 'svnadmin recover' command. Instead it failed with the following error:</p> <pre><code>svnadmin: Berkeley DB error for filesystem 'db' while opening 'nodes' table: Invalid argument svnadmin: bdb: file nodes (meta pgno = 0) has LSN [1083][429767]. svnadmin: bdb: end of log is [1083][354707] svnadmin: bdb: db/nodes: unexpected file type or format </code></pre> <p>I'm going to restore the repository from the last known good backup, but it would be good to know if there is a way this repository could be fixed.</p> <p>edit: even the db_recover utility does not make a difference. It shows recovery is completed, but the same error persists when verifying the repository using svnadmin.</p>
[ { "answer_id": 119798, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>I've got a Subversion repository, backed by the berkeley DB.</p>\n</blockquote>\n\n<p>Sorry to hear th...
2008/09/23
[ "https://Stackoverflow.com/questions/119792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3197/" ]
I've got a Subversion repository, backed by the berkeley DB. Occasionally it breaks down due to some locks and such not being released, but this morning it was impossible to recover it using the 'svnadmin recover' command. Instead it failed with the following error: ``` svnadmin: Berkeley DB error for filesystem 'db' while opening 'nodes' table: Invalid argument svnadmin: bdb: file nodes (meta pgno = 0) has LSN [1083][429767]. svnadmin: bdb: end of log is [1083][354707] svnadmin: bdb: db/nodes: unexpected file type or format ``` I'm going to restore the repository from the last known good backup, but it would be good to know if there is a way this repository could be fixed. edit: even the db\_recover utility does not make a difference. It shows recovery is completed, but the same error persists when verifying the repository using svnadmin.
> > I've got a Subversion repository, backed by the berkeley DB. > > > Sorry to hear that. I would suggest that at your earliest convenience, you dump that repository (`svnadmin dump`) and reload it into a new one backed by FSFS (`svnadmin load`).
119,802
<p>I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:</p> <pre><code>server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() </code></pre> <p>I then have a ServiceRemote class that looks like this:</p> <pre><code>def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) </code></pre> <p>So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:</p> <pre><code>@useDb def select(self, db, fields, **kwargs): pass </code></pre> <p>The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.</p> <p>When I call this method, I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.</p> <hr> <p>Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.</p>
[ { "answer_id": 119943, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 1, "selected": false, "text": "<p>As far as I know, the underlying protocol doesn't support named varargs (or any named args for that matter). The ...
2008/09/23
[ "https://Stackoverflow.com/questions/119802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this: ``` server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() ``` I then have a ServiceRemote class that looks like this: ``` def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) ``` So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs: ``` @useDb def select(self, db, fields, **kwargs): pass ``` The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result. When I call this method, I get the error "**call**() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need. --- Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.
You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, example below: Server ------ ``` from SimpleXMLRPCServer import SimpleXMLRPCServer class Server(object): def __init__(self, hostport): self.server = SimpleXMLRPCServer(hostport) def register_function(self, function, name=None): def _function(args, kwargs): return function(*args, **kwargs) _function.__name__ = function.__name__ self.server.register_function(_function, name) def serve_forever(self): self.server.serve_forever() #example usage server = Server(('localhost', 8000)) def test(arg1, arg2): print 'arg1: %s arg2: %s' % (arg1, arg2) return 0 server.register_function(test) server.serve_forever() ``` Client ------ ``` import xmlrpclib class ServerProxy(object): def __init__(self, url): self._xmlrpc_server_proxy = xmlrpclib.ServerProxy(url) def __getattr__(self, name): call_proxy = getattr(self._xmlrpc_server_proxy, name) def _call(*args, **kwargs): return call_proxy(args, kwargs) return _call #example usage server = ServerProxy('http://localhost:8000') server.test(1, 2) server.test(arg2=2, arg1=1) server.test(1, arg2=2) server.test(*[1,2]) server.test(**{'arg1':1, 'arg2':2}) ```
119,818
<p>I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side.</p>
[ { "answer_id": 119833, "author": "convex hull", "author_id": 10747, "author_profile": "https://Stackoverflow.com/users/10747", "pm_score": 0, "selected": false, "text": "<p>If it's your only checkbox you can do a getElementsByTagName() call to get all inputs and then iterate through the ...
2008/09/23
[ "https://Stackoverflow.com/questions/119818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side.
Here is a thought: As indicated by Anonymous you can generate javascript, if you are in ASP.NET you have some help with the RegisterClientScriptBlock() method. [MSDN on Injecting Client Side Script](http://msdn.microsoft.com/en-us/library/aa478975.aspx) Also you could write, or generate, a javascript function that takes in a checkbox as a parameter and add an onClick attribute to your checkbox definition that calls your function and passes itself as the parameter ``` function TrackMyCheckbox(ck) { //keep track of state } <input type="checkbox" onClick="TrackMyCheckbox(this);".... /> ```
119,819
<p>I need to cleanup the HTML of pasted text into TinyMCE by passing it to a webservice and then getting it back into the textarea. So I need to override the Ctrl+V in TinyMCE to caputre the text, do a background request, and on return continue with whatever the paste handler was for TinyMCE. First off, where is TinyMCE's Ctrl+V handler, and is there a non-destructive way to override it? (instead of changing the source code)</p>
[ { "answer_id": 119901, "author": "Aleksi Yrttiaho", "author_id": 11427, "author_profile": "https://Stackoverflow.com/users/11427", "pm_score": 2, "selected": false, "text": "<p>You could write a plug-in that handles the ctrl+v event and passes it through or modify the paste plug-in. The ...
2008/09/23
[ "https://Stackoverflow.com/questions/119819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to cleanup the HTML of pasted text into TinyMCE by passing it to a webservice and then getting it back into the textarea. So I need to override the Ctrl+V in TinyMCE to caputre the text, do a background request, and on return continue with whatever the paste handler was for TinyMCE. First off, where is TinyMCE's Ctrl+V handler, and is there a non-destructive way to override it? (instead of changing the source code)
You could write a plug-in that handles the ctrl+v event and passes it through or modify the paste plug-in. The following code is found at [plugins/paste/editor\_plugin.js](http://source.ibiblio.org/trac/lyceum/browser/vendor/wordpress/trunk/wp-includes/js/tinymce/plugins/paste/editor_plugin.js?rev=1241) and it handles the ctrl+v event. ``` handleEvent : function(e) { // Force paste dialog if non IE browser if (!tinyMCE.isRealIE && tinyMCE.getParam("paste_auto_cleanup_on_paste", false) && e.ctrlKey && e.keyCode == 86 && e.type == "keydown") { window.setTimeout('tinyMCE.selectedInstance.execCommand("mcePasteText",true)', 1); return tinyMCE.cancelEvent(e); } return true; }, ``` Here is some [more information about creating plug-ins for tinyMCE](http://wiki.moxiecode.com/index.php/TinyMCE:Creating_Plugin).
119,857
<p>I am reading image files in Java using</p> <pre><code>java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath); </code></pre> <p>On some systems this doesn't work, it instead throws an AWTError complaining about sun/awt/motif/MToolkit.</p> <p>How else can you create a java.awt.Image object from an image file?</p>
[ { "answer_id": 119864, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 4, "selected": true, "text": "<p>I read images using <a href=\"http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html\" rel=\"noreferrer\">ImageIO...
2008/09/23
[ "https://Stackoverflow.com/questions/119857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
I am reading image files in Java using ``` java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath); ``` On some systems this doesn't work, it instead throws an AWTError complaining about sun/awt/motif/MToolkit. How else can you create a java.awt.Image object from an image file?
I read images using [ImageIO](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html). ``` Image i = ImageIO.read(InputStream in); ``` The javadoc will offer more info as well.
119,860
<p>Using Visual Studio 2008 Team Edition, is it possible to assign a shortcut key that switches between markup and code? If not, is it possible to assign a shortcut key that goes from code to markup?</p>
[ { "answer_id": 119883, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 3, "selected": true, "text": "<p>The following is a macro taken from a comment by Lozza on <a href=\"https://blog.codinghorror.com/visual-studio-net...
2008/09/23
[ "https://Stackoverflow.com/questions/119860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
Using Visual Studio 2008 Team Edition, is it possible to assign a shortcut key that switches between markup and code? If not, is it possible to assign a shortcut key that goes from code to markup?
The following is a macro taken from a comment by Lozza on <https://blog.codinghorror.com/visual-studio-net-2003-and-2005-keyboard-shortcuts/>. You just need to bind it to a shortcut of your choice: ``` Sub SwitchToMarkup() Dim FileName If (DTE.ActiveWindow.Caption().EndsWith(".cs")) Then ' swith from .aspx.cs to .aspx FileName = DTE.ActiveWindow.Document.FullName.Replace(".cs", "") If System.IO.File.Exists(FileName) Then DTE.ItemOperations.OpenFile(FileName) End If ElseIf (DTE.ActiveWindow.Caption().EndsWith(".aspx")) Then ' swith from .aspx to .aspx.cs FileName = DTE.ActiveWindow.Document.FullName.Replace(".aspx", ".aspx.cs") If System.IO.File.Exists(FileName) Then DTE.ItemOperations.OpenFile(FileName) End If ElseIf (DTE.ActiveWindow.Caption().EndsWith(".ascx")) Then FileName = DTE.ActiveWindow.Document.FullName.Replace(".ascx", ".ascx.cs") If System.IO.File.Exists(FileName) Then DTE.ItemOperations.OpenFile(FileName) End If End If End Sub ```
119,869
<p>Can someone give me some working examples of how you can create, add messages, read from, and destroy a private message queue from C++ APIs? I tried the MSDN pieces of code but i can't make them work properly.</p> <p>Thanks</p>
[ { "answer_id": 120457, "author": "Nevermind", "author_id": 12366, "author_profile": "https://Stackoverflow.com/users/12366", "pm_score": -1, "selected": false, "text": "<p>Not quite sure how you'd go about creating or destroying message queues. Windows should create one per thread. </p>\...
2008/09/23
[ "https://Stackoverflow.com/questions/119869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can someone give me some working examples of how you can create, add messages, read from, and destroy a private message queue from C++ APIs? I tried the MSDN pieces of code but i can't make them work properly. Thanks
Actualy this is the code i was interested in: ``` #include "windows.h" #include "mq.h" #include "tchar.h" HRESULT CreateMSMQQueue( LPWSTR wszPathName, PSECURITY_DESCRIPTOR pSecurityDescriptor, LPWSTR wszOutFormatName, DWORD *pdwOutFormatNameLength ) { // Define the maximum number of queue properties. const int NUMBEROFPROPERTIES = 2; // Define a queue property structure and the structures needed to initialize it. MQQUEUEPROPS QueueProps; MQPROPVARIANT aQueuePropVar[NUMBEROFPROPERTIES]; QUEUEPROPID aQueuePropId[NUMBEROFPROPERTIES]; HRESULT aQueueStatus[NUMBEROFPROPERTIES]; HRESULT hr = MQ_OK; // Validate the input parameters. if (wszPathName == NULL || wszOutFormatName == NULL || pdwOutFormatNameLength == NULL) { return MQ_ERROR_INVALID_PARAMETER; } DWORD cPropId = 0; aQueuePropId[cPropId] = PROPID_Q_PATHNAME; aQueuePropVar[cPropId].vt = VT_LPWSTR; aQueuePropVar[cPropId].pwszVal = wszPathName; cPropId++; WCHAR wszLabel[MQ_MAX_Q_LABEL_LEN] = L"Test Queue"; aQueuePropId[cPropId] = PROPID_Q_LABEL; aQueuePropVar[cPropId].vt = VT_LPWSTR; aQueuePropVar[cPropId].pwszVal = wszLabel; cPropId++; QueueProps.cProp = cPropId; // Number of properties QueueProps.aPropID = aQueuePropId; // IDs of the queue properties QueueProps.aPropVar = aQueuePropVar; // Values of the queue properties QueueProps.aStatus = aQueueStatus; // Pointer to the return status WCHAR wszFormatNameBuffer[256]; DWORD dwFormatNameBufferLength = sizeof(wszFormatNameBuffer)/sizeof(wszFormatNameBuffer[0]); hr = MQCreateQueue(pSecurityDescriptor, // Security descriptor &QueueProps, // Address of queue property structure wszFormatNameBuffer, // Pointer to format name buffer &dwFormatNameBufferLength); // Pointer to receive the queue's format name length if (hr == MQ_OK || hr == MQ_INFORMATION_PROPERTY) { if (*pdwOutFormatNameLength >= dwFormatNameBufferLength) { wcsncpy_s(wszOutFormatName, *pdwOutFormatNameLength - 1, wszFormatNameBuffer, _TRUNCATE); wszOutFormatName[*pdwOutFormatNameLength - 1] = L'\0'; *pdwOutFormatNameLength = dwFormatNameBufferLength; } else { wprintf(L"The queue was created, but its format name cannot be returned.\n"); } } return hr; } ``` This presumably creates a queue... but there are some parts missing for this to work, that's why i need a simple example that works.
119,941
<p>I want to create variables inside function from dictionary.</p> <p>Lets say I have a dictionary</p> <pre><code>bar = {'a': 1, 'b': 2, 'c': 3} </code></pre> <p>and function</p> <pre><code>def foo(): pass </code></pre> <p>What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values</p> <p>So in the end it should be similar to</p> <pre><code>def foo(): a = 1 b = 2 c = 3 </code></pre> <p>Is it possible at all? And if it does, how to do such thing?</p>
[ { "answer_id": 119964, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 1, "selected": false, "text": "<p>Why would you want to do such a thing? Unless you actually do anything with the variables inside the function, a function ...
2008/09/23
[ "https://Stackoverflow.com/questions/119941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20955/" ]
I want to create variables inside function from dictionary. Lets say I have a dictionary ``` bar = {'a': 1, 'b': 2, 'c': 3} ``` and function ``` def foo(): pass ``` What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values So in the end it should be similar to ``` def foo(): a = 1 b = 2 c = 3 ``` Is it possible at all? And if it does, how to do such thing?
Your question is not clear. If you want to "set" said variables when foo is not running, no, you can't. There is no frame object yet to "set" the local variables in. If you want to do that in the function body, you shouldn't (check the [python documentation](http://docs.python.org/lib/built-in-funcs.html) for locals()). However, you *could* do a `foo.__dict__.update(bar)`, and then you could access those variables even from inside the function as foo.a, foo.b and foo.c. The question is: why do you want to do that, and why isn't a class more suitable for your purposes?
119,961
<p>Normally you can do this:</p> <pre><code>&lt;select size="3"&gt; &lt;option&gt;blah&lt;/option&gt; &lt;option&gt;blah&lt;/option&gt; &lt;option&gt;blah&lt;/option&gt; &lt;/select&gt; </code></pre> <p>And it would render as a selectionbox where all three options are visible (without dropping down)<br> I'm looking for a way to set this size attribute from css.</p>
[ { "answer_id": 119977, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": -1, "selected": false, "text": "<p>I do not believe this is possible no</p>\n" }, { "answer_id": 119988, "author": "pilif", "author_id": ...
2008/09/23
[ "https://Stackoverflow.com/questions/119961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
Normally you can do this: ``` <select size="3"> <option>blah</option> <option>blah</option> <option>blah</option> </select> ``` And it would render as a selectionbox where all three options are visible (without dropping down) I'm looking for a way to set this size attribute from css.
There ins't an option for setting the size, but if you do set the size some browsers will let you set the width/height properties to whatever you want via CSS. Some = Firefox, Chrome, Safari, Opera. Not much works in IE though (no surprise) You could though, if you wanted, use CSS expressions in IE, to check if the size attribute is set, and if so, run JS to (re)set it to the size you want... e.g. ``` size = options.length; ```
119,971
<p>I'm trying to run Selenium RC against my ASP.NET code running on a Cassini webserver.</p> <p>The web application works when i browse it directly but when running through Selenium I get </p> <p>HTTP ERROR: 403<br> Forbidden for Proxy</p> <hr> <p>Running Selenium i interactive mode I start a new session with: </p> <pre>cmd=getNewBrowserSession&1=*iexplore&2=http://localhost:81/ cmd=open&1=http://localhost:81/default.aspx&sessionId=199578 </pre> <p>I get the above error in the Selenium browser, the command window tells me OK.</p> <hr> <p>Any input?</p>
[ { "answer_id": 121055, "author": "HAXEN", "author_id": 11434, "author_profile": "https://Stackoverflow.com/users/11434", "pm_score": 1, "selected": false, "text": "<p>I think the problem is that both Selenium and the webserver is running on localhost.<br>\nIt works if I run with the \"ie...
2008/09/23
[ "https://Stackoverflow.com/questions/119971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11434/" ]
I'm trying to run Selenium RC against my ASP.NET code running on a Cassini webserver. The web application works when i browse it directly but when running through Selenium I get HTTP ERROR: 403 Forbidden for Proxy --- Running Selenium i interactive mode I start a new session with: ``` cmd=getNewBrowserSession&1=*iexplore&2=http://localhost:81/ cmd=open&1=http://localhost:81/default.aspx&sessionId=199578 ``` I get the above error in the Selenium browser, the command window tells me OK. --- Any input?
I think the problem is that both Selenium and the webserver is running on localhost. It works if I run with the "iehta" instead of "iexplore".
119,980
<p>Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?</p> <p>I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.</p> <p><strong>Edit:</strong> From link provided in accepted answer:</p> <p>Include Silverlight.js (from Silverlight SDK)</p> <pre><code>Silverlight.isInstalled("2.0"); </code></pre>
[ { "answer_id": 119992, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 5, "selected": true, "text": "<p>Include Silverlight.js (from Silverlight SDK)</p>\n\n<p><code>Silverlight.isInstalled(\"4.0\")</code></p>\n\n<hr>\n\n<p><s...
2008/09/23
[ "https://Stackoverflow.com/questions/119980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser? I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load. **Edit:** From link provided in accepted answer: Include Silverlight.js (from Silverlight SDK) ``` Silverlight.isInstalled("2.0"); ```
Include Silverlight.js (from Silverlight SDK) `Silverlight.isInstalled("4.0")` --- **Resource:** [<http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx>](http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx)
120,001
<p>I am looking for a free tool to load Excel data sheet into an Oracle database. I tried the Oracle SQL developer, but it keeps throwing a NullPointerException. Any ideas?</p>
[ { "answer_id": 120021, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "<p>Excel -> CSV -> Oracle</p>\n\n<p>Save the Excel spreadsheet as file type 'CSV' (Comma-Separated Values).</p>\n\n<p>Tran...
2008/09/23
[ "https://Stackoverflow.com/questions/120001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233512/" ]
I am looking for a free tool to load Excel data sheet into an Oracle database. I tried the Oracle SQL developer, but it keeps throwing a NullPointerException. Any ideas?
Excel -> CSV -> Oracle Save the Excel spreadsheet as file type 'CSV' (Comma-Separated Values). Transfer the .csv file to the Oracle server. Create the Oracle table, using the SQL `CREATE TABLE` statement to define the table's column lengths and types. Use sqlload to load the .csv file into the Oracle table. Create a sqlload control file like this: ``` load data infile theFile.csv replace into table theTable fields terminated by ',' (x,y,z) ``` Invoke sqlload to read the .csv file into the new table, creating one row in the table for each line in the .csv file. This is done as a Unix command: ``` % sqlload userid=username/password control=<filename.ctl> log=<filename>.log ``` **OR** If you just want a tool, use [QuickLoad](http://sourceforge.net/projects/quickload)
120,016
<p>I have the following XML structure:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;course xml:lang="nl"&gt; &lt;body&gt; &lt;item id="787900813228567" view="12000" title="0x|Beschrijving" engtitle="0x|Description"&gt;&lt;![CDATA[Dit college leert studenten hoe ze een onderzoek kunn$ &lt;item id="5453116633894965" view="12000" title="0x|Onderwijsvorm" engtitle="0x|Method of instruction"&gt;&lt;![CDATA[instructiecollege]]&gt;&lt;/item&gt; &lt;item id="7433550075448316" view="12000" title="0x|Toetsing" engtitle="0x|Examination"&gt;&lt;![CDATA[Opdrachten/werkstuk]]&gt;&lt;/item&gt; &lt;item id="015071401858970545" view="12000" title="0x|Literatuur" engtitle="0x|Required reading"&gt;&lt;![CDATA[Wayne C. Booth, Gregory G. Colomb, Joseph M. Wi$ &lt;item id="5960589172957031" view="12000" title="0x|Uitbreiding" engtitle="0x|Expansion"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="3610066867901779" view="12000" title="0x|Aansluiting" engtitle="0x|Place in study program"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="19232369892482925" view="12000" title="0x|Toegangseisen" engtitle="0x|Course requirements"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="3332396346891524" view="12000" title="0x|Doelgroep" engtitle="0x|Target audience"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="6606851872934866" view="12000" title="0x|Aanmelden bij" engtitle="0x|Enrollment at"&gt;&lt;![CDATA[]]&gt;&lt;/item&gt; &lt;item id="1478643580820973" view="12000" title="0x|Informatie bij" engtitle="0x|Information at"&gt;&lt;![CDATA[Docent]]&gt;&lt;/item&gt; &lt;item id="9710608434763993" view="12000" title="0x|Rooster" engtitle="0x|Schedule"&gt;&lt;![CDATA[1e semester, maandag 15.00-17.00, zaal 1175/030]]&gt;&lt;/item&gt; &lt;/body&gt; &lt;/course&gt; </code></pre> <p>I want to get the data from one of the item tags. To get to this tag, I use the following xpath:</p> <pre><code>$description = $xml-&gt;xpath("//item[@title='0x|Beschrijving']"); </code></pre> <p>This does indeed return an array in the form of:</p> <pre><code>Array ( [0] =&gt; SimpleXMLElement Object ( [@attributes] =&gt; Array ( [id] =&gt; 787900813228567 [view] =&gt; 12000 [title] =&gt; 0x|Beschrijving [engtitle] =&gt; 0x|Description ) ) ) </code></pre> <p>But where is the actual information (that is stored between the item tags) located? I must be doing something wrong, but I can't figure out what that might be... Probably something really simple... Help would be appreciated.</p>
[ { "answer_id": 120069, "author": "Marc Gear", "author_id": 6563, "author_profile": "https://Stackoverflow.com/users/6563", "pm_score": 2, "selected": false, "text": "<p>I believe its equivalent to the __toString() method on the object, so </p>\n\n<pre><code>echo $description[0];\n</code>...
2008/09/23
[ "https://Stackoverflow.com/questions/120016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18922/" ]
I have the following XML structure: ``` <?xml version="1.0" ?> <course xml:lang="nl"> <body> <item id="787900813228567" view="12000" title="0x|Beschrijving" engtitle="0x|Description"><![CDATA[Dit college leert studenten hoe ze een onderzoek kunn$ <item id="5453116633894965" view="12000" title="0x|Onderwijsvorm" engtitle="0x|Method of instruction"><![CDATA[instructiecollege]]></item> <item id="7433550075448316" view="12000" title="0x|Toetsing" engtitle="0x|Examination"><![CDATA[Opdrachten/werkstuk]]></item> <item id="015071401858970545" view="12000" title="0x|Literatuur" engtitle="0x|Required reading"><![CDATA[Wayne C. Booth, Gregory G. Colomb, Joseph M. Wi$ <item id="5960589172957031" view="12000" title="0x|Uitbreiding" engtitle="0x|Expansion"><![CDATA[]]></item> <item id="3610066867901779" view="12000" title="0x|Aansluiting" engtitle="0x|Place in study program"><![CDATA[]]></item> <item id="19232369892482925" view="12000" title="0x|Toegangseisen" engtitle="0x|Course requirements"><![CDATA[]]></item> <item id="3332396346891524" view="12000" title="0x|Doelgroep" engtitle="0x|Target audience"><![CDATA[]]></item> <item id="6606851872934866" view="12000" title="0x|Aanmelden bij" engtitle="0x|Enrollment at"><![CDATA[]]></item> <item id="1478643580820973" view="12000" title="0x|Informatie bij" engtitle="0x|Information at"><![CDATA[Docent]]></item> <item id="9710608434763993" view="12000" title="0x|Rooster" engtitle="0x|Schedule"><![CDATA[1e semester, maandag 15.00-17.00, zaal 1175/030]]></item> </body> </course> ``` I want to get the data from one of the item tags. To get to this tag, I use the following xpath: ``` $description = $xml->xpath("//item[@title='0x|Beschrijving']"); ``` This does indeed return an array in the form of: ``` Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 787900813228567 [view] => 12000 [title] => 0x|Beschrijving [engtitle] => 0x|Description ) ) ) ``` But where is the actual information (that is stored between the item tags) located? I must be doing something wrong, but I can't figure out what that might be... Probably something really simple... Help would be appreciated.
When you load the XML file, you'll need to handle the CDATA.. This example works: ``` <?php $xml = simplexml_load_file('file.xml', NULL, LIBXML_NOCDATA); $description = $xml->xpath("//item[@title='0x|Beschrijving']"); var_dump($description); ?> ``` Here's the output: ``` array(1) { [0]=> object(SimpleXMLElement)#2 (2) { ["@attributes"]=> array(4) { ["id"]=> string(15) "787900813228567" ["view"]=> string(5) "12000" ["title"]=> string(15) "0x|Beschrijving" ["engtitle"]=> string(14) "0x|Description" } [0]=> string(41) "Dit college leert studenten hoe ze een on" } } ```